问:
Redirecting with ajax but instead of redirect, my array is echoing
I'm trying to redirect the page after using ajax to validate my form. The problem is that instead of redirect or validation when I click the signup button I get a page with the text:

```<code>{"status":true,"message":"error","redirect":"..\/login-error-page.php"}
</code>```

And in my error log:

```<code>[07-Jun-2017 01:04:24 UTC] PHP Notice:  Undefined variable: errorEmpty in include/signup.inc.php

[07-Jun-2017 01:04:24 UTC] PHP Notice:  Undefined variable: errorEmail in include/signup.inc.php
</code>```

Can anyone tell me what's wrong? I am new to ajax. Thanks in advance.

Index.php:

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Yahbang</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
    <script>
        $(document).on('submit', '.signup-message', function () {

            $("#signup-form").submit(function (event) {
                event.preventDefault();
                var first  = $("#signup-first").val();
                var last   = $("#signup-last").val();
                var email  = $("#signup-email").val();
                var pwd    = $("#signup-pwd").val();
                var submit = $("#signup-submit").val();

                $.ajax({
                    url:      'include/signup.inc.php',
                    type:     'POST',
                    data:     {first: first, last: last, email: email, pwd: pwd, submit: submit},
                    datatype: 'json',
                    success:  function (respond) {
                        if (!respond.status) {
                            alert(respond.message);
                        }
                        else
                            Window.Location.href = respond.redirect;
                    }
                });
            });
        });

    </script>
</head>
<body>
<header>
    <div class="header_index">
        <div class="headerlogo">
            <nav>
                <ul>
                    <li><a href="index.php">Yahbang</a></li>
                </ul>
            </nav>
        </div>

        <form id="login-form" class="loginform" action='include/login.inc.php' method='POST'>
            <input id="login-email" type='text' name='email' placeholder='Email'>
            <input id="login-pwd" type='password' name='pwd' placeholder='Password'>
            <p><a href="forgotpassword.php">Forgot Password</a></p>
            <button id="login-submit" type='submit'>Login</button>
            <p class="login-message"></p>
        </form>
    </div>
</header>

<form id="signup-form" class="signup" action='include/signup.inc.php' method='POST'>
    <input id="signup-first" type='text' name='first' placeholder='First Name'><br>
    <input id="signup-last" type='text' name='last' placeholder='Last Name'><br>
    <input id="signup-email" type='text' name='email' placeholder='Email'><br>
    <input id="signup-pwd" type='password' name='pwd' placeholder='Password'><br>
    <button id="signup-submit" type='submit'>Sign Up</button>
    <p class="signup-message"></p>
</form>

<footer>
    <div class="footer_index">
        <nav>
            <ul>
                <li><a href="contact.php">Contact Us</a></li>
                <li><a href="TermsofUse.php">Terms of Use</a></li>
            </ul>
        </nav>
    </div>
</footer>
</body>
</html>
</code>```

signup.inc.php:

```<code><?php
session_start();
include '../dbh.php';

$respond = [
    'status'   => true,
    'message'  => 'error',
    'redirect' => '../profile.php',
];

echo json_encode($respond);

if (isset($_POST['submit'])) {

    $first = mysqli_real_escape_string($conn, $_POST['first']);
    $last  = mysqli_real_escape_string($conn, $_POST['last']);
    $email = mysqli_real_escape_string($conn, $_POST['email']);
    $pwd   = mysqli_real_escape_string($conn, $_POST['pwd']);

    $errorEmpty = false;
    $errorEmail = false;

    if (empty($first) || empty($last) || empty($email) || empty($pwd)) {
        echo "<span class='signup-error'>Please fill out all fields!</span>";
        $errorEmpty = true;
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "<span class='signup-error'>Please enter a valid email address!</span>";
        $errorEmail = true;
    } else {
        $sql        = "SELECT email FROM user WHERE email='$email'";
        $result     = mysqli_query($conn, $sql);
        $emailcheck = mysqli_num_rows($result);

        if ($emailcheck > 0) {
            echo "<span class='signup-error'>That email address already exists!</span>";
            $errorEmail = true;
        } else {
            $encryptpwd = password_hash($pwd, PASSWORD_DEFAULT);
            $sql        = "INSERT INTO user (first, last, email, pwd)
        VALUES ('$first', '$last', '$email', '$encryptpwd')";
            $result     = mysqli_query($conn, $sql);
        }
    }
}
?>

<script>
    $("#signup-first, #signup-last, #signup-email, #signup-pwd").removeClass("input-error");

    var errorEmpty = "<?php echo $errorEmpty; ?>";
    var errorEmail = "<?php echo $errorEmail; ?>";

    if (errorEmpty == true) {
        $("#signup-first, #signup-last, #signup-email, #signup-pwd").addClass("input-error");
    }

    if (errorEmail == true) {
        $("#signup-email").addClass("input-error");
    }

    if (errorEmpty == false && errorEmail == false) {
        $("#signup-first, #signup-last, #signup-email, #signup-pwd").val("");
    }
</script>
</code>```

答:
Hi try to add error in ajax to simulate error response from php

```<code>$.ajax({
    url: 'include/signup.inc.php',
    type: 'POST',
    data: {first: first, last: last, email: email, pwd: pwd, submit: submit},
    datatype: 'json',
    success: function(respond){
        if (!respond.status)
        {
            alert(respond.message);
        }
        else
            Window.Location.href = respond.redirect;
    },
    error: function(error){
        //methods here
    }
});
</code>```

Body:
I'm trying to redirect the page after using ajax to validate my form. The problem is that instead of redirect or validation when I click the signup button I get a page with the text:

{"status":true,"message":"error","redirect":"..\/login-error-page.php"}

And in my error log:

[07-Jun-2017 01:04:24 UTC] PHP Notice:  Undefined variable: errorEmpty in include/signup.inc.php

[07-Jun-2017 01:04:24 UTC] PHP Notice:  Undefined variable: errorEmail in include/signup.inc.php

Can anyone tell me what's wrong? I am new to ajax. Thanks in advance.

Index.php:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Yahbang</title>
    <link rel="stylesheet" type="text/css" href="style.css">

Yahbang

        <form id="login-form" class="loginform" action='include/login.inc.php' method='POST'>
            <input id="login-email" type='text' name='email' placeholder='Email'>
            <input id="login-pwd" type='password' name='pwd' placeholder='Password'>

Forgot Password

            <button id="login-submit" type='submit'>Login</button>

        </form>

<form id="signup-form" class="signup" action='include/signup.inc.php' method='POST'>
    <input id="signup-first" type='text' name='first' placeholder='First Name'>

    <input id="signup-last" type='text' name='last' placeholder='Last Name'>

    <input id="signup-email" type='text' name='email' placeholder='Email'>

    <input id="signup-pwd" type='password' name='pwd' placeholder='Password'>

    <button id="signup-submit" type='submit'>Sign Up</button>

</form>

Contact Us

Terms of Use

signup.inc.php:

<?php
session_start();
include '../dbh.php';

$respond = [
    'status'   => true,
    'message'  => 'error',
    'redirect' => '../profile.php',
];

echo json_encode($respond);

if (isset($_POST['submit'])) {

    $first = mysqli_real_escape_string($conn, $_POST['first']);
    $last  = mysqli_real_escape_string($conn, $_POST['last']);
    $email = mysqli_real_escape_string($conn, $_POST['email']);
    $pwd   = mysqli_real_escape_string($conn, $_POST['pwd']);

    $errorEmpty = false;
    $errorEmail = false;

    if (empty($first) || empty($last) || empty($email) || empty($pwd)) {
        echo "Please fill out all fields!";
        $errorEmpty = true;
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "Please enter a valid email address!";
        $errorEmail = true;
    } else {
        $sql        = "SELECT email FROM user WHERE email='$email'";
        $result     = mysqli_query($conn, $sql);
        $emailcheck = mysqli_num_rows($result);

        if ($emailcheck > 0) {
            echo "That email address already exists!";
            $errorEmail = true;
        } else {
            $encryptpwd = password_hash($pwd, PASSWORD_DEFAULT);
            $sql        = "INSERT INTO user (first, last, email, pwd)
        VALUES ('$first', '$last', '$email', '$encryptpwd')";
            $result     = mysqli_query($conn, $sql);
        }
    }
}
?>

Body:
Hi try to add error in ajax to simulate error response from php

$.ajax({
    url: 'include/signup.inc.php',
    type: 'POST',
    data: {first: first, last: last, email: email, pwd: pwd, submit: submit},
    datatype: 'json',
    success: function(respond){
        if (!respond.status)
        {
            alert(respond.message);
        }
        else
            Window.Location.href = respond.redirect;
    },
    error: function(error){
        //methods here
    }
});


来源: stackexchange

问:
Converting set of integers to a bitarray for memory-efficient lookup
I have a set of 150M integers in Python that I'd like to use for filtering data. Each of these integers is a "user ID" stored in a 32-bit format and I want to remove any users that are in the set. The set is too big as I need to transfer it to lots of workers on a cluster, where each worker has a limited amount of memory. Seeing as I only need a binary value (user is set / not in set) it seems feasible to do this using a bitarray.

The IDs start at 0 and finish at roughly 300M (i.e. half the users are in the set). The entire bitarray should be set to False (i.e. 0) except for the locations that are contained in the set of ints.

I've looked at the bitstring package and the bitarray package, but I'm not sure which is better for my purpose and how I should go about it. Can anyone provide some guidance or a small example of how to convert my set to a bitarray and then do a lookup using it?

答:
Personally I prefer bitarray and assuming you have such a set (only larger):

```<code># Just some random set
myset = {5, 27, 142, 824}
</code>```

Then you could use bitarray to create a bitarray (of appropriate length) containing only False:

```<code>from bitarray import bitarray
ba = bitarray(1000)  # length 1000
ba.setall(False)     # contains only zeros
</code>```

However there's no native support for creating one from a set, so you'll need a loop to set the appropriate values:

```<code>for item in myset:
    ba[item] = True
</code>```

And you could check if the value by indexing:

```<code>print(ba[5])   # True
print(ba[6])   # False
print(ba[27])  # True
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Personally I prefer bitarray and assuming you have such a set (only larger):

# Just some random set
myset = {5, 27, 142, 824}

Then you could use bitarray to create a bitarray (of appropriate length) containing only False:

from bitarray import bitarray
ba = bitarray(1000)  # length 1000
ba.setall(False)     # contains only zeros

However there's no native support for creating one from a set, so you'll need a loop to set the appropriate values:

for item in myset:
    ba[item] = True

And you could check if the value by indexing:

print(ba[5])   # True
print(ba[6])   # False
print(ba[27])  # True


问:
There is a error:1464 when I using the SQL Server 2016 "New Availability Group"
The last step of "AlwaysOn High Availability wizard", when joining database A to availability group AG on one server.

The error info is:

Database A is not in a recovering state which is required for a mirror database or secondary database.The remote database must be restored using WITH NORECOVERY.(Microsoft SQL Server,Error:1464)

Do you have any suggestion?

答:
There is a requirement that DB must be restored on secondary replicas with NORECOVERY option.

See https://learn.microsoft.com/en-us/sql/database-engine/availability-groups/windows/manually-prepare-a-secondary-database-for-an-availability-group-sql-server


问:
Is there anything like !in_array()?
$file_name = "smith.jpg" // This gives error 'Invalid file extension'
What could be the problem?</p>

```<code>$whitelist = array('jpg', 'png', 'gif', 'jpeg');

// Validate file extension
    if(!in_array(end(explode('.', $file_name)), $whitelist))
        HandleError('Invalid file extension');
</code>```

答:
It would have been better if you used:

```<code>echo pathinfo('/www/htdocs/your_image.jpg', PATHINFO_EXTENSION);
</code>```

use the right functions for what they are made for.

ContentLicense: CC BY-SA 2.5

Title: Is there anything like !in_array()?

Body:
$file_name = "smith.jpg" // This gives error 'Invalid file extension'
What could be the problem?

$whitelist = array('jpg', 'png', 'gif', 'jpeg');

// Validate file extension
    if(!in_array(end(explode('.', $file_name)), $whitelist))
        HandleError('Invalid file extension');

Body:
It would have been better if you used:

echo pathinfo('/www/htdocs/your_image.jpg', PATHINFO_EXTENSION);

use the right functions for what they are made for.


问:
Primary and Secondary axis VBA
I am attempting to plot two time series on Primary and Secondary axis on one chart with  following code:

```<code>   Set ARng_1 = range("Annual_Series_1")
   Set MRng_1 = range("Monthly_Series_1")
   Sheet10.ChartObjects("Chart 17").Activate
   With ActiveChart
  .ChartType = xlLineMarkers
  .SeriesCollection.Add Source:=ARng_1
  .SeriesCollection.Add Source:=MRng_1
  .Axes(xlCategory, xlPrimary).HasTitle = True
  .Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = "Dates"
  .SeriesCollection(1).Axes(xlValue, xlPrimary).HasTitle = True
  .SeriesCollection(2).Axes(xlValue, xlSecondary).HasTitle = True
  .SeriesCollection(1).Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "Annual"
  .SeriesCollection(2).Axes(xlValue, xlSecondary).AxisTitle.Characters.Text = "Monthly"
  .Axes(xlCategory).HasMajorGridlines = True
  .SeriesCollection(1).Format.Line.ForeColor.RGB = RGB(255, 0, 0)
  .SeriesCollection(2).Format.Line.ForeColor.RGB = RGB(255, 0, 0)
  .SeriesCollection(1).XValues = Date_Rng
  End With
</code>```

I keep getting an error ("object doesn't support this property or object") at the line:

```<code>  .SeriesCollection(1).Axes(xlValue, xlPrimary).HasTitle = True
</code>```

What am I doing wrong here? Also, am I treating the axis correctly?  Am I going about this correctly?

Thanks!!!!!

答:
I think yourt code is to be like bellow..</p>

```<code>   Set ARng_1 = Range("Annual_Series_1")
   Set MRng_1 = Range("Monthly_Series_1")

      With ActiveChart
        For i = .SeriesCollection.Count To 1 Step -1
              .SeriesCollection(i).Delete
        Next i
        .ChartType = xlLineMarkers
        .SeriesCollection.Add Source:=ARng_1
        .SeriesCollection.Add Source:=MRng_1
        .SeriesCollection(2).AxisGroup = 2
        .Axes(xlCategory, xlPrimary).HasTitle = True
        .Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = "Dates"
        .Axes(xlValue, xlPrimary).HasTitle = True
        .Axes(xlValue, xlSecondary).HasTitle = True
        .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "Annual"
        .Axes(xlValue, xlSecondary).AxisTitle.Characters.Text = "Monthly"
        .Axes(xlCategory).HasMajorGridlines = True
        .SeriesCollection(1).Format.Line.ForeColor.RGB = RGB(255, 0, 0)
        .SeriesCollection(2).Format.Line.ForeColor.RGB = RGB(255, 0, 0)
        .SeriesCollection(1).XValues = date_rng
      End With
</code>```

Title: Primary and Secondary axis VBA

Body:
I am attempting to plot two time series on Primary and Secondary axis on one chart with  following code:

   Set ARng_1 = range("Annual_Series_1")
   Set MRng_1 = range("Monthly_Series_1")
   Sheet10.ChartObjects("Chart 17").Activate
   With ActiveChart
  .ChartType = xlLineMarkers
  .SeriesCollection.Add Source:=ARng_1
  .SeriesCollection.Add Source:=MRng_1
  .Axes(xlCategory, xlPrimary).HasTitle = True
  .Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = "Dates"
  .SeriesCollection(1).Axes(xlValue, xlPrimary).HasTitle = True
  .SeriesCollection(2).Axes(xlValue, xlSecondary).HasTitle = True
  .SeriesCollection(1).Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "Annual"
  .SeriesCollection(2).Axes(xlValue, xlSecondary).AxisTitle.Characters.Text = "Monthly"
  .Axes(xlCategory).HasMajorGridlines = True
  .SeriesCollection(1).Format.Line.ForeColor.RGB = RGB(255, 0, 0)
  .SeriesCollection(2).Format.Line.ForeColor.RGB = RGB(255, 0, 0)
  .SeriesCollection(1).XValues = Date_Rng
  End With

I keep getting an error ("object doesn't support this property or object") at the line:

  .SeriesCollection(1).Axes(xlValue, xlPrimary).HasTitle = True

What am I doing wrong here? Also, am I treating the axis correctly?  Am I going about this correctly?

Thanks!!!!!

Body:
I think yourt code is to be like bellow..

   Set ARng_1 = Range("Annual_Series_1")
   Set MRng_1 = Range("Monthly_Series_1")

      With ActiveChart
        For i = .SeriesCollection.Count To 1 Step -1
              .SeriesCollection(i).Delete
        Next i
        .ChartType = xlLineMarkers
        .SeriesCollection.Add Source:=ARng_1
        .SeriesCollection.Add Source:=MRng_1
        .SeriesCollection(2).AxisGroup = 2
        .Axes(xlCategory, xlPrimary).HasTitle = True
        .Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = "Dates"
        .Axes(xlValue, xlPrimary).HasTitle = True
        .Axes(xlValue, xlSecondary).HasTitle = True
        .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "Annual"
        .Axes(xlValue, xlSecondary).AxisTitle.Characters.Text = "Monthly"
        .Axes(xlCategory).HasMajorGridlines = True
        .SeriesCollection(1).Format.Line.ForeColor.RGB = RGB(255, 0, 0)
        .SeriesCollection(2).Format.Line.ForeColor.RGB = RGB(255, 0, 0)
        .SeriesCollection(1).XValues = date_rng
      End With


问:
unity convert a float to a vector3 c#
Here is my error message:

Assets/BanditLogic.cs(45,30): error CS0029: Cannot implicitly convert
  type 'float' to 'UnityEngine.Vector3'

And here is a section of the code:

```<code>Vector3 Distance = Vector3.Distance (player.transform.position,bandit.transform.position);
anim.SetFloat ("DistanceToPlayer", Distance);
</code>```

I'm trying to find the distance to the enemy from the player, if there are any easier ways please let me know.

答:
You're on the right track. You assigned your variable to a vector3 instead of a float.

```<code>float Distance = Vector3.Distance (player.transform.position,bandit.transform.position);
anim.SetFloat ("DistanceToPlayer", Distance);
</code>```

this should work

Title: unity convert a float to a vector3 c#

Body:
Here is my error message:

Assets/BanditLogic.cs(45,30): error CS0029: Cannot implicitly convert
  type 'float' to 'UnityEngine.Vector3'

And here is a section of the code:

Vector3 Distance = Vector3.Distance (player.transform.position,bandit.transform.position);
anim.SetFloat ("DistanceToPlayer", Distance);

I'm trying to find the distance to the enemy from the player, if there are any easier ways please let me know.

Body:
You're on the right track. You assigned your variable to a vector3 instead of a float.

float Distance = Vector3.Distance (player.transform.position,bandit.transform.position);
anim.SetFloat ("DistanceToPlayer", Distance);

this should work


问:
Capture API works bad in dark especially in night time or in previewing dark corners through camera
I was using this library which is https://github.com/CosmicMind/Material. Everything is already working well aside from one which requires a bit of optimization,

I've tried this one which works pretty well with improved lighting in the dark, it is pretty much useful for devices that don't have flash such as iPads.

https://github.com/ooper-shlab/AVCamManual-Swift

I can't seem to get where the lighting optimization happens in the code. I would've help if I have figured out.

The preview really would look a lot darker using the Capture API of material.

Screenshots of each can be seen below:
The demo for Material's Capture Api:

The demo for AVFoundation:

答: Based on the given answer above by @Jojo Narté, the correct usage of the API would be to set the Capture.capturePreset value to .presetPhoto.


问:
TypeLoadException with DocumentClient on Visual Studio Mac
I downloaded the getting started sample app from Azure Cosmos DB and am getting the following error with Visual Studio Mac

```<code>System.TypeLoadException: Could not resolve type with token 010000f6 (from typeref, class/assembly System.Diagnostics.Eventing.EventProviderTraceListener, System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
  at Microsoft.Azure.Documents.Client.DocumentClient.Initialize (System.Uri serviceEndpoint, Microsoft.Azure.Documents.Client.ConnectionPolicy connectionPolicy, System.Nullable`1[T] desiredConsistencyLevel) [0x00014] in <f7f11c3ada88490092c73d6bef54be97>:0
  at Microsoft.Azure.Documents.Client.DocumentClient..ctor (System.Uri serviceEndpoint, System.String authKeyOrResourceToken, Microsoft.Azure.Documents.Client.ConnectionPolicy connectionPolicy, System.Nullable`1[T] desiredConsistencyLevel) [0x00069] in <f7f11c3ada88490092c73d6bef54be97>:0
  at GraphGetStarted.Program.Main (System.String[] args) [0x00021] in /DocumentDB-Quickstart-DotNet-Graph/GraphGetStarted/Program.cs:29
</code>```

And the code where it fails

```<code>   DocumentClient client = new DocumentClient(url, authKey, policy);
</code>```

Here's the packages.config: do I need to set a different targetFramework for Visual Studio Mac?

```<code><?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Microsoft.Azure.DocumentDB" version="1.14.0" targetFramework="net452" />
  <package id="Microsoft.Azure.Graphs" version="0.2.0-preview" targetFramework="net452" />
  <package id="Microsoft.CodeAnalysis.Analyzers" version="1.1.0" targetFramework="net452" />
  <package id="Microsoft.CodeAnalysis.Common" version="1.3.0" targetFramework="net452" />
  <package id="Microsoft.CodeAnalysis.CSharp" version="1.3.0" targetFramework="net452" />
  <package id="Newtonsoft.Json" version="10.0.2" targetFramework="net452" />
  <package id="System.Collections" version="4.3.0" targetFramework="net452" />
  <package id="System.Collections.Immutable" version="1.1.37" targetFramework="net452" />
  <package id="System.Diagnostics.Debug" version="4.3.0" targetFramework="net452" />
  <package id="System.Globalization" version="4.3.0" targetFramework="net452" />
  <package id="System.Linq" version="4.3.0" targetFramework="net452" />
  <package id="System.Reflection.Metadata" version="1.2.0" targetFramework="net452" />
  <package id="System.Resources.ResourceManager" version="4.3.0" targetFramework="net452" />
  <package id="System.Runtime" version="4.3.0" targetFramework="net452" />
  <package id="System.Runtime.Extensions" version="4.3.0" targetFramework="net452" />
  <package id="System.Threading" version="4.3.0" targetFramework="net452" />
</packages>
</code>```

答: According to your comment, you use .net project. Please don't try to run .net project on the MacOS. We can create .NET Core apps that run on Windows, Linux and macOS. We also could get info about azure DocumentDB and .NET Core from the official tutorials.</p>

Body:
I downloaded the getting started sample app from Azure Cosmos DB and am getting the following error with Visual Studio Mac

System.TypeLoadException: Could not resolve type with token 010000f6 (from typeref, class/assembly System.Diagnostics.Eventing.EventProviderTraceListener, System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
  at Microsoft.Azure.Documents.Client.DocumentClient.Initialize (System.Uri serviceEndpoint, Microsoft.Azure.Documents.Client.ConnectionPolicy connectionPolicy, System.Nullable`1[T] desiredConsistencyLevel) [0x00014] in <f7f11c3ada88490092c73d6bef54be97>:0
  at Microsoft.Azure.Documents.Client.DocumentClient..ctor (System.Uri serviceEndpoint, System.String authKeyOrResourceToken, Microsoft.Azure.Documents.Client.ConnectionPolicy connectionPolicy, System.Nullable`1[T] desiredConsistencyLevel) [0x00069] in <f7f11c3ada88490092c73d6bef54be97>:0
  at GraphGetStarted.Program.Main (System.String[] args) [0x00021] in /DocumentDB-Quickstart-DotNet-Graph/GraphGetStarted/Program.cs:29

And the code where it fails

   DocumentClient client = new DocumentClient(url, authKey, policy);

Here's the packages.config: do I need to set a different targetFramework for Visual Studio Mac?

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Microsoft.Azure.DocumentDB" version="1.14.0" targetFramework="net452" />
  <package id="Microsoft.Azure.Graphs" version="0.2.0-preview" targetFramework="net452" />
  <package id="Microsoft.CodeAnalysis.Analyzers" version="1.1.0" targetFramework="net452" />
  <package id="Microsoft.CodeAnalysis.Common" version="1.3.0" targetFramework="net452" />
  <package id="Microsoft.CodeAnalysis.CSharp" version="1.3.0" targetFramework="net452" />
  <package id="Newtonsoft.Json" version="10.0.2" targetFramework="net452" />
  <package id="System.Collections" version="4.3.0" targetFramework="net452" />
  <package id="System.Collections.Immutable" version="1.1.37" targetFramework="net452" />
  <package id="System.Diagnostics.Debug" version="4.3.0" targetFramework="net452" />
  <package id="System.Globalization" version="4.3.0" targetFramework="net452" />
  <package id="System.Linq" version="4.3.0" targetFramework="net452" />
  <package id="System.Reflection.Metadata" version="1.2.0" targetFramework="net452" />
  <package id="System.Resources.ResourceManager" version="4.3.0" targetFramework="net452" />
  <package id="System.Runtime" version="4.3.0" targetFramework="net452" />
  <package id="System.Runtime.Extensions" version="4.3.0" targetFramework="net452" />
  <package id="System.Threading" version="4.3.0" targetFramework="net452" />
</packages>


问:
Unable to install Subversive connectors (SVN) on Eclipse Neon
I installed the new Eclipse Neon, then added the Subversive plugIn (for SVN) but have strange issue to add SVN connectors.

What I do:

1. Window -> Preference -> Team -> SVN.

2. On the "SVN Connector" tab I click on "Get Connectors...".

3. Checking the box for "SVN Kit 1.8.12" and click "finish" (tried also checking Native JavaHL instead).

4. On the new window, I leave both connectors checked and click on "next" and then on "Finish" ("Subversive SVN Connectors" and "SVNKit 1.8.12 Implementation (Optional))".

After 1 second I got the following error message:

'Installing Software' has encountered a problem.
  An error occured while collecting items to be installed.

Details:

An error occurred while collecting items to be installed
  session context was:(profile=C__Users_michaels_eclipse_java-neon_eclipse, phase=org.eclipse.equinox.internal.p2.engine.phases.Collect, operand=, action=).
  No artifact repository available.
  noArtifactRepositoriesAvailable

I tried to add/remove update sites but it didn't help.

Someone familiar with this issue?
Should I install other Eclipse (Luna?)

Thanks in advance!

Mike

答:
I had the same problem today. To install subversive on Neon (at the time of writing neon-3):

Select Help > Install New Software

In the Work With field enter:  http://download.eclipse.org/releases/neon

In the Filter Text field enter: svn

Install the software as usual and restart.

When Eclipse restarts, open Window > Preferences.

Select Team > SVN and you should be prompted to download the SVN Connectors (SVNKit 1.8.14 worked for me). Install as usual and restart. Now Subversive should work.


问:
Angular - Data Binding with ngFor directive
I am new to angular and I'm not sure of how to render data as HTML markup. How can I show the component data inside of the component template?

There is a small reproduction in this plnkr.

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

@Component({
  selector: 'my-app',
  template: `

`
})
export class AppComponent {
  name = 'Angular';
  liArraycontent = ["testing 1", "testing 2", "testing3"]

}
```

答:
To show information from your data source (component class) in your template (html code) you need to use interpolation. You can do this by using the double curly brace syntax {{}} inside of your template. By doing that, you will automatically bind the data in one direction: data source to template. That means, if the data changes in the data source, the changes will be reflected in your template.

I would recommend u to read the following section of the docs:
https://angular.io/docs/ts/latest/guide/template-syntax.html

Hope it helps!


问:
SQL Server row_number() over partition by, but ignore repeating categorical values
I am trying to track different paths through multiple categories.  A simplified view of my table looks like this:

```<code>Table: customer_category

CustomerID   |  Category  |  Date
11111        |  A         |  2016-01-01
11111        |  B         |  2016-02-01
11111        |  C         |  2016-03-01
22222        |  A         |  2016-01-01
22222        |  A         |  2016-02-01
22222        |  A         |  2016-03-01
22222        |  C         |  2016-04-01
33333        |  A         |  2016-01-01
33333        |  B         |  2016-02-01
33333        |  C         |  2016-03-01
33333        |  C         |  2016-04-01
</code>```

I can find the absolute paths by using this query:

```<code>with cat_order as (
    select CustomerID
          ,Category
          ,row_number() over (partition by CustomerID order by Date) as rnk
    from customer_category
),pivot as (
    select CustomerID
      ,max(case when rnk = 1 then Category else null end) as category_1
      ,max(case when rnk = 2 then Category else null end) as category_2
      ,max(case when rnk = 3 then Category else null end) as category_3
      ,max(case when rnk = 4 then Category else null end) as category_4
    from cat_order
    group by CustomerID
)
select category_1, category_2, category_3, category_4, count(*) as count
from pivot
group by category_1, category_2, category_3, category_4
</code>```

;

This gives me the following:

```<code>category_1  |  category_2  |  category_3  |  category_4  |  count
A           |  B           |  C           |              |  1
A           |  A           |  A           |  C           |  1
A           |  B           |  C           |  C           |  1
</code>```

What I want, though, is to ignore repeated categories, so that I would see

```<code>category_1  |  category_2  |  category_3  |  category_4  |  count
A           |  B           |  C           |              |  2
A           |  C           |              |              |  1
</code>```

In my head, I think I would need to

omit any record where Category = lag(category)

rank over partition...

pivot with case statements

aggregate the results

It feels way overcomplicated.  Is there a simpler way to do this?

答:
There isn't a simpler way to do it as far as I can tell (given your data and your desired output). To get your desired results, you basically need to do the four steps you outlined (or some variation of it). You can "simplify" it in a way that doesn't require CTEs though. For example:</p>

```<code>SELECT category_1 = P.[1],
       category_2 = P.[2],
       category_3 = P.[3],
       category_4 = P.[4],
       [Count] = COUNT(*)
FROM
(
    SELECT CustomerID,
           Category,
           rnk = SUM(checkprev) OVER (PARTITION BY CustomerID ORDER BY [Date])
    FROM
    (
        SELECT *, checkprev = CASE WHEN LAG(Category) OVER (PARTITION BY CustomerID ORDER BY [Date]) = Category THEN 0 ELSE 1 END
        FROM customer_category
    ) T
) AS T
PIVOT
(
    MAX(Category) FOR rnk IN ([1], [2], [3], [4])
) AS P
GROUP BY P.[1], P.[2], P.[3], P.[4];
</code>```

Body:
I am trying to track different paths through multiple categories.  A simplified view of my table looks like this:

Table: customer_category

CustomerID   |  Category  |  Date
11111        |  A         |  2016-01-01
11111        |  B         |  2016-02-01
11111        |  C         |  2016-03-01
22222        |  A         |  2016-01-01
22222        |  A         |  2016-02-01
22222        |  A         |  2016-03-01
22222        |  C         |  2016-04-01
33333        |  A         |  2016-01-01
33333        |  B         |  2016-02-01
33333        |  C         |  2016-03-01
33333        |  C         |  2016-04-01

I can find the absolute paths by using this query:

with cat_order as (
    select CustomerID
          ,Category
          ,row_number() over (partition by CustomerID order by Date) as rnk
    from customer_category
),pivot as (
    select CustomerID
      ,max(case when rnk = 1 then Category else null end) as category_1
      ,max(case when rnk = 2 then Category else null end) as category_2
      ,max(case when rnk = 3 then Category else null end) as category_3
      ,max(case when rnk = 4 then Category else null end) as category_4
    from cat_order
    group by CustomerID
)
select category_1, category_2, category_3, category_4, count(*) as count
from pivot
group by category_1, category_2, category_3, category_4

;

This gives me the following:

category_1  |  category_2  |  category_3  |  category_4  |  count
A           |  B           |  C           |              |  1
A           |  A           |  A           |  C           |  1
A           |  B           |  C           |  C           |  1

What I want, though, is to ignore repeated categories, so that I would see

category_1  |  category_2  |  category_3  |  category_4  |  count
A           |  B           |  C           |              |  2
A           |  C           |              |              |  1

In my head, I think I would need to

omit any record where Category = lag(category)

rank over partition...

pivot with case statements

aggregate the results

It feels way overcomplicated.  Is there a simpler way to do this?

Body:
There isn't a simpler way to do it as far as I can tell (given your data and your desired output). To get your desired results, you basically need to do the four steps you outlined (or some variation of it). You can "simplify" it in a way that doesn't require CTEs though. For example:

SELECT category_1 = P.[1],
       category_2 = P.[2],
       category_3 = P.[3],
       category_4 = P.[4],
       [Count] = COUNT(*)
FROM
(
    SELECT CustomerID,
           Category,
           rnk = SUM(checkprev) OVER (PARTITION BY CustomerID ORDER BY [Date])
    FROM
    (
        SELECT *, checkprev = CASE WHEN LAG(Category) OVER (PARTITION BY CustomerID ORDER BY [Date]) = Category THEN 0 ELSE 1 END
        FROM customer_category
    ) T
) AS T
PIVOT
(
    MAX(Category) FOR rnk IN ([1], [2], [3], [4])
) AS P
GROUP BY P.[1], P.[2], P.[3], P.[4];


问:
How to Iterate over a Set/HashSet without an Iterator?
How can I iterate over a Set/HashSet without the following?

```<code>Iterator iter = set.iterator();
while (iter.hasNext()) {
    System.out.println(iter.next());
}
</code>```

答:
Here are few tips on how to iterate a Set along with their performances:

```<code>public class IterateSet {

    public static void main(String[] args) {

        //example Set
        Set<String> set = new HashSet<>();

        set.add("Jack");
        set.add("John");
        set.add("Joe");
        set.add("Josh");

        long startTime = System.nanoTime();
        long endTime = System.nanoTime();

        //using iterator
        System.out.println("Using Iterator");
        startTime = System.nanoTime();
        Iterator<String> setIterator = set.iterator();
        while(setIterator.hasNext()){
            System.out.println(setIterator.next());
        }
        endTime = System.nanoTime();
        long durationIterator = (endTime - startTime);

        //using lambda
        System.out.println("Using Lambda");
        startTime = System.nanoTime();
        set.forEach((s) -> System.out.println(s));
        endTime = System.nanoTime();
        long durationLambda = (endTime - startTime);

        //using Stream API
        System.out.println("Using Stream API");
        startTime = System.nanoTime();
        set.stream().forEach((s) -> System.out.println(s));
        endTime = System.nanoTime();
        long durationStreamAPI = (endTime - startTime);

        //using Split Iterator (not recommended)
        System.out.println("Using Split Iterator");
        startTime = System.nanoTime();
        Spliterator<String> splitIterator = set.spliterator();
        splitIterator.forEachRemaining((s) -> System.out.println(s));
        endTime = System.nanoTime();
        long durationSplitIterator = (endTime - startTime);

        //time calculations
        System.out.println("Iterator Duration:" + durationIterator);
        System.out.println("Lamda Duration:" + durationLambda);
        System.out.println("Stream API:" + durationStreamAPI);
        System.out.println("Split Iterator:"+ durationSplitIterator);
    }
}
</code>```

The code is self explanatory.

The result of the durations are:

```<code>Iterator Duration: 495287
Lambda Duration: 50207470
Stream Api:       2427392
Split Iterator:    567294
</code>```

We can see the Lambda takes the longest while Iterator is the fastest.

Body:
How can I iterate over a Set/HashSet without the following?

Iterator iter = set.iterator();
while (iter.hasNext()) {
    System.out.println(iter.next());
}

Body:
Here are few tips on how to iterate a Set along with their performances:

public class IterateSet {

    public static void main(String[] args) {

        //example Set
        Set<String> set = new HashSet<>();

        set.add("Jack");
        set.add("John");
        set.add("Joe");
        set.add("Josh");

        long startTime = System.nanoTime();
        long endTime = System.nanoTime();

        //using iterator
        System.out.println("Using Iterator");
        startTime = System.nanoTime();
        Iterator<String> setIterator = set.iterator();
        while(setIterator.hasNext()){
            System.out.println(setIterator.next());
        }
        endTime = System.nanoTime();
        long durationIterator = (endTime - startTime);

        //using lambda
        System.out.println("Using Lambda");
        startTime = System.nanoTime();
        set.forEach((s) -> System.out.println(s));
        endTime = System.nanoTime();
        long durationLambda = (endTime - startTime);

        //using Stream API
        System.out.println("Using Stream API");
        startTime = System.nanoTime();
        set.stream().forEach((s) -> System.out.println(s));
        endTime = System.nanoTime();
        long durationStreamAPI = (endTime - startTime);

        //using Split Iterator (not recommended)
        System.out.println("Using Split Iterator");
        startTime = System.nanoTime();
        Spliterator<String> splitIterator = set.spliterator();
        splitIterator.forEachRemaining((s) -> System.out.println(s));
        endTime = System.nanoTime();
        long durationSplitIterator = (endTime - startTime);

        //time calculations
        System.out.println("Iterator Duration:" + durationIterator);
        System.out.println("Lamda Duration:" + durationLambda);
        System.out.println("Stream API:" + durationStreamAPI);
        System.out.println("Split Iterator:"+ durationSplitIterator);
    }
}

The code is self explanatory.

The result of the durations are:

Iterator Duration: 495287
Lambda Duration: 50207470
Stream Api:       2427392
Split Iterator:    567294

We can see the Lambda takes the longest while Iterator is the fastest.

ContentLicense: CC BY-SA 4.0


问:
Order of image generated in keras
I am trying to feed the images generated by Keras' ImageDataGenerator into a LSTM that will generate it's caption. Currently the train folder contains the information in the order of: image1.jpg, image1_caption, image2.jpg, image2_caption, ...imageN.jpg, imageN_caption.

However,
1. I'm not sure how many images are being generated per image file (by flipping, zooming, rotating).
2. Which batch and sample in the batch corresponds to image 1. It all seems quite random. Even setting shuffle = False doesn't seem to help.

Basically I just want to know which batch and sample in the batch that imageN corresponds to so that I can feed into an LSTM to match up with imageN_caption.

```<code>train_datagen = ImageDataGenerator(
        rescale=1./255,
        rotation_range=5,
        zoom_range=0.2,
        horizontal_flip=True)

img_height = img_width = 224
train_generator = train_datagen.flow_from_directory(
    './train/',
    color_mode = "rgb",
    target_size=(img_height, img_width),
    batch_size=32,
    shuffle = False,
    class_mode=None)

i = 0
img_list = []
for batch in train_generator: #.flow(x, batch_size=1)
    img_list.append(batch)
    i += 1
    if i > 5:
        break
</code>```

答:
I found the answer after seeing this post: https://github.com/fchollet/keras/issues/3296

Basically the images are generated in the same order of train_generator.filenames. I assumed that each image would go through a sequence of zooming and rotating etc. before moving onto the next images but this isn't the case. A transformation is applied to each image once before moving onto the next image.

I was able to confirm this after running the following code:

```<code>plt.figure(figsize=(12,12))
for i in range(5):
    plt.subplot(5,2,2*i+1)
    plt.imshow(np.squeeze(img_list[0][i]), cmap='gray')
    img=mpimg.imread('./train/'+files[i])
    plt.subplot(5,2,2*i+2)
    plt.imshow(img, cmap='gray')
plt.show()
</code>```

Or in the case of the second batch:

```<code>plt.figure(figsize=(12,12))
for i in range(5):
    plt.subplot(5,2,2*i+1)
    plt.imshow(np.squeeze(img_list[1][i]), cmap='gray')
    img=mpimg.imread('./train/'+files[32+i])
    plt.subplot(5,2,2*i+2)
    plt.imshow(img, cmap='gray')
plt.show()
</code>```

Title: Order of image generated in keras

Body:
I am trying to feed the images generated by Keras' ImageDataGenerator into a LSTM that will generate it's caption. Currently the train folder contains the information in the order of: image1.jpg, image1_caption, image2.jpg, image2_caption, ...imageN.jpg, imageN_caption.

However,
1. I'm not sure how many images are being generated per image file (by flipping, zooming, rotating).
2. Which batch and sample in the batch corresponds to image 1. It all seems quite random. Even setting shuffle = False doesn't seem to help.

Basically I just want to know which batch and sample in the batch that imageN corresponds to so that I can feed into an LSTM to match up with imageN_caption.

train_datagen = ImageDataGenerator(
        rescale=1./255,
        rotation_range=5,
        zoom_range=0.2,
        horizontal_flip=True)

img_height = img_width = 224
train_generator = train_datagen.flow_from_directory(
    './train/',
    color_mode = "rgb",
    target_size=(img_height, img_width),
    batch_size=32,
    shuffle = False,
    class_mode=None)

i = 0
img_list = []
for batch in train_generator: #.flow(x, batch_size=1)
    img_list.append(batch)
    i += 1
    if i > 5:
        break

Body:
I found the answer after seeing this post: https://github.com/fchollet/keras/issues/3296

Basically the images are generated in the same order of train_generator.filenames. I assumed that each image would go through a sequence of zooming and rotating etc. before moving onto the next images but this isn't the case. A transformation is applied to each image once before moving onto the next image.

I was able to confirm this after running the following code:

plt.figure(figsize=(12,12))
for i in range(5):
    plt.subplot(5,2,2*i+1)
    plt.imshow(np.squeeze(img_list[0][i]), cmap='gray')
    img=mpimg.imread('./train/'+files[i])
    plt.subplot(5,2,2*i+2)
    plt.imshow(img, cmap='gray')
plt.show()

Or in the case of the second batch:

plt.figure(figsize=(12,12))
for i in range(5):
    plt.subplot(5,2,2*i+1)
    plt.imshow(np.squeeze(img_list[1][i]), cmap='gray')
    img=mpimg.imread('./train/'+files[32+i])
    plt.subplot(5,2,2*i+2)
    plt.imshow(img, cmap='gray')
plt.show()


问:
How to open files in default program?
I'm writing application using Xamarin.forms and i need to open PDF and Doc documents in Droid and IOS. Is there any crossplatform way to achive this? Maybe any packages?</p>

答:
It depends on what type of documents you are taking about. In Xamarin.Forms, you can use

```<code>Device.OpenUri(new Uri("filepath or http url"));
</code>```

If there is an application that can handle the extension, then it will prompt you on which app you wish to use.

If you wanted to view them internally, inside the app, without launching a 3rd party app, then we really need to know what type of documents you are opening. If it's a PDF, then you can look at Display Local PDF File In WebView.

Should it be another type of document, you will need to see if there is a different

Title: How to open files in default program?

Body:
It depends on what type of documents you are taking about. In Xamarin.Forms, you can use

Device.OpenUri(new Uri("filepath or http url"));

If there is an application that can handle the extension, then it will prompt you on which app you wish to use.

If you wanted to view them internally, inside the app, without launching a 3rd party app, then we really need to know what type of documents you are opening. If it's a PDF, then you can look at Display Local PDF File In WebView.

Should it be another type of document, you will need to see if there is a different


问:
How can I convert a fully qualified file path to URL in Laravel
I have a complete file path (/var/www/project/public/csv/Info.csv) stored in a variable $file

How can I convert this variable into a server friendly URL. I tried to use the url($file) helper function but it returns http://127.0.0.1/var/www/soccer/public/csv/Info.csv

The expected output is: http://127.0.0.1/csv/Info.csv

One approach is to cut the string from public and pass it to url() function. Does anyone have a more eloquent approach?

答:
How about:</p>

```<code>str_replace(public_path(), '', $file);
</code>```

Body:
How about:

str_replace(public_path(), '', $file);


问:
UserName authentication for WCF WebService
I am having an absolute nightmare trying to get this to work. Can someone please point me in the right direction or tell me where I am going wrong?

I have created a certificate which is located in LocalMachine\My.

I have a console application that
hosts a WCF WebService.

I have an ASP.NET website that connects to the
WebService.

I have followed advice on this site and others and documentation but seem to be missing something as my ASP.NET website can still connect to the WebService without authentication.

So to summarise: the website connects to the web service fine which indicates the authentication isn't working as I have yet to tell the website what security settings it needs to connect to the webservice.

Thankyou in advance

Here is the info:

Console App (hosting WebService)

Program.cs

WebService Host (console app) uses the following code in

```<code>ServiceHost host = new ServiceHost(typeof(MyService));
host.Open();
</code>```

App.Config (abbreviated)

```<code><services>
  <service behaviorConfiguration="MetaDataBehaviour" name="MyService_Provider.MyService">
    <clear />
    <endpoint address="myService" binding="wsHttpBinding" contract="MyService_Provider.IMyService"
        listenUriMode="Explicit" />
    <host>
      <baseAddresses>
        <add baseAddress="http://localhost:8080" />
      </baseAddresses>
    </host>
  </service>
</services>
</code>```

MyService Provider

App.Config (abbreviated)

```<code> <system.serviceModel>
    <bindings />
    <client />
    <services>
      <service behaviorConfiguration="MyService_Provider.Service1Behavior"
        name="MyService_Provider.MyService">
        <endpoint address="" binding="wsHttpBinding" contract="MyService_Provider.IMyService">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8732/Design_Time_Addresses/MyService_Provider/Service1/" />
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="MyService_Provider.Service1Behavior">
          <serviceMetadata httpGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="False" />
          <serviceCredentials>
            <userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="MyService_Provider.CredentialsValidator,MyService_Provider"/>
            <serviceCertificate findValue="mycert" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName"/>
          </serviceCredentials>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</code>```

答: You haven't specified any security requirements for your service. Have a look at this article for an example of configuring a service to use certificates.</p>

Body:
I am having an absolute nightmare trying to get this to work. Can someone please point me in the right direction or tell me where I am going wrong?

I have created a certificate which is located in LocalMachine\My.

I have a console application that
hosts a WCF WebService.

I have an ASP.NET website that connects to the
WebService.

I have followed advice on this site and others and documentation but seem to be missing something as my ASP.NET website can still connect to the WebService without authentication.

So to summarise: the website connects to the web service fine which indicates the authentication isn't working as I have yet to tell the website what security settings it needs to connect to the webservice.

Thankyou in advance

Here is the info:

Console App (hosting WebService)

Program.cs

WebService Host (console app) uses the following code in

ServiceHost host = new ServiceHost(typeof(MyService));
host.Open();

App.Config (abbreviated)

<services>
  <service behaviorConfiguration="MetaDataBehaviour" name="MyService_Provider.MyService">
    <clear />
    <endpoint address="myService" binding="wsHttpBinding" contract="MyService_Provider.IMyService"
        listenUriMode="Explicit" />
    <host>
      <baseAddresses>
        <add baseAddress="http://localhost:8080" />
      </baseAddresses>
    </host>
  </service>
</services>

MyService Provider

App.Config (abbreviated)

 <system.serviceModel>
    <bindings />
    <client />
    <services>
      <service behaviorConfiguration="MyService_Provider.Service1Behavior"
        name="MyService_Provider.MyService">
        <endpoint address="" binding="wsHttpBinding" contract="MyService_Provider.IMyService">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8732/Design_Time_Addresses/MyService_Provider/Service1/" />
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="MyService_Provider.Service1Behavior">
          <serviceMetadata httpGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="False" />
          <serviceCredentials>
            <userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="MyService_Provider.CredentialsValidator,MyService_Provider"/>
            <serviceCertificate findValue="mycert" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName"/>
          </serviceCredentials>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>


问:
Why not fading out and fading in jquery?
I've been trying this for several hours

```<code>    $('#position-name').html('Successfuly Changed').fadeOut(1000);
    $('#position-name').html('New Name').fadeIn();
</code>```

I know its simple but, I don't know the reason why If I run those line within my code only New Name that keep showing up despite the given effect.

It fadeOut the New Name and then FadeIn the New Name again

why Is it not fading out or showing successfully changed?

答:
The problem is: Your code reads like -change the element html to 'Successfuly Changed' -then while fadOut() with 1000 its directly change to 'New Name' -so you can see it fadeOut() and then fadeIn() .. To avoid that you need to use fadeOut() callback function

$('#position-name').html('Successfuly Changed').fadeOut(1000 ,function(){
  $(this).html('New Name').fadeIn();
});```
<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>
<div id="position-name"></div></code>```

Body:
I've been trying this for several hours

    $('#position-name').html('Successfuly Changed').fadeOut(1000);
    $('#position-name').html('New Name').fadeIn();

I know its simple but, I don't know the reason why If I run those line within my code only New Name that keep showing up despite the given effect.

It fadeOut the New Name and then FadeIn the New Name again

why Is it not fading out or showing successfully changed?

Body:
The problem is: Your code reads like -change the element html to 'Successfuly Changed' -then while fadOut() with 1000 its directly change to 'New Name' -so you can see it fadeOut() and then fadeIn() .. To avoid that you need to use fadeOut() callback function

$('#position-name').html('Successfuly Changed').fadeOut(1000 ,function(){
  $(this).html('New Name').fadeIn();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="position-name"></div>


问:
How to pause a YouTube player when hiding the iframe?
I have a hidden div containing a YouTube video in an . When the user clicks on a link, this div becomes visible, the user should then be able to play the video.

When the user closes the panel, the video should stop playback. How can I achieve this?

Code:

```<code><!-- link to open popupVid -->
<p><a href="javascript:;" onClick="document.getElementById('popupVid').style.display='';">Click here</a> to see my presenting showreel, to give you an idea of my style - usually described as authoritative, affable and and engaging.</p>

<!-- popup and contents -->
<div id="popupVid" style="position:absolute;left:0px;top:87px;width:500px;background-color:#D05F27;height:auto;display:none;z-index:200;">

  <iframe width="500" height="315" src="http://www.youtube.com/embed/T39hYJAwR40" frameborder="0" allowfullscreen></iframe>

  <br /><br />
  <a href="javascript:;" onClick="document.getElementById('popupVid').style.display='none';">
  close
  </a>
</div><!--end of popupVid -->
</code>```

答:
This approach requires jQuery. First, select your iframe:

```<code>var yourIframe = $('iframe#yourId');
//yourId or something to select your iframe.
</code>```

Now you select button play/pause of this iframe and click it

```<code>$('button.ytp-play-button.ytp-button', yourIframe).click();
</code>```

I hope it will help you.

Body:
I have a hidden div containing a YouTube video in an . When the user clicks on a link, this div becomes visible, the user should then be able to play the video.

When the user closes the panel, the video should stop playback. How can I achieve this?

Code:

Click here to see my presenting showreel, to give you an idea of my style - usually described as authoritative, affable and and engaging.

  close

Body:
This approach requires jQuery. First, select your iframe:

var yourIframe = $('iframe#yourId');
//yourId or something to select your iframe.

Now you select button play/pause of this iframe and click it

$('button.ytp-play-button.ytp-button', yourIframe).click();

I hope it will help you.


问:
Change rails value with ajax
I am trying to change a rails value with ajax and I am having trouble. Here is what I have so far.

ajax

```<code>$(button).click(function(){
        $.ajax({
           url: '/change_value',
           type: 'GET'
    })
});
</code>```

Controller

```<code>def home
  @value = 0
end

def change_value
  @value = 1
end
</code>```

routes

```<code>get '/change_value', to: 'static_pages#change_value'
</code>```

Thank you for all the help.

答:
You need to create a view to respond in js format:

change_value.js.erb

```<code>var newValue = <%= @value %>;
</code>```

Now, use it in your script:

```<code>$(button).click(function(){
        $.ajax({
           url: '/change_value',
           type: 'GET',
           success: function(data) {
               console.log(newValue);
           }
    })
});
</code>```

Title: Change rails value with ajax

Body:
I am trying to change a rails value with ajax and I am having trouble. Here is what I have so far.

ajax

$(button).click(function(){
        $.ajax({
           url: '/change_value',
           type: 'GET'
    })
});

Controller

def home
  @value = 0
end

def change_value
  @value = 1
end

routes

get '/change_value', to: 'static_pages#change_value'

Thank you for all the help.

Body:
You need to create a view to respond in js format:

change_value.js.erb

var newValue = <%= @value %>;

Now, use it in your script:

$(button).click(function(){
        $.ajax({
           url: '/change_value',
           type: 'GET',
           success: function(data) {
               console.log(newValue);
           }
    })
});


问:
How to edit existing rolebinding in Openshift using yml files?
I have a predefined rolebinding in place for an Openshift project, that I want to edit/update using a .yml file.

I have already tried the below:

oc create –f –> failed, obvious because it exists, the error is:

```<code>Error from server: rolebinding "edit" already exists
</code>```

oc patch –f–> failed, looks like patch only accepts –p argument, the error is:

```<code>Error: Must specify -p to patch
See 'oc patch -h' for help and examples.
</code>```

oc replace –f–> failed, the error is:

```<code>Error: error when replacing "sample.yml": resource name may not be empty
If I were to run the create command against the file on a new project, it works.
</code>```

Please do respond if any one has thoughts on this.

Thanks much,
Aneesh

答:
If I understand what you are trying to do, I would use separate oc adm policy commands to do it.

```<code>oc adm policy add-role-to-group edit group-name-a
oc adm policy add-role-to-group edit group-name-b

oc adm policy add-role-to-group edit group-name-x
oc adm policy add-role-to-group edit group-name-y
oc adm policy add-role-to-group edit group-name-z
</code>```

Using oc patch is only going to work if there existed a resource object for the roleRef name already, it isn't going to create the whole role binding object if it doesn't exist.

Modifying roles is one of the times where you can't make additive changes by simply loading a new resource object definition.

You can see this by enabling logging for the oc command and looking at what it does. In the case of adding additional role bindings, it will first query the existing role binding and add the change to it and then load the new modified entry with all role bindings in it.

Run:

```<code>oc --loglevel=9 adm policy add-role-to-group edit group-name-x
</code>```

when only group-name-a and group-name-b have already been set up to see what I mean.

Body:
I have a predefined rolebinding in place for an Openshift project, that I want to edit/update using a .yml file.

I have already tried the below:

oc create –f –> failed, obvious because it exists, the error is:

Error from server: rolebinding "edit" already exists

oc patch –f–> failed, looks like patch only accepts –p argument, the error is:

Error: Must specify -p to patch
See 'oc patch -h' for help and examples.

oc replace –f–> failed, the error is:

Error: error when replacing "sample.yml": resource name may not be empty
If I were to run the create command against the file on a new project, it works.

Please do respond if any one has thoughts on this.

Thanks much,
Aneesh

Body:
If I understand what you are trying to do, I would use separate oc adm policy commands to do it.

oc adm policy add-role-to-group edit group-name-a
oc adm policy add-role-to-group edit group-name-b

oc adm policy add-role-to-group edit group-name-x
oc adm policy add-role-to-group edit group-name-y
oc adm policy add-role-to-group edit group-name-z

Using oc patch is only going to work if there existed a resource object for the roleRef name already, it isn't going to create the whole role binding object if it doesn't exist.

Modifying roles is one of the times where you can't make additive changes by simply loading a new resource object definition.

You can see this by enabling logging for the oc command and looking at what it does. In the case of adding additional role bindings, it will first query the existing role binding and add the change to it and then load the new modified entry with all role bindings in it.

Run:

oc --loglevel=9 adm policy add-role-to-group edit group-name-x

when only group-name-a and group-name-b have already been set up to see what I mean.


问:
Difference between 1 ELB per AZ and 1 ELB to multiple AZs
I'd like to seek clarification on the following.

Considering the 2 diagrams here

1 ELB to multiple EC2 instances in multiple AZs

1 ELB per AZ

Assuming all EC2 instances are running the same version of the same app - just scaled with auto scale groups, what's the difference between both architectures? When would I choose one over the other?

答:
The diagrams are actually depicting the same thing!

While diagrams normally depict an Elastic Load Balancer as being in a Region, the reality is that it actually creates multiple load balancing servers in each Availability Zone that appear in the VPC's subnets via Elastic Network Interfaces (ENIs).

The process is:

An end-user access the app via a DNS name that is mapped to the Load Balancer

The Elastic Load Balancing service resolves the DNS name to the IP address of one of the ENIs in the VPC. If an Availability Zone fails, it only sends requests to functional AZs.

The end-user's web browser then sends the request to that IP address, which goes to one of the load balancers

The load balancer figures out which Amazon EC2 instance should receive the traffic, based on least open connections and forwards the request to it. Also, the load balancer can send traffic to an instance in a different AZ to keep requests balanced ("Cross-zone load balancing").

The second diagram is simply showing the additional layer of load balancers that connect to the VPC. Traditionally, an ELB is simply shown as one icon at the regional level but the reality is more like the second diagram.

For those interested, see: How Elastic Load Balancing Works


问:
WinForms - DataGridViewCell not being set to read only
I am working on an old .Net 2.0 WinForms project and need to set some cells to read only.

I have a DataTable that I am reading and setting as the DataSource and the field types are being set correctly

Generate DataTable and columns

```<code>public DataTable FilterData(DataTable datatable, string dataType)
    {
        try
        {
            if (dataType == "MailPreferences")
            {

                var dt = new DataTable();

                dt.Columns.Add("SEQ_ID", typeof(int));                              // SEQ_ID
                dt.Columns.Add("MAIL_PREFERENCE_ID", typeof(string));               // MAIL_PREFERENCE_ID
                dt.Columns.Add("Mail Preference Description", typeof(string));      // MAIL_PREFERENCE_DESC
                dt.Columns.Add("Post", typeof(bool));                               // POST
                dt.Columns.Add("SMS", typeof(bool));                                // SMS
                dt.Columns.Add("Email", typeof(bool));                              // EMAIL
                dt.Columns.Add("Telephone", typeof(bool));                          // TELEPHONE

                foreach (DataRow row in datatable.Rows)
                {
                    dt.Rows.Add(row["SEQ_ID"].ToString(),
                                row["MAIL_PREFERENCE_ID"].ToString(),
                                row["MAIL_PREFERENCE_DESC"].ToString(),
                                Convert.ToBoolean(row["POST"]),
                                Convert.ToBoolean(row["SMS"]),
                                Convert.ToBoolean(row["EMAIL"]),
                                Convert.ToBoolean(row["TELEPHONE"]));
                }

                return dt;

            }

        }
        catch (Exception ex)
        {
            // catch and deal with my exception here
        }

        return null;
    }
</code>```

The above method is being called here and this is where I am having the issue of disabling cells.

```<code>private void PopulateMailPreferencesGV()
    {
        var dt = FilterData(_cAddPersonWizard.GetMailPreferneces(), "MailPreferences");
        dgvMailPreferences.DataSource = dt;

        dgvMailPreferences.Columns["Mail Preference Description"].Width = 250;
        dgvMailPreferences.Columns["Post"].Width = 50;
        dgvMailPreferences.Columns["SMS"].Width = 50;
        dgvMailPreferences.Columns["Email"].Width = 50;
        dgvMailPreferences.Columns["Telephone"].Width = 75;

        dgvMailPreferences.Columns["SEQ_ID"].Visible = false;
        dgvMailPreferences.Columns["MAIL_PREFERENCE_ID"].Visible = false;

        // not setting the datagridview cell to readonly
        foreach (DataGridViewRow row in dgvMailPreferences.Rows)
        {
            foreach (DataGridViewCell cell in row.Cells)
            {
                if (cell.GetType() == typeof(DataGridViewCheckBoxCell))
                {
                    if(((DataGridViewCheckBoxCell)row.Cells[cell.ColumnIndex]).Selected == false)
                    {
                        ((DataGridViewCheckBoxCell)row.Cells[cell.ColumnIndex]).ReadOnly = true;
                    }
                }
            }
        }

    }
</code>```

When stepping through and looking at the Watch window I can see that the read only properties are being set, however when coming to work with the DataGridView the cells are still active.

I would be grateful if someone could point me in the direction of where this code is wrong or if I need to do something else?

Thanks for your help.

--- Edit 31/05/2017

The image above shows the grid that I want to work with, the options that are selected are selected by default.

The options that are not selected are to be disabled because these forms of delivery are not possible for the mail type

答:
EDIT:

Ok I realised that the fiddle code wasn't yours (I should have read more carefully). I was able to recreate this using the code from your question. I see what the problem is now, it is this line:

```<code>if(((DataGridViewCheckBoxCell)row.Cells[cell.ColumnIndex]).Selected == false)
</code>```

You are testing against 'Selected' which is not what you want, you want to test against the 'Value' of the cell.

If you look at the code in the other answers this is what they show.

Original Answer: Left for others

Running your code (fiddle) the checkboxes are indeed readonly although they do not appear grayed out as if they were disabled (which is what I think you are looking for) Can you confirm if you are able to actually check the checkboxes or not?

Unfortunately you can not disable the checkbox directly.

If this is what you want then you have a couple of options, you can either change the BackColor of the cell, which may be sufficient, however this will not actually change the colour of the checkbox itself.

You can also paint the control yourself, here is a microsoft guide to a similar tutorial.

Or you could create a disabled cell and replace the ones that you need with that. It's not too much work, especially when someone has already done it for you!

Body:
I am working on an old .Net 2.0 WinForms project and need to set some cells to read only.

I have a DataTable that I am reading and setting as the DataSource and the field types are being set correctly

Generate DataTable and columns

public DataTable FilterData(DataTable datatable, string dataType)
    {
        try
        {
            if (dataType == "MailPreferences")
            {

                var dt = new DataTable();

                dt.Columns.Add("SEQ_ID", typeof(int));                              // SEQ_ID
                dt.Columns.Add("MAIL_PREFERENCE_ID", typeof(string));               // MAIL_PREFERENCE_ID
                dt.Columns.Add("Mail Preference Description", typeof(string));      // MAIL_PREFERENCE_DESC
                dt.Columns.Add("Post", typeof(bool));                               // POST
                dt.Columns.Add("SMS", typeof(bool));                                // SMS
                dt.Columns.Add("Email", typeof(bool));                              // EMAIL
                dt.Columns.Add("Telephone", typeof(bool));                          // TELEPHONE

                foreach (DataRow row in datatable.Rows)
                {
                    dt.Rows.Add(row["SEQ_ID"].ToString(),
                                row["MAIL_PREFERENCE_ID"].ToString(),
                                row["MAIL_PREFERENCE_DESC"].ToString(),
                                Convert.ToBoolean(row["POST"]),
                                Convert.ToBoolean(row["SMS"]),
                                Convert.ToBoolean(row["EMAIL"]),
                                Convert.ToBoolean(row["TELEPHONE"]));
                }

                return dt;

            }

        }
        catch (Exception ex)
        {
            // catch and deal with my exception here
        }

        return null;
    }

The above method is being called here and this is where I am having the issue of disabling cells.

private void PopulateMailPreferencesGV()
    {
        var dt = FilterData(_cAddPersonWizard.GetMailPreferneces(), "MailPreferences");
        dgvMailPreferences.DataSource = dt;

        dgvMailPreferences.Columns["Mail Preference Description"].Width = 250;
        dgvMailPreferences.Columns["Post"].Width = 50;
        dgvMailPreferences.Columns["SMS"].Width = 50;
        dgvMailPreferences.Columns["Email"].Width = 50;
        dgvMailPreferences.Columns["Telephone"].Width = 75;

        dgvMailPreferences.Columns["SEQ_ID"].Visible = false;
        dgvMailPreferences.Columns["MAIL_PREFERENCE_ID"].Visible = false;

        // not setting the datagridview cell to readonly
        foreach (DataGridViewRow row in dgvMailPreferences.Rows)
        {
            foreach (DataGridViewCell cell in row.Cells)
            {
                if (cell.GetType() == typeof(DataGridViewCheckBoxCell))
                {
                    if(((DataGridViewCheckBoxCell)row.Cells[cell.ColumnIndex]).Selected == false)
                    {
                        ((DataGridViewCheckBoxCell)row.Cells[cell.ColumnIndex]).ReadOnly = true;
                    }
                }
            }
        }

    }

When stepping through and looking at the Watch window I can see that the read only properties are being set, however when coming to work with the DataGridView the cells are still active.

I would be grateful if someone could point me in the direction of where this code is wrong or if I need to do something else?

Thanks for your help.

--- Edit 31/05/2017

The image above shows the grid that I want to work with, the options that are selected are selected by default.

The options that are not selected are to be disabled because these forms of delivery are not possible for the mail type

Body:
EDIT:

Ok I realised that the fiddle code wasn't yours (I should have read more carefully). I was able to recreate this using the code from your question. I see what the problem is now, it is this line:

if(((DataGridViewCheckBoxCell)row.Cells[cell.ColumnIndex]).Selected == false)

You are testing against 'Selected' which is not what you want, you want to test against the 'Value' of the cell.

If you look at the code in the other answers this is what they show.

Original Answer: Left for others

Running your code (fiddle) the checkboxes are indeed readonly although they do not appear grayed out as if they were disabled (which is what I think you are looking for) Can you confirm if you are able to actually check the checkboxes or not?

Unfortunately you can not disable the checkbox directly.

If this is what you want then you have a couple of options, you can either change the BackColor of the cell, which may be sufficient, however this will not actually change the colour of the checkbox itself.

You can also paint the control yourself, here is a microsoft guide to a similar tutorial.

Or you could create a disabled cell and replace the ones that you need with that. It's not too much work, especially when someone has already done it for you!


问:
mysql query displays field data not matched to LIKE statement
I've been spending hours on this one.
So I got two tables, the "candidate_list" table and "election_title" table. I need to display all the candidates running in a certain election/club by matching the "ename" column on both tables. Also, it has an if while statement because it is highly dependent on admin input. Hope you can help me with this one.

```<code><?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "voting_system";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT ename FROM election_title ORDER BY `sdate` ASC";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
    $ename= $row['ename'];
?>
<p><font size= "6px" align = "center" color = "#efbf77"> <?php echo $row['ename']. "<br>";?></p>

<?php

$servername1 = "localhost";
$username1 = "root";
$password1 = "";
$dbname1 = "voting_system";

$conn1 = new mysqli($servername1, $username1, $password1, $dbname1);

if ($conn1->connect_error) {
die("Connection failed: " . $conn1->connect_error);

}

$sql = "SELECT * FROM candidate_list WHERE ename IN (SELECT ename FROM election_title);";
$result = $conn1->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
    $ename= $row['ename'];
    $pos= $row['pos'];
    $fname= $row['fname'];
    $mname= $row['mname'];
    $lname= $row['lname'];

    ?>
    <button type="submit" class = "ename"> <?php echo "<p class = 'bold'>" .$row['ename']. " </p>" .$row['pos']. "<br>" .$row['fname']. " " .$row['mname'] . " " .$row['lname'];?> </button>

<?php
}
} else {
echo "0 results";
}

$conn->close();

?>
<?php
}
} else {
echo "0 results";
}

$conn1->close();

?>
</code>```

As of now, it only display one election title. I need it to loop and display all my elections together with its respective candidates.

答: UPDATE: The query has worked after some reading on INNER JOINS. Thanks for your help guys! :)</p>

Body:
I've been spending hours on this one.
So I got two tables, the "candidate_list" table and "election_title" table. I need to display all the candidates running in a certain election/club by matching the "ename" column on both tables. Also, it has an if while statement because it is highly dependent on admin input. Hope you can help me with this one.

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "voting_system";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT ename FROM election_title ORDER BY `sdate` ASC";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
    $ename= $row['ename'];
?>

 <?php echo $row['ename']. "
";?>

<?php

$servername1 = "localhost";
$username1 = "root";
$password1 = "";
$dbname1 = "voting_system";

$conn1 = new mysqli($servername1, $username1, $password1, $dbname1);

if ($conn1->connect_error) {
die("Connection failed: " . $conn1->connect_error);

}

$sql = "SELECT * FROM candidate_list WHERE ename IN (SELECT ename FROM election_title);";
$result = $conn1->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
    $ename= $row['ename'];
    $pos= $row['pos'];
    $fname= $row['fname'];
    $mname= $row['mname'];
    $lname= $row['lname'];

    ?>
    <button type="submit" class = "ename"> <?php echo "
" .$row['ename']. "
" .$row['pos']. "
" .$row['fname']. " " .$row['mname'] . " " .$row['lname'];?> </button>

<?php
}
} else {
echo "0 results";
}

$conn->close();

?>
<?php
}
} else {
echo "0 results";
}

$conn1->close();

?>

As of now, it only display one election title. I need it to loop and display all my elections together with its respective candidates.


问:
Is there anything like !in_array()?
$file_name = "smith.jpg" // This gives error 'Invalid file extension'
What could be the problem?</p>

```<code>$whitelist = array('jpg', 'png', 'gif', 'jpeg');

// Validate file extension
    if(!in_array(end(explode('.', $file_name)), $whitelist))
        HandleError('Invalid file extension');
</code>```

答:
It's a referencing error:</p>

```<code>$whitelist = array('jpg', 'png', 'gif', 'jpeg');

// Validate file extension
$parts = explode('.', $file_name);
if(!in_array(end($parts), $whitelist))
{
 HandleError('Invalid file extension');
}
</code>```

Title: Is there anything like !in_array()?

Body:
$file_name = "smith.jpg" // This gives error 'Invalid file extension'
What could be the problem?

$whitelist = array('jpg', 'png', 'gif', 'jpeg');

// Validate file extension
    if(!in_array(end(explode('.', $file_name)), $whitelist))
        HandleError('Invalid file extension');

Body:
It's a referencing error:

$whitelist = array('jpg', 'png', 'gif', 'jpeg');

// Validate file extension
$parts = explode('.', $file_name);
if(!in_array(end($parts), $whitelist))
{
 HandleError('Invalid file extension');
}


问:
Linker error undefined reference to `timer_getoverrun' (-lrt linker option doesn't work)
I am trying to compile example code from timer_create() Linux>man_page. using following command line:

gcc example.c -o example -lrt

Nevertheless, I have linker error:

undefined reference to `timer_getoverrun'

Why -lrt couldn't work.

答: Sorry - timer_getoverrun() isn't implemented under Cygwin.</p>


问:
Is there an isdate PHP function?
I saw an inbuilt function called isdate in the user function below and when I checked the PHP documentation I didn't find it. Does it exist and what does it do; or is this simply a typo?</p>

```<code>function mystery($a, $b, $c) {
$result = null;
if (strlen(trim($a)) == 0) {
    $result = $c;
}
else {
    if (strtolower(trim($b)) == "n") {
        if (!is_numeric($a)) {
            $result = $c;
        }
        else {
            $result = trim($a);
        }
    }
    else {
        if (strtolower(trim($b)) == "d") {
            if (!isdate($a)) {
                $result = $c;
            }
            else {
                $result = trim($a);
            }
        }
        else {
            $result = $a;
        }
    }
}
return($result);
}
</code>```

答:
Perhaps, this isn't really an answer since I don't know what the original function is for and to be honest I don't care. Whatever, you can do several simplifications to make it more readable, to avoid duplicate processing, the useless $result variable and in particular to remove these unreadable nested if/else, in other words to remove all this useless noise:

```<code>function mystery($a, $b, $c) {
    $trima = trim($a);

    if ( empty($trima) )
        return $c;

    $b = strtolower(trim($b));

    if ( $b == "n" )
        return is_numeric($trima) ? $trima : $c ;

    if ( $b == "d" )
        return isdate($trima) ? $trima : $c ;

    return $a;
}
</code>```

I hope this will help you to understand what this function is supposed to do (perhaps a context will be helpful).

Title: Is there an isdate PHP function?

Body:
I saw an inbuilt function called isdate in the user function below and when I checked the PHP documentation I didn't find it. Does it exist and what does it do; or is this simply a typo?

function mystery($a, $b, $c) {
$result = null;
if (strlen(trim($a)) == 0) {
    $result = $c;
}
else {
    if (strtolower(trim($b)) == "n") {
        if (!is_numeric($a)) {
            $result = $c;
        }
        else {
            $result = trim($a);
        }
    }
    else {
        if (strtolower(trim($b)) == "d") {
            if (!isdate($a)) {
                $result = $c;
            }
            else {
                $result = trim($a);
            }
        }
        else {
            $result = $a;
        }
    }
}
return($result);
}

Body:
Perhaps, this isn't really an answer since I don't know what the original function is for and to be honest I don't care. Whatever, you can do several simplifications to make it more readable, to avoid duplicate processing, the useless $result variable and in particular to remove these unreadable nested if/else, in other words to remove all this useless noise:

function mystery($a, $b, $c) {
    $trima = trim($a);

    if ( empty($trima) )
        return $c;

    $b = strtolower(trim($b));

    if ( $b == "n" )
        return is_numeric($trima) ? $trima : $c ;

    if ( $b == "d" )
        return isdate($trima) ? $trima : $c ;

    return $a;
}

I hope this will help you to understand what this function is supposed to do (perhaps a context will be helpful).


问:
how to reassemble tcp segment?
im now developing a project using winpcap..as i have known packets being sniffed are usually fragmented packets.

how to reassemble this TCP segements?..any ideas, suggestion or tutorials available?..

this i assume to be the only way i can view the HTTP header...

thanks!..

答: libtins provides classes to perform TCP stream reassembly in a very high level way, so you don't have to worry about TCP internals to do so.</p>

Title: how to reassemble tcp segment?


问:
QGIS - Composer
My question concerns the general purpose of the composer in qgis. My first idea was that with the composer you can "save" different layer combinations with different style to gain the possibility the have different "views" on the same data. However I realized when I change the map in QGIS, the information in the composer is also refreshed. To clarify my intent I want to give a small example:
Assume you have the gas stations of different companies for a country and you want to produce a map with all companies and maps containing only the gas stations of a certain company. So in the beginning I though I just create different composers to gain different maps but I somehow fail. </p>

答:
For large projects with a large number of composers, it's better to use layer presets and the "Follow visibility preset" option within the composer.

This is because when using "lock layers" and "lock layer styles", it saves all of the layers and their styles and properties. When it does this for each composer, it can quickly balloon the size of the QGIS file. This can make it take an extremely long time to open a project, cause a lot of performance issues, and inevitably will corrupt your QGIS file. Following a visibility preset simply references the style for the layer rather than duplicates it.

E.g. I had an employee whose QGIS file got corrupted and I had him send it and the backup files to me. On review, the primary QGIS file was empty, and the backup file was an exceptional 65mb. The markup behind the QGIS file was nearly a million lines long. It was corrupted because it got cut off, so I'm not even sure how long it might have been in it's entirety. This was a result of him having about 30 layers and over 100 composers that each had the layers locked. It also explained why he was the only one who was constantly complaining about his laptop being too slow for the work :)

Title: QGIS - Composer


问:
Create a Legend on a Folium map
The Folium documentation is incomplete at this time: https://folium.readthedocs.io/en/latest/

According to the index of the incomplete docs Legends and Layers are, or will be supported. I've spent some time looking for examples on the web but have found nothing so far. If anyone has any idea how to create these things, or can point me to a document or tutorial I would be most grateful.

答:
Try using

```<code>feature_group = FeatureGroup(name='Layer1')
feature_group2 = FeatureGroup(name='Layer2')
</code>```

Then add to your map

```<code>map = folium.Map(zoom_start=6)

# coordinates to locate your marker
COORDINATE = [(333,333)] # example coordinate
COORDINATE2 = [(444,444)]

# add marker to your map
folium.Marker(location=COORDINATE).add_to(feature_group)
folium.Marker(location=COORDINATE2).add_to(feature_group2)

map.add_child(feature_group)
map.add_child(feature_group2)

# turn on layer control
map.add_child(folium.map.LayerControl())
</code>```

Title: Create a Legend on a Folium map

Body:
Try using

feature_group = FeatureGroup(name='Layer1')
feature_group2 = FeatureGroup(name='Layer2')

Then add to your map

map = folium.Map(zoom_start=6)

# coordinates to locate your marker
COORDINATE = [(333,333)] # example coordinate
COORDINATE2 = [(444,444)]

# add marker to your map
folium.Marker(location=COORDINATE).add_to(feature_group)
folium.Marker(location=COORDINATE2).add_to(feature_group2)

map.add_child(feature_group)
map.add_child(feature_group2)

# turn on layer control
map.add_child(folium.map.LayerControl())


答:
Both fadeOut and fadeIn are asynchronous functions.  Meaning, that once you call them, the action will happen in the background and your code immediately returns and continues onto the next statement.

In your example, you start a fadeout over a second, but as soon as it starts you replace the content of the div and fade in.  Because the fadeout has only run for a microsecond, jquery internally cancels the fadeOut action and runs a fadeIn which doesnt need to do anything.

Both these functions take a second parameter which is a 'complete' callback.  You should structure your code as follows.

```<code>  $('#position-name').html('Successfuly Changed').fadeOut(1000,
    function () {
      $('#position-name').html('New Name').fadeIn();
  });
</code>```

Title: Why not fading out and fading in jquery?

Body:
Both fadeOut and fadeIn are asynchronous functions.  Meaning, that once you call them, the action will happen in the background and your code immediately returns and continues onto the next statement.

In your example, you start a fadeout over a second, but as soon as it starts you replace the content of the div and fade in.  Because the fadeout has only run for a microsecond, jquery internally cancels the fadeOut action and runs a fadeIn which doesnt need to do anything.

Both these functions take a second parameter which is a 'complete' callback.  You should structure your code as follows.

  $('#position-name').html('Successfuly Changed').fadeOut(1000,
    function () {
      $('#position-name').html('New Name').fadeIn();
  });


问:
How to write unit test with mocks when method uses ObjectMapper.writeValueAsString
I have a SpringMVC project. The method from my FooController that I want to test is:

```<code>@GetMapping("/view/{fooId}")
public String view(@PathVariable String fooId, Model model) throws FooNotFoundException, JsonProcessingException {
    Foo foo = fooService.getFoo(fooId);
    model.addAttribute("fooId", foo.getId());
    model.addAttribute("foo", new ObjectMapper().writeValueAsString(foo));
    return "foo/view";
}
</code>```

The test that I've written is:

```<code>public class FooControllerTest {
    @Mock
    private Foo mockFoo;
    @Mock
    private FooService mockFooService;
    @InjectMocks
    private FooController controller;
    private MockMvc mockMvc;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
    }

    @Test
    public void testView() throws Exception {
        String fooId = "fooId";
        when(mockFooService.getFoo(fooId)).thenReturn(mockFoo);
        when(mockFoo.getId()).thenReturn(fooId);

        mockMvc.perform(get("/foo/view/" + fooId))
                .andExpect(status().isOk())
                .andExpect(model().attribute("fooId", fooId))
                .andExpect(model().attributeExists("foo"))
                .andExpect(forwardedUrl("foo/view"));
    }

}
</code>```

This test fails with java.lang.AssertionError: No ModelAndView found.
When I debug the test, I see it goes wrong when my mockFoo is given to new ObjectMapper.writeValueAsString(). So I think mocked objects cannot be serialized. How do I work around this, how do I make my test pass?

What have I tried already:

I commented the line model.addAttribute("foo", new ObjectMapper().writeValueAsString(foo)); in FooController, this way the test worked (but not the way I want my method to work)! So now I know this is where it goes wrong.

I commented the line .andExpect(model().attributeExists("foo")) in FooControllerTest, it still produced the above AssertionError.

Googling and StackOverflowing, but I could find something usable.

答:
Try adding the Spy annotation when doing the InjectMocks annotation like this

```<code>@InjectMocks
@Spy
private FooController controller;
</code>```

And yes do not instantiate ObjectMapper or any classes inside the controller. You will be forced to use PowerMockito if you do so. Try injecting them in the controller like @Ruben Mentioned.

Injecting dependencies is always easier for testing.

Body:
I have a SpringMVC project. The method from my FooController that I want to test is:

@GetMapping("/view/{fooId}")
public String view(@PathVariable String fooId, Model model) throws FooNotFoundException, JsonProcessingException {
    Foo foo = fooService.getFoo(fooId);
    model.addAttribute("fooId", foo.getId());
    model.addAttribute("foo", new ObjectMapper().writeValueAsString(foo));
    return "foo/view";
}

The test that I've written is:

public class FooControllerTest {
    @Mock
    private Foo mockFoo;
    @Mock
    private FooService mockFooService;
    @InjectMocks
    private FooController controller;
    private MockMvc mockMvc;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
    }

    @Test
    public void testView() throws Exception {
        String fooId = "fooId";
        when(mockFooService.getFoo(fooId)).thenReturn(mockFoo);
        when(mockFoo.getId()).thenReturn(fooId);

        mockMvc.perform(get("/foo/view/" + fooId))
                .andExpect(status().isOk())
                .andExpect(model().attribute("fooId", fooId))
                .andExpect(model().attributeExists("foo"))
                .andExpect(forwardedUrl("foo/view"));
    }

}

This test fails with java.lang.AssertionError: No ModelAndView found.
When I debug the test, I see it goes wrong when my mockFoo is given to new ObjectMapper.writeValueAsString(). So I think mocked objects cannot be serialized. How do I work around this, how do I make my test pass?

What have I tried already:

I commented the line model.addAttribute("foo", new ObjectMapper().writeValueAsString(foo)); in FooController, this way the test worked (but not the way I want my method to work)! So now I know this is where it goes wrong.

I commented the line .andExpect(model().attributeExists("foo")) in FooControllerTest, it still produced the above AssertionError.

Googling and StackOverflowing, but I could find something usable.

Body:
Try adding the Spy annotation when doing the InjectMocks annotation like this

@InjectMocks
@Spy
private FooController controller;

And yes do not instantiate ObjectMapper or any classes inside the controller. You will be forced to use PowerMockito if you do so. Try injecting them in the controller like @Ruben Mentioned.

Injecting dependencies is always easier for testing.


问:
Microsoft Azure Table Storage - Create New Table
I'm new to Azure Table Storage, and after creating an accound, I'm completely unable to figure out how to create a table. I have downloaded the Storage Explorer, but I only get error messages trying to connect to the account.

So, a very simple question, how do I crate a table?

答:
As far as I know, the newest Storage Explorer support three ways to connect to your azure storage account.

I suggest you could try to connect to the azure storage account by using your azure account username and password.

1.Click the icon as the image shows:

2.Sign in the azure account as below image shows:

3.Use your username and password login in.

4.After login success, you could locate your storage account's tag and right click the table selection to create a new table:

Besides, you could also use account key and account name to connect to your azure storage account in Storage Explorer.

I suggest you could refer to below steps:

1.Select use a storage account name and key click next:

2.Find your storage account name and key in the portal and add them in the storage explorer.

3.At last you could find your storage account in the local and attached tag as below.

Right click the tables, you could create new table.

If you want to know how to create table by codes, I suggest you could refer to this article.

Note: This is C# version, if you want to change the language version, you could refer to below image:


问:
Lighttpd url.rewrite-if-not-file in subdir
I need some help with an url.rewrite-if-not-file.

I am using a Zend Framework based application so most of my requests are to be treated by
/index.php and so far everything is good.

However, I have some sub-applications that'll have to work without that redirect.

For example, I need all requests in the dir /events to lead to that directoriy-index file.

```<code>"/events/" => "/events/index.php",
"/events/?foo=bar" => "/events/index.php?foo=bar",
"/events/create/" => "/events/create/index.php"
</code>```

And so on

What I have so far is

```<code>url.rewrite-if-not-file = (
   "^/events/(.*)/$" => "/events/$1/index.php"
)
</code>```

But when it comes to capturing the GET variables and place them right, I am lost.

I have tried

```<code>"^/events/(.*)\??(.*)$" => "/events/$1/index.php?$2"
</code>```

But that doesn't work.

Thankful for any help.

答:
Read the last section of the docs.

So try this:

```<code>"^/events/([^\?]*)(\?(.*))?$" => "/events/$1/index.php?$3"
</code>```

The difference is that the . in your first subpattern was greedy so it would have gobbled up the ? character, preventing it from ever matching the other part...

Body:
I need some help with an url.rewrite-if-not-file.

I am using a Zend Framework based application so most of my requests are to be treated by
/index.php and so far everything is good.

However, I have some sub-applications that'll have to work without that redirect.

For example, I need all requests in the dir /events to lead to that directoriy-index file.

"/events/" => "/events/index.php",
"/events/?foo=bar" => "/events/index.php?foo=bar",
"/events/create/" => "/events/create/index.php"

And so on

What I have so far is

url.rewrite-if-not-file = (
   "^/events/(.*)/$" => "/events/$1/index.php"
)

But when it comes to capturing the GET variables and place them right, I am lost.

I have tried

"^/events/(.*)\??(.*)$" => "/events/$1/index.php?$2"

But that doesn't work.

Thankful for any help.

Body:
Read the last section of the docs.

So try this:

"^/events/([^\?]*)(\?(.*))?$" => "/events/$1/index.php?$3"

The difference is that the . in your first subpattern was greedy so it would have gobbled up the ? character, preventing it from ever matching the other part...