问:
Return Viewmodel to HttpPost ActionResult
I'm trying to update my collection of users' roles in my ASP.NET Identity project, but I'm currently stuck because I'm getting a null UsersAndRolesDictionary property in the ViewModel sent to my [HttpPost] method.

Here is my ViewModel, UpdateUserRolesViewModel:

```<code>namespace Project_Name.Models
{
    public class UpdateUserRolesViewModel
    {
        public IDictionary<ApplicationUser, ICollection<IdentityUserRole>> UsersAndRolesDictionary { get; set; } // <-- This is returning null currently
    }
}
</code>```

Here's my HomeController's methods:

```<code>[Authorize(Roles = "Admin")]
public ActionResult RoleManager()
{
    ViewBag.Message = "Role Management Page";

    var databaseContext = new ApplicationDbContext();           // Get the Database Context
    var users = databaseContext.Users.Include(u => u.Roles);    // Get all users from the Database and their Roles

    var newDict = new Dictionary<ApplicationUser, ICollection<IdentityUserRole>>();

    // Add each user and their roles to the dictionary
    foreach (var user in users)
    {
        newDict.Add(user, user.Roles);
    }

    // Update the ViewModel with the collection of users and roles
    var updateUserRolesViewModel = new UpdateUserRolesViewModel {UsersAndRolesDictionary = newDict};

    return View(updateUserRolesViewModel);
}

[HttpPost]
[Authorize(Roles = "Admin")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> UpdateUsersRolesAsync(UpdateUserRolesViewModel updateUserRolesViewModel)
{
    try
    {
        //TODO: Attempt to update the user roles or delete the user
        return View("RoleManager");
    }
    catch
    {
        //TODO: Properly catch errors
        return View("RoleManager");
    }
}
</code>```

Here is my View, RoleManager:

```<code>@using Project_Name.Models

@model UpdateUserRolesViewModel

@{
    ViewBag.Title = "Role Manager";
    var databaseContext = new ApplicationDbContext();   // Get the Database Context
    var roles = databaseContext.Roles;                  // Get all Roles from the database, use this to compare against
}

<h2>@ViewBag.Title</h2>

<div class="row">
    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
        @using (Html.BeginForm("UpdateUsersRolesAsync", "Home", FormMethod.Post))
        {
            @Html.AntiForgeryToken()

            <div class="form-group">
                <div class="table-responsive">
                    <table class="table table-striped table-bordered table-hover">
                        <thead>
                            <tr>
                                <th>Email</th>
                                <th>Roles</th>
                                <th>Delete User?</th>
                            </tr>
                        </thead>
                        <tbody>
                            @{
                                int i = 0; // Used to make unique IDs for the user's table row, and deleteUserCheckbox
                                int j = 0; // Used to make unique IDs for the role checkboxes
                                foreach (var user in Model.UsersAndRolesDictionary.Keys)
                                {
                                    i++;
                                    <tr id="userTableRow_@i">
                                        <td>@user.Email</td>
                                        <td>
                                            @* Show each role availabe as a checkbox. Check them if the user has that role. *@
                                            @foreach (var role in roles)
                                            {
                                                @Html.CheckBox("userRoleCheckbox_" + j++, user.Roles.Any(identityUserRole => identityUserRole.RoleId.Contains(role.Id)))
                                                <span>@role.Name</span>
                                                <br />
                                            }
                                        </td>
                                        <td>
                                            @Html.CheckBox("deleteUserCheckbox_" + i)
                                            <span>Delete User</span>
                                        </td>
                                    </tr>
                                }
                            }
                        </tbody>
                    </table>
                </div>

                @* Reset and Submit buttons *@
                <div class="col-lg-2 col-lg-push-8 col-md-2 col-md-push-8 col-sm-2 col-sm-push-8 col-xs-2 col-xs-push-8">
                    <input type="reset" class="btn btn-danger btn-block" value="Reset" />
                </div>
                <div class="col-lg-2 col-lg-push-8 col-md-2 col-md-push-8 col-sm-2 col-sm-push-8 col-xs-2 col-xs-push-8">
                    <input type="submit" class="btn btn-primary btn-block" value="Submit" />
                </div>

            </div>
        }
    </div>
</div>
</code>```

I'm using the dictionary UsersAndRolesDictionary to collect all the users and their roles, then enumerating through that to produce my view in the form of a table.

I'm hoping to change the checkbox values of potential multiple users, then passing that updated ViewModel to my [HttpPost] UpdateUsersRolesAsync method in order to update my user roles, but right now I'm getting a null value for the UsersAndRolesDictionary property and I'm not sure why or how to fix it.

Thanks to Stephen Muecke's links/answers in the comments I was able to answer this question. See my answer post below.

答:
Following the suggestions of Stephen Muecke in the comments, I have gotten a valid ViewModel to be returned.

Added/updated three ViewModels that combine together:

The first being RoleViewModel:

```<code>public class RoleViewModel
{
    public string Id { get; set; }
    public string Name { get; set; }
    public bool IsSelected { get; set; }
}
</code>```

Second being UserViewModel:

```<code>public class UserViewModel
{
    public string Id { get; set; }
    public string Email { get; set; }
    public List<RoleViewModel> RoleViewModels { get; set; }
    public bool DeleteUser { get; set; } // Doesn't work yet, might be in the wrong place
}
</code>```

And finally the third being an updated version of UpdateUserRoleViewModel:

```<code>public class UpdateUserRolesViewModel
{
    public int Id { get; set; }
    public List<UserViewModel> UserViewModels { get; set; }
}
</code>```

In my updated HomeController are the methods again:

```<code>[Authorize(Roles = "Admin")]
public ActionResult RoleManager()
{
    ViewBag.Message = "Role Management Page";

    var databaseContext = new ApplicationDbContext();                   // Get the Database Context
    var users = databaseContext.Users.Include(u => u.Roles).ToList();   // Get all users from the Database and their Roles

    // Create the UpdateUserRolesViewModel
    var updateUserRolesViewModel = new UpdateUserRolesViewModel
    {
        Id = 0, // Not sure what else the Id would be
        UserViewModels = new List<UserViewModel>()
    };

    // Add each user to the UserViewModels list
    for (int i = 0; i < users.Count(); i++)
    {
        var userViewModel = new UserViewModel
        {
            Id = users.AsEnumerable().ElementAt(i).Id,
            Email = users.AsEnumerable().ElementAt(i).UserName,
            RoleViewModels = new List<RoleViewModel>(),
            DeleteUser = false
        };

        // Add each role from the Roles table to the RoleViewModels list, check if user has that role
        foreach (var role in databaseContext.Roles)
        {
            var roleViewModel = new RoleViewModel
            {
                Id = role.Id,
                Name = role.Name,
                IsSelected = users.AsEnumerable().ElementAt(i).Roles.Any(identityUserRole => identityUserRole.RoleId.Contains(role.Id))
            };

            userViewModel.RoleViewModels.Add(roleViewModel);
        }

        updateUserRolesViewModel.UserViewModels.Add(userViewModel);
    }

    return View(updateUserRolesViewModel);
}

[HttpPost]
[Authorize(Roles = "Admin")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> UpdateUsersRolesAsync(UpdateUserRolesViewModel updateUserRolesViewModel)
{
    try
    {
        // Attempt to update the user roles
        foreach (var user in updateUserRolesViewModel.UserViewModels)
        {
            // Delete user
            //TODO: Prompt user to confirm deletion if one or more people are being deleted
            if (user.DeleteUser)
            {
                var userToDelete = await UserManager.FindByIdAsync(user.Id);    // Get the ApplicationUser object of who we want to delete
                await UserManager.DeleteAsync(userToDelete);                    // Delete the user
                continue;                                                       // Don't try to update the roles of a deleted user.
            }

            // Remove all roles from the User
            var rolesToRemove = await UserManager.GetRolesAsync(user.Id);
            await UserManager.RemoveFromRolesAsync(user.Id, rolesToRemove.ToArray());

            // Add roles to the User
            foreach (var roleViewModel in user.RoleViewModels.Where(r => r.IsSelected))
            {
                await UserManager.AddToRoleAsync(user.Id, roleViewModel.Name);
            }
        }

        return RedirectToAction("RoleManager");
    }
    catch
    {
        //TODO: Properly catch errors
        return RedirectToAction("RoleManager");
    }
}
</code>```

Finally, here is my View, RoleManager

```<code>@using Project_Name.ViewModels

@model UpdateUserRolesViewModel

@{
    ViewBag.Title = "Role Manager";
}

@* Debugging text *@
@foreach (var user in Model.UserViewModels)
{
    <div>User ID: @user.Id</div>
    <div>User Name: @user.Email</div>
    <p>
        @foreach (var roleViewModel in user.RoleViewModels.Where(r => r.IsSelected))
        {
            <div>Role ID: @roleViewModel.Id</div>
            <div>Role Name: @roleViewModel.Name</div>
        }
    </p>
    <hr />
}

<h2>@ViewBag.Title</h2>

<div class="row">
    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
        @using (Html.BeginForm("UpdateUsersRolesAsync", "Home", FormMethod.Post))
        {
            @Html.AntiForgeryToken()
            @Html.HiddenFor(m => m.Id)
            <div class="form-group">
                <div class="table-responsive">
                    <table class="table table-striped table-bordered table-hover">
                        <thead>
                            <tr>
                                <th>Email</th>
                                <th>Roles</th>
                                <th>Delete User?</th>
                            </tr>
                        </thead>
                        <tbody>
                            @for (int i = 0; i < Model.UserViewModels.Count; i++)
                            {
                                <tr id="userTableRow_@i">
                                    <td>
                                        @Html.HiddenFor(m => m.UserViewModels[i].Id)
                                        @Html.HiddenFor(m => m.UserViewModels[i].Email)
                                        @Model.UserViewModels[i].Email
                                    </td>
                                    <td>
                                        @for (int j = 0; j < Model.UserViewModels[i].RoleViewModels.Count; j++)
                                        {
                                            @Html.HiddenFor(m => m.UserViewModels[i].RoleViewModels[j].Id)
                                            @Html.HiddenFor(m => m.UserViewModels[i].RoleViewModels[j].Name)
                                            @Html.CheckBoxFor(m => m.UserViewModels[i].RoleViewModels[j].IsSelected)
                                            @Html.DisplayTextFor(m => m.UserViewModels[i].RoleViewModels[j].Name)
                                            <br/>
                                        }
                                    </td>
                                    <td>
                                        @Html.CheckBoxFor(m => m.UserViewModels[i].DeleteUser)
                                        @Html.DisplayNameFor(m => m.UserViewModels[i].DeleteUser)
                                    </td>
                                </tr>
                            }
                        </tbody>
                    </table>
                </div>

                @* Reset and Submit buttons *@
                <div class="col-lg-2 col-lg-push-8 col-md-2 col-md-push-8 col-sm-2 col-sm-push-8 col-xs-2 col-xs-push-8">
                    <input type="reset" class="btn btn-danger btn-block" value="Reset" />
                </div>
                <div class="col-lg-2 col-lg-push-8 col-md-2 col-md-push-8 col-sm-2 col-sm-push-8 col-xs-2 col-xs-push-8">
                    <input type="submit" class="btn btn-primary btn-block" value="Submit" />
                </div>

            </div>
        }
    </div>
</div>
</code>```

This now updates the user's Roles, and Deletes them (though there is no confirmation check so be careful with that!)

Body:
I'm trying to update my collection of users' roles in my ASP.NET Identity project, but I'm currently stuck because I'm getting a null UsersAndRolesDictionary property in the ViewModel sent to my [HttpPost] method.

Here is my ViewModel, UpdateUserRolesViewModel:

namespace Project_Name.Models
{
    public class UpdateUserRolesViewModel
    {
        public IDictionary<ApplicationUser, ICollection<IdentityUserRole>> UsersAndRolesDictionary { get; set; } // <-- This is returning null currently
    }
}

Here's my HomeController's methods:

[Authorize(Roles = "Admin")]
public ActionResult RoleManager()
{
    ViewBag.Message = "Role Management Page";

    var databaseContext = new ApplicationDbContext();           // Get the Database Context
    var users = databaseContext.Users.Include(u => u.Roles);    // Get all users from the Database and their Roles

    var newDict = new Dictionary<ApplicationUser, ICollection<IdentityUserRole>>();

    // Add each user and their roles to the dictionary
    foreach (var user in users)
    {
        newDict.Add(user, user.Roles);
    }

    // Update the ViewModel with the collection of users and roles
    var updateUserRolesViewModel = new UpdateUserRolesViewModel {UsersAndRolesDictionary = newDict};

    return View(updateUserRolesViewModel);
}

[HttpPost]
[Authorize(Roles = "Admin")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> UpdateUsersRolesAsync(UpdateUserRolesViewModel updateUserRolesViewModel)
{
    try
    {
        //TODO: Attempt to update the user roles or delete the user
        return View("RoleManager");
    }
    catch
    {
        //TODO: Properly catch errors
        return View("RoleManager");
    }
}

Here is my View, RoleManager:

@using Project_Name.Models

@model UpdateUserRolesViewModel

@{
    ViewBag.Title = "Role Manager";
    var databaseContext = new ApplicationDbContext();   // Get the Database Context
    var roles = databaseContext.Roles;                  // Get all Roles from the database, use this to compare against
}

@ViewBag.Title

        @using (Html.BeginForm("UpdateUsersRolesAsync", "Home", FormMethod.Post))
        {
            @Html.AntiForgeryToken()

                                Email
                                Roles
                                Delete User?

                            @{
                                int i = 0; // Used to make unique IDs for the user's table row, and deleteUserCheckbox
                                int j = 0; // Used to make unique IDs for the role checkboxes
                                foreach (var user in Model.UsersAndRolesDictionary.Keys)
                                {
                                    i++;

                                        @user.Email

                                            @* Show each role availabe as a checkbox. Check them if the user has that role. *@
                                            @foreach (var role in roles)
                                            {
                                                @Html.CheckBox("userRoleCheckbox_" + j++, user.Roles.Any(identityUserRole => identityUserRole.RoleId.Contains(role.Id)))
                                                @role.Name

                                            }

                                            @Html.CheckBox("deleteUserCheckbox_" + i)
                                            Delete User

                                }
                            }

                @* Reset and Submit buttons *@

                    <input type="reset" class="btn btn-danger btn-block" value="Reset" />

                    <input type="submit" class="btn btn-primary btn-block" value="Submit" />

        }

I'm using the dictionary UsersAndRolesDictionary to collect all the users and their roles, then enumerating through that to produce my view in the form of a table.

I'm hoping to change the checkbox values of potential multiple users, then passing that updated ViewModel to my [HttpPost] UpdateUsersRolesAsync method in order to update my user roles, but right now I'm getting a null value for the UsersAndRolesDictionary property and I'm not sure why or how to fix it.

Thanks to Stephen Muecke's links/answers in the comments I was able to answer this question. See my answer post below.

Body:
Following the suggestions of Stephen Muecke in the comments, I have gotten a valid ViewModel to be returned.

Added/updated three ViewModels that combine together:

The first being RoleViewModel:

public class RoleViewModel
{
    public string Id { get; set; }
    public string Name { get; set; }
    public bool IsSelected { get; set; }
}

Second being UserViewModel:

public class UserViewModel
{
    public string Id { get; set; }
    public string Email { get; set; }
    public List<RoleViewModel> RoleViewModels { get; set; }
    public bool DeleteUser { get; set; } // Doesn't work yet, might be in the wrong place
}

And finally the third being an updated version of UpdateUserRoleViewModel:

public class UpdateUserRolesViewModel
{
    public int Id { get; set; }
    public List<UserViewModel> UserViewModels { get; set; }
}

In my updated HomeController are the methods again:

[Authorize(Roles = "Admin")]
public ActionResult RoleManager()
{
    ViewBag.Message = "Role Management Page";

    var databaseContext = new ApplicationDbContext();                   // Get the Database Context
    var users = databaseContext.Users.Include(u => u.Roles).ToList();   // Get all users from the Database and their Roles

    // Create the UpdateUserRolesViewModel
    var updateUserRolesViewModel = new UpdateUserRolesViewModel
    {
        Id = 0, // Not sure what else the Id would be
        UserViewModels = new List<UserViewModel>()
    };

    // Add each user to the UserViewModels list
    for (int i = 0; i < users.Count(); i++)
    {
        var userViewModel = new UserViewModel
        {
            Id = users.AsEnumerable().ElementAt(i).Id,
            Email = users.AsEnumerable().ElementAt(i).UserName,
            RoleViewModels = new List<RoleViewModel>(),
            DeleteUser = false
        };

        // Add each role from the Roles table to the RoleViewModels list, check if user has that role
        foreach (var role in databaseContext.Roles)
        {
            var roleViewModel = new RoleViewModel
            {
                Id = role.Id,
                Name = role.Name,
                IsSelected = users.AsEnumerable().ElementAt(i).Roles.Any(identityUserRole => identityUserRole.RoleId.Contains(role.Id))
            };

            userViewModel.RoleViewModels.Add(roleViewModel);
        }

        updateUserRolesViewModel.UserViewModels.Add(userViewModel);
    }

    return View(updateUserRolesViewModel);
}

[HttpPost]
[Authorize(Roles = "Admin")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> UpdateUsersRolesAsync(UpdateUserRolesViewModel updateUserRolesViewModel)
{
    try
    {
        // Attempt to update the user roles
        foreach (var user in updateUserRolesViewModel.UserViewModels)
        {
            // Delete user
            //TODO: Prompt user to confirm deletion if one or more people are being deleted
            if (user.DeleteUser)
            {
                var userToDelete = await UserManager.FindByIdAsync(user.Id);    // Get the ApplicationUser object of who we want to delete
                await UserManager.DeleteAsync(userToDelete);                    // Delete the user
                continue;                                                       // Don't try to update the roles of a deleted user.
            }

            // Remove all roles from the User
            var rolesToRemove = await UserManager.GetRolesAsync(user.Id);
            await UserManager.RemoveFromRolesAsync(user.Id, rolesToRemove.ToArray());

            // Add roles to the User
            foreach (var roleViewModel in user.RoleViewModels.Where(r => r.IsSelected))
            {
                await UserManager.AddToRoleAsync(user.Id, roleViewModel.Name);
            }
        }

        return RedirectToAction("RoleManager");
    }
    catch
    {
        //TODO: Properly catch errors
        return RedirectToAction("RoleManager");
    }
}

Finally, here is my View, RoleManager

@using Project_Name.ViewModels

@model UpdateUserRolesViewModel

@{
    ViewBag.Title = "Role Manager";
}

@* Debugging text *@
@foreach (var user in Model.UserViewModels)
{
    <div>User ID: @user.Id</div>
    <div>User Name: @user.Email</div>
    <p>
        @foreach (var roleViewModel in user.RoleViewModels.Where(r => r.IsSelected))
        {
            <div>Role ID: @roleViewModel.Id</div>
            <div>Role Name: @roleViewModel.Name</div>
        }
    </p>
    <hr />
}

<h2>@ViewBag.Title</h2>

<div class="row">
    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
        @using (Html.BeginForm("UpdateUsersRolesAsync", "Home", FormMethod.Post))
        {
            @Html.AntiForgeryToken()
            @Html.HiddenFor(m => m.Id)
            <div class="form-group">
                <div class="table-responsive">
                    <table class="table table-striped table-bordered table-hover">
                        <thead>
                            <tr>
                                <th>Email</th>
                                <th>Roles</th>
                                <th>Delete User?</th>
                            </tr>
                        </thead>
                        <tbody>
                            @for (int i = 0; i < Model.UserViewModels.Count; i++)
                            {
                                <tr id="userTableRow_@i">
                                    <td>
                                        @Html.HiddenFor(m => m.UserViewModels[i].Id)
                                        @Html.HiddenFor(m => m.UserViewModels[i].Email)
                                        @Model.UserViewModels[i].Email
                                    </td>
                                    <td>
                                        @for (int j = 0; j < Model.UserViewModels[i].RoleViewModels.Count; j++)
                                        {
                                            @Html.HiddenFor(m => m.UserViewModels[i].RoleViewModels[j].Id)
                                            @Html.HiddenFor(m => m.UserViewModels[i].RoleViewModels[j].Name)
                                            @Html.CheckBoxFor(m => m.UserViewModels[i].RoleViewModels[j].IsSelected)
                                            @Html.DisplayTextFor(m => m.UserViewModels[i].RoleViewModels[j].Name)
                                            <br/>
                                        }
                                    </td>
                                    <td>
                                        @Html.CheckBoxFor(m => m.UserViewModels[i].DeleteUser)
                                        @Html.DisplayNameFor(m => m.UserViewModels[i].DeleteUser)
                                    </td>
                                </tr>
                            }
                        </tbody>
                    </table>
                </div>

                @* Reset and Submit buttons *@
                <div class="col-lg-2 col-lg-push-8 col-md-2 col-md-push-8 col-sm-2 col-sm-push-8 col-xs-2 col-xs-push-8">
                    <input type="reset" class="btn btn-danger btn-block" value="Reset" />
                </div>
                <div class="col-lg-2 col-lg-push-8 col-md-2 col-md-push-8 col-sm-2 col-sm-push-8 col-xs-2 col-xs-push-8">
                    <input type="submit" class="btn btn-primary btn-block" value="Submit" />
                </div>

            </div>
        }
    </div>
</div>

This now updates the user's Roles, and Deletes them (though there is no confirmation check so be careful with that!)


来源: stackexchange

问:
Keras VS Tensorflow for developing CNN or RNN
I am going to start a Deep learning project on image processing hopefully it would be CNN problem as we know Tensorflow and Keras both are very good frameworks to work on any deep learning problem. I am familiar with both of them and had coded in both but i want to identify the reasons (if any) which leads a deep learning project to a specific frame work.</p>

答:
Have in mind that Keras can actually run on Tensorflow if you configure in such way. Keras also supporst Theano as a backend.

When you configure your installation, you include in your keras.json file what backend you wish to use (after you have installed it properly). In case you wish to use Tensorflow as backend your configuration file should look something like:

```<code>{
    "image_data_format": "channels_last",
    "epsilon": 1e-07,
    "floatx": "float32",
    "backend": "tensorflow"
}
</code>```

Keras provides an abstraction to Tensorflow's (or your selected backend)  functions and framework, possibly making it easier to learn and write, so you could try focusing on Keras first, and if it does not fit your need migrate to use Tensorflow direcly.

There is no unbiased or absolute answer regarding which one you should use, so trying them to see which one is a better fit could work out for you.

ContentLicense: CC BY-SA 3.0

Body:
Have in mind that Keras can actually run on Tensorflow if you configure in such way. Keras also supporst Theano as a backend.

When you configure your installation, you include in your keras.json file what backend you wish to use (after you have installed it properly). In case you wish to use Tensorflow as backend your configuration file should look something like:

{
    "image_data_format": "channels_last",
    "epsilon": 1e-07,
    "floatx": "float32",
    "backend": "tensorflow"
}

Keras provides an abstraction to Tensorflow's (or your selected backend)  functions and framework, possibly making it easier to learn and write, so you could try focusing on Keras first, and if it does not fit your need migrate to use Tensorflow direcly.

There is no unbiased or absolute answer regarding which one you should use, so trying them to see which one is a better fit could work out for you.


问:
Robocopy copy contents of current folder
How would you translate this xcopy command into Robocopy:

```<code>xcopy *.* "C:\DestinationFolder\"
</code>```

Keeping in mind that the current folder where the command is run changes dynamically (and hence the source folder is unknown in advance).

Thanks.

答:
As an addition:
If robocopy is started from an administrator console, the current folder "." will point to Windows\system32.

You can use the following commands at the top of your batch file to fix this:

```<code>@setlocal enableextensions
@cd /d "%~dp0"
</code>```

Body:
How would you translate this xcopy command into Robocopy:

xcopy *.* "C:\DestinationFolder\"

Keeping in mind that the current folder where the command is run changes dynamically (and hence the source folder is unknown in advance).

Thanks.

Body:
As an addition:
If robocopy is started from an administrator console, the current folder "." will point to Windows\system32.

You can use the following commands at the top of your batch file to fix this:

@setlocal enableextensions
@cd /d "%~dp0"


问:
Combine string Scrapy python
I have a question about how to combine a set of values when using scrapy so that my json output is cleaner.  Here is what I have:

```<code>import scrapy
from scrapy.contrib.loader import ItemLoader
from scrapy.contrib.loader.processor import TakeFirst, MapCompose, Join

class LLPubs (scrapy.Spider):
    name = "linlinks"
    start_urls = [
        'http://www.linnaeuslink.org/records/record/1',
        'http://www.linnaeuslink.org/records/record/2',
        'http://www.linnaeuslink.org/records/record/2a',
        'http://www.linnaeuslink.org/records/record/10',
]

    def parse(self, response):
        for item in response.css('div.item'):
            yield {
                'text': item.css('div.field.soulsbyNo .value span::text').extract(),
                'uniformtitle': item.css('div.field.uniformTitle .value span::text').extract(),
                'title': item.css('div.field.title .value span::text').extract(),
                'opac': item.css('div.field.localControlNo .value span::text').extract(),
                'digitalcopyurl': .join(response.css('div#digitalLinks li a').xpath('@href').extract()),
                'name': response.css('div#digitalLinks li a span::text').extract(),
                }
</code>```

The "digitalcopyurl" is where I am having the problem.  I guess I can't use "join" in this way but I'm not sure what to modify.  Here's an example of what the JSON looks like now:

```<code>{"text": ["Soulsby no. 46(1)"],
"uniformtitle": ["Systema naturae"],
"title": ["Caroli Linnæi ... Systema naturæ\nin quo naturæ regna tria, secundum classes, ordines, genera, species, systematice proponuntur."],
"opac": ["002178079"],
"digitalcopyurl": ["http://books.google.co.uk/books?vid=BL:A0019621817", "http://books.google.co.uk/books?vid=BL:A0019621817", "", ""],
"name": ["View digital version at BL", "View digital version at BL", "View digital version at NHM-LONDON", "View digital version at UUL"]},
</code>```

I would like the "digitalcopyurl" to look more like:

```<code>"digitalcopyurl": ["http://books.google.co.uk/books?vid=BL:A0019621817, http://books.google.co.uk/books?vid=BL:A0019621817"],
</code>```

(And I would like to use the same solution to do the same to the "name" field.)

Thanks for your help!

Edit: The example output is NOT using the ".join"--it's without.

答:
Write

```<code>'digitalcopyurl': ", ".join(response.css('div#digitalLinks li a').xpath('@href').extract())
</code>```

OR

```<code>'digitalcopyurl': ", ".join(a.strip() for a in response.css('div#digitalLinks li a').xpath('@href').extract())
</code>```

Both will do the same thing

Title: Combine string Scrapy python

Body:
I have a question about how to combine a set of values when using scrapy so that my json output is cleaner.  Here is what I have:

import scrapy
from scrapy.contrib.loader import ItemLoader
from scrapy.contrib.loader.processor import TakeFirst, MapCompose, Join

class LLPubs (scrapy.Spider):
    name = "linlinks"
    start_urls = [
        'http://www.linnaeuslink.org/records/record/1',
        'http://www.linnaeuslink.org/records/record/2',
        'http://www.linnaeuslink.org/records/record/2a',
        'http://www.linnaeuslink.org/records/record/10',
]

    def parse(self, response):
        for item in response.css('div.item'):
            yield {
                'text': item.css('div.field.soulsbyNo .value span::text').extract(),
                'uniformtitle': item.css('div.field.uniformTitle .value span::text').extract(),
                'title': item.css('div.field.title .value span::text').extract(),
                'opac': item.css('div.field.localControlNo .value span::text').extract(),
                'digitalcopyurl': .join(response.css('div#digitalLinks li a').xpath('@href').extract()),
                'name': response.css('div#digitalLinks li a span::text').extract(),
                }

The "digitalcopyurl" is where I am having the problem.  I guess I can't use "join" in this way but I'm not sure what to modify.  Here's an example of what the JSON looks like now:

{"text": ["Soulsby no. 46(1)"],
"uniformtitle": ["Systema naturae"],
"title": ["Caroli Linnæi ... Systema naturæ\nin quo naturæ regna tria, secundum classes, ordines, genera, species, systematice proponuntur."],
"opac": ["002178079"],
"digitalcopyurl": ["http://books.google.co.uk/books?vid=BL:A0019621817", "http://books.google.co.uk/books?vid=BL:A0019621817", "", ""],
"name": ["View digital version at BL", "View digital version at BL", "View digital version at NHM-LONDON", "View digital version at UUL"]},

I would like the "digitalcopyurl" to look more like:

"digitalcopyurl": ["http://books.google.co.uk/books?vid=BL:A0019621817, http://books.google.co.uk/books?vid=BL:A0019621817"],

(And I would like to use the same solution to do the same to the "name" field.)

Thanks for your help!

Edit: The example output is NOT using the ".join"--it's without.

Body:
Write

'digitalcopyurl': ", ".join(response.css('div#digitalLinks li a').xpath('@href').extract())

OR

'digitalcopyurl': ", ".join(a.strip() for a in response.css('div#digitalLinks li a').xpath('@href').extract())

Both will do the same thing


问:
Add new objects after using "new"
after I call new, how can I add more objects to the pointer? (I need it for a class)
this is what I mean:

```<code>int *a;
a = new int;
a = new int;
</code>```

Thank you very much!

答:
If you need a contiguous buffer use vector.

```<code>std::vector<int> buf;
buf.push_back( 1 );
buf.push_back( 2 );
buf.push_back( 3 );

int * intbuf = &buf[0];
</code>```

Beware this pointer could be invalidated if you add more items to your vector. You can prevent this if you want by doing this first:

```<code>buf.reserve( 65536 );
</code>```

or some other number. You can still add more than 65536 items to the vector but it is guaranteed that as long as the size is less than this, &buf[0] will not change.

Given that you are not doing any of this though, you are trying to implement vector, one way to do this is not to use new at all but to use malloc to allocate the memory, thus:

```<code>char * buf = static_cast<char *>( malloc( BUF_SIZE ) );
</code>```

Now you can create objects in here with placement new

```<code>int * intbuf = new( buf + sizeof(int) * N ) int( i );
</code>```

When you need more space you can "realloc" your pointer. Be certain to realloc to a temporary one first to check it succeeds.

```<code>bufNew = static_cast< char * >( realloc( buf, newBufSize ) );
if( bufNew )
     buf = bufNew;
</code>```

This works here because int is POD type. If the type is not POD it is not safe to realloc and simply move objects by memory, you need to move them as objects, using operator= on each one.

Now you know a bit about this, but for practical purposes you probably want to use vector.

ContentLicense: CC BY-SA 2.5

Title: Add new objects after using "new"

Body:
after I call new, how can I add more objects to the pointer? (I need it for a class)
this is what I mean:

int *a;
a = new int;
a = new int;

Thank you very much!

Body:
If you need a contiguous buffer use vector.

std::vector<int> buf;
buf.push_back( 1 );
buf.push_back( 2 );
buf.push_back( 3 );

int * intbuf = &buf[0];

Beware this pointer could be invalidated if you add more items to your vector. You can prevent this if you want by doing this first:

buf.reserve( 65536 );

or some other number. You can still add more than 65536 items to the vector but it is guaranteed that as long as the size is less than this, &buf[0] will not change.

Given that you are not doing any of this though, you are trying to implement vector, one way to do this is not to use new at all but to use malloc to allocate the memory, thus:

char * buf = static_cast<char *>( malloc( BUF_SIZE ) );

Now you can create objects in here with placement new

int * intbuf = new( buf + sizeof(int) * N ) int( i );

When you need more space you can "realloc" your pointer. Be certain to realloc to a temporary one first to check it succeeds.

bufNew = static_cast< char * >( realloc( buf, newBufSize ) );
if( bufNew )
     buf = bufNew;

This works here because int is POD type. If the type is not POD it is not safe to realloc and simply move objects by memory, you need to move them as objects, using operator= on each one.

Now you know a bit about this, but for practical purposes you probably want to use vector.


问:
Using the Ninja build system, can I clean intermediate build products?
When I generate an out of tree Ninja build using CMake, it would be useful to be able to remove the intermediate build products (i.e. object files and static libraries), in order to save disk space on our CI server. Is there a way to do this?</p>

答:
It is possible to clean by rule with Ninja, but knowing which rules generate intermediates is not possible with Ninja alone; instead we must resort to shell scripts:

```<code>grep "^rule.*\(_COMPILER_\|_STATIC_LIBRARY_\)" rules.ninja | \
    cut -d' ' -f2 | xargs -n1 ninja -t clean -r
</code>```

This greps the rules.ninja file for those rules that generate object files and static libraries, then invokes ninja -t clean -r <rule> on each in order to do the actual cleaning. The equivalent functionality on Windows is achieved with:

```<code>FOR /f "tokens=2" %%R IN ('findstr "_COMPILER_ _STATIC_LIBRARY_" rules.ninja') DO (
    ninja -t clean -r %%~R
)
</code>```

It's a hack for sure, but it saves us a substantial amount of disk space, so worth documenting, I thought.

Body:
It is possible to clean by rule with Ninja, but knowing which rules generate intermediates is not possible with Ninja alone; instead we must resort to shell scripts:

grep "^rule.*\(_COMPILER_\|_STATIC_LIBRARY_\)" rules.ninja | \
    cut -d' ' -f2 | xargs -n1 ninja -t clean -r

This greps the rules.ninja file for those rules that generate object files and static libraries, then invokes ninja -t clean -r <rule> on each in order to do the actual cleaning. The equivalent functionality on Windows is achieved with:

FOR /f "tokens=2" %%R IN ('findstr "_COMPILER_ _STATIC_LIBRARY_" rules.ninja') DO (
    ninja -t clean -r %%~R
)

It's a hack for sure, but it saves us a substantial amount of disk space, so worth documenting, I thought.


问:
how to send \n neutral character in strophe.js
To implement keep alive feature for Ejabberd it recommends to send a \n character to server.

I'm using strophe.js as the client library. How do I send neutral character from strophe?

Body: You can try to encode the carriage return (CR) character. That is, you can use its character entity:  &#13;


问:
Using car:::linearHypothesis() with lme4 models
I want to test whether a coefficient (not the intercept) from a mixed effects model fit using lme4:::lmer() is different from a value other than zero.  car:::linearHypothesis() should be able to do this, with p-values and error degrees of freedom calculated using a Kenward-Rogers approximation, as implemented in pbkrtest (car documentation; pbkrtest documentation).

However, I've run into what I think is a bug. I only seem to be able to obtain tests of the coefficient of interest against 0.  Here's a reproducible example:

```<code>library(car)
library(lme4)
library(pbkrtest)

set.seed(32432)

d <- data.frame(id=rep(1:100, 4), x=rnorm(400), y=rnorm(400))
m <- lmer(y ~ x + (1|id), data=d)

linearHypothesis(m, "x=4", test="F")
# F=.1256, p=.7232
linearHypothesis(m, "x=0", test="F")
# F=.1256, p=.7232
</code>```

Clearly these F and p-values should not be the same!

For reference, I don't get the same bug if I use $\Chi^2$ tests, which suggests to me that the bug is pbkrtest:

```<code>linearHypothesis(m, "x=4")
# X2=5614.1, p=2.2e-16
linearHypothesis(m, "x=0")
# X2=.1268, p=.7218
</code>```

Anyone have a workaround?

答: I contacted John Fox, the author of the car package. He confirmed that there is indeed a bug in how car:::linearHypothesis() treats models fit with lme4:::lmer(). This should be fixed in the next version of car.

Body:
I want to test whether a coefficient (not the intercept) from a mixed effects model fit using lme4:::lmer() is different from a value other than zero.  car:::linearHypothesis() should be able to do this, with p-values and error degrees of freedom calculated using a Kenward-Rogers approximation, as implemented in pbkrtest (car documentation; pbkrtest documentation).

However, I've run into what I think is a bug. I only seem to be able to obtain tests of the coefficient of interest against 0.  Here's a reproducible example:

library(car)
library(lme4)
library(pbkrtest)

set.seed(32432)

d <- data.frame(id=rep(1:100, 4), x=rnorm(400), y=rnorm(400))
m <- lmer(y ~ x + (1|id), data=d)

linearHypothesis(m, "x=4", test="F")
# F=.1256, p=.7232
linearHypothesis(m, "x=0", test="F")
# F=.1256, p=.7232

Clearly these F and p-values should not be the same!

For reference, I don't get the same bug if I use $\Chi^2$ tests, which suggests to me that the bug is pbkrtest:

linearHypothesis(m, "x=4")
# X2=5614.1, p=2.2e-16
linearHypothesis(m, "x=0")
# X2=.1268, p=.7218

Anyone have a workaround?


问:
Manual Focus by using steps with Sony JSON Camera API
I have question regarding manual focus with SONY Camera JSON API.

For the automation of the FocusStack feature (combining more images with different focus values into the resulting one, to achieve the best possible sharpness of the image).

I need a manual control of the focus by using “steps” = absolute value.
How we can achieve this with Sony JSON API? We did’t find anything related to this in the SONY Camera API documentation. Thank you!

答:
Unfortunately you won't be able to control the camera focus in such a manual way. When it comes to focus control here is what you can do:

Change the focus mode (Single AF/Continuous AF/Direct Manual Focus/Manual Focus)

Set the focus coordinate

Set Tracking focus on/off


问:
Python : how to count amount of letters of alphabet in string in parts
How to count the amount of letters in this string between the different parts?
And the other way around: how to get the alphabetical string representation when the numbers are given?

Input: 'A-G H-O P Q-Z'

Output: (7, 8, 1, 10)

```<code>  q = list()

    for i in seq:
        if i is char:
            n = ord(i+1) - ord(i)
            q.append(n)
</code>```

答:
You can do this:

```<code>input_string = 'A-G H-O P Q-Z'
input_string = input_string.split()

q = []
for dletter in input_string:
    if '-' in dletter:
        q.append(1 + ord(dletter[2]) - ord(dletter[0]))
    else:
        q.append(1)
</code>```

Alternatively without the if statement:

```<code>input_string = 'A-G H-O P Q-Z'
input_string = input_string.split()

q = []
for dletter in input_string:
    q.append(1 + ord(dletter[-1]) - ord(dletter[0]))
</code>```

But this is a very good answer

Body:
How to count the amount of letters in this string between the different parts?
And the other way around: how to get the alphabetical string representation when the numbers are given?

Input: 'A-G H-O P Q-Z'

Output: (7, 8, 1, 10)

  q = list()

    for i in seq:
        if i is char:
            n = ord(i+1) - ord(i)
            q.append(n)

Body:
You can do this:

input_string = 'A-G H-O P Q-Z'
input_string = input_string.split()

q = []
for dletter in input_string:
    if '-' in dletter:
        q.append(1 + ord(dletter[2]) - ord(dletter[0]))
    else:
        q.append(1)

Alternatively without the if statement:

input_string = 'A-G H-O P Q-Z'
input_string = input_string.split()

q = []
for dletter in input_string:
    q.append(1 + ord(dletter[-1]) - ord(dletter[0]))

But this is a very good answer


问:
Delete rows older than 14 days in MySQL

Summary

I need to purge the history of a table from rows that are older than 14 days.

Being no MySQL Expert, my searches lead me to this:

```<code>delete
    from SYS_VERROUS_POLICE
    where idModificationPolice not in (
                select distinct idModificationPolice
                    from SYS_VERROUS_POLICE
                    where date(dateHeureModification)
                            between curdate() and curdate() - interval 14 day
            );
</code>```

Thrown Exception

But then I'm stuck with this error message:

Error Code: 1093. You can't specify target table 'SYS_VERROUS_POLICE' for update in FROM clause.

What the...

Context

MySQL seems to be operating in safe mode, so I just won't be able to perform a DELETE where matching dates.

In safe-mode, if I try to delete using only the date field, it doesn't comply.

```<code>delete
  from SYS_VERROUS_POLICE
 where date(dateHeureModification) < curdate() - interval 14 day

Error Code: 1175. You are using safe update mode and you tried to update a table without a
WHERE that uses a KEY column
To disable safe mode, toggle the option in Preferences -> SQL Editor and reconnect.
0,00071 sec
</code>```

Am I missing something?

答:
@Jean Dous is the correct answer. But just to explain what is the problem in your query. You try to check a condition for the same table you are updating and is like creating a circular reference.

Instead you materialize the table as a subquery so you can use it.

```<code>delete
from SYS_VERROUS_POLICE
where idModificationPolice not in (
              select distinct T.idModificationPolice
              from (SELECT *
                    FROM SYS_VERROUS_POLICE) as T
              where date(T.dateHeureModification)
                    between curdate() and curdate() - interval 14 day
         );
</code>```

Title: Delete rows older than 14 days in MySQL

Body:
Summary

I need to purge the history of a table from rows that are older than 14 days.

Being no MySQL Expert, my searches lead me to this:

delete
    from SYS_VERROUS_POLICE
    where idModificationPolice not in (
                select distinct idModificationPolice
                    from SYS_VERROUS_POLICE
                    where date(dateHeureModification)
                            between curdate() and curdate() - interval 14 day
            );

Thrown Exception

But then I'm stuck with this error message:

Error Code: 1093. You can't specify target table 'SYS_VERROUS_POLICE' for update in FROM clause.

What the...

Context

MySQL seems to be operating in safe mode, so I just won't be able to perform a DELETE where matching dates.

In safe-mode, if I try to delete using only the date field, it doesn't comply.

delete
  from SYS_VERROUS_POLICE
 where date(dateHeureModification) < curdate() - interval 14 day

Error Code: 1175. You are using safe update mode and you tried to update a table without a
WHERE that uses a KEY column
To disable safe mode, toggle the option in Preferences -> SQL Editor and reconnect.
0,00071 sec

Am I missing something?

Body:
@Jean Dous is the correct answer. But just to explain what is the problem in your query. You try to check a condition for the same table you are updating and is like creating a circular reference.

Instead you materialize the table as a subquery so you can use it.

delete
from SYS_VERROUS_POLICE
where idModificationPolice not in (
              select distinct T.idModificationPolice
              from (SELECT *
                    FROM SYS_VERROUS_POLICE) as T
              where date(T.dateHeureModification)
                    between curdate() and curdate() - interval 14 day
         );


问:
Google Maps iOS rendering empty tiles white instead of clear
I'm making an app that uses Tile Layers in Google Maps to provide custom indoor maps for buildings of interest. I've got the tile layer sending tiles at the appropriate coordinates, but any time one of the tiles is empty, Google Maps is rendering it as white, not transparent. You can see this in the attached screenshot.

What is going on here and how can I get it to render those tiles as transparent? Note, the tiles exhibit no unusual characteristics when viewed in Photoshop or Preview.

答:
I finally figured out what the problem was: ImageMagick was saving the fully-transparent tiles in a 16-bit format (8 gray / 8 alpha) that Google Maps didn't understand. Tiles with content were being saved as the usual 32-bit RGBA format. I added the following option to my tile generating script to fix it:</p>

```<code>-define png:color-type=6
</code>```

Body:
I finally figured out what the problem was: ImageMagick was saving the fully-transparent tiles in a 16-bit format (8 gray / 8 alpha) that Google Maps didn't understand. Tiles with content were being saved as the usual 32-bit RGBA format. I added the following option to my tile generating script to fix it:

-define png:color-type=6


问:
How to load images in html whose src contain {{}} through webpack 2?
I use html-loader to load img in html, and it works well when img's src is invariable.as. BUT my when my write like this:, it will be error:Can't resolve '../../../assets/images/device_{{key.deviceName}}.png' in '/Users/zhangxu/Desktop/LicenseServer/angular/src/app/components/home'.
this is my webpack.config.js:

module: {
        rules: [
            {
                test: /\.ts$/,
                loaders:['awesome-typescript-loader', 'angular2-template-loader']
            },
            {
                test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
                loader: 'file-loader?name=assets/[name].[hash].[ext]',
            },

            {
                test:/\.html$/,
                loader: 'html-loader',
                exclude: helper.root('src','index.html')

            },

            {
                test: /\.css$/,
                exclude: helper.root('src', 'app'),
                loader: ExtractTextPlugin.extract({ fallbackLoader: 'style-loader', loader: 'css-loader?sourceMap' })
            },
            {
                test:/\.css$/,
                include: helper.root('src', 'app'),
                loader:'raw-loader'

            },
            {
                test: /\.scss$/,
                loaders: ['style', 'css', 'postcss', 'sass']
            }
        ],

    },```
</div>
</div>

this is my HTML:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div *ngFor="let key of devices;let i = index;">
       <div class="device" *ngIf="key.selected && !key.out_select" (click)="cancelSelectDevice(i)">
         <img src="../../../assets/images/device_{{key.deviceName}}.png" width="75">

        </div>

</div></code>```

How can I solve this error? Thanks

答:
Maybe you can use the [src] property and concatenate strings and variables'. </p>

```<code><img [src]="'../../../assets/images/device' + key.deviceName + '.png'" />
</code>```

Body:
I use html-loader to load img in html, and it works well when img's src is invariable.as. BUT my when my write like this:, it will be error:Can't resolve '../../../assets/images/device_{{key.deviceName}}.png' in '/Users/zhangxu/Desktop/LicenseServer/angular/src/app/components/home'.
this is my webpack.config.js:

module: {
        rules: [
            {
                test: /\.ts$/,
                loaders:['awesome-typescript-loader', 'angular2-template-loader']
            },
            {
                test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
                loader: 'file-loader?name=assets/[name].[hash].[ext]',
            },

            {
                test:/\.html$/,
                loader: 'html-loader',
                exclude: helper.root('src','index.html')

            },

            {
                test: /\.css$/,
                exclude: helper.root('src', 'app'),
                loader: ExtractTextPlugin.extract({ fallbackLoader: 'style-loader', loader: 'css-loader?sourceMap' })
            },
            {
                test:/\.css$/,
                include: helper.root('src', 'app'),
                loader:'raw-loader'

            },
            {
                test: /\.scss$/,
                loaders: ['style', 'css', 'postcss', 'sass']
            }
        ],

    },

this is my HTML:

How can I solve this error? Thanks

Body:
Maybe you can use the [src] property and concatenate strings and variables'.

<img [src]="'../../../assets/images/device' + key.deviceName + '.png'" />


问:
Generate missing data from existing data
I have hourly level data of a unit, with its status and its value. The status and value of the unit changes after certain intervals (not necessarily at every hour). I want to generate hourly level data from existing data. Say for example: I have input such as:

and output required is:

Please find below scripts for required input and output:

Input

```<code>SELECT '3' as ID,'CName1' AS Name,'0' AS Status,'2017-10-25' AS CDate,'22' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'2' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'0' AS Status,'2017-10-26' AS CDate,'5' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'8' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'0' AS Status,'2017-10-26' AS CDate,'11' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'13' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'16' AS CHour,1.0 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'2' AS Status,'2017-10-26' AS CDate,'20' AS CHour,1.0 AS Value
</code>```

Output:

```<code>SELECT '3' as ID,'CName1' AS Name,'0' AS Status,'2017-10-25' AS CDate,'22' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'0' AS Status,'2017-10-25' AS CDate,'23' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'0' AS Status,'2017-10-26' AS CDate,'0' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'0' AS Status,'2017-10-26' AS CDate,'1' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'2' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'3' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'4' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'0' AS Status,'2017-10-26' AS CDate,'5' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'0' AS Status,'2017-10-26' AS CDate,'6' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'0' AS Status,'2017-10-26' AS CDate,'7' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'8' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'9' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'10' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'0' AS Status,'2017-10-26' AS CDate,'11' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'0' AS Status,'2017-10-26' AS CDate,'12' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'13' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'14' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'15' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'16' AS CHour,1.0 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'17' AS CHour,1.0 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'18' AS CHour,1.0 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'19' AS CHour,1.0 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'2' AS Status,'2017-10-26' AS CDate,'20' AS CHour,1.0 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'2' AS Status,'2017-10-26' AS CDate,'21' AS CHour,1.0 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'2' AS Status,'2017-10-26' AS CDate,'22' AS CHour,1.0 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'2' AS Status,'2017-10-26' AS CDate,'23' AS CHour,1.0 AS Value
</code>```

答:
This is for SQL Server.

Here, I use a CTE that supplies a rownumber to distinguish previous date and time.
The CTE selects distinct Dates cross joined to your hours format: 0 to 23.

In the select statement is the algorithm to identify previous row. I inner join the CTE to itself using this previous rownumber. By inner join this removes earlier dates prior to the first data entry.

This is subqueried. If the row was missing data, then by LEFT JOIN in the cte fields like ID, Name, and Status are NULL.  The Coalesce selects the original (non-null) data, else the most recent data by rownumber.

```<code>DECLARE @temp TABLE (ID tinyint, Name varchar(100), Status tinyint, CDate date, CHour tinyint, Value decimal(12,1))
INSERT INTO @temp(ID, Name, Status, CDate, CHour, Value)
VALUES (3, 'CName1', 0, '2017-10-25', 22, 0.5)
      ,(3, 'CName1', 1, '2017-10-26',  2, 0.5)
      ,(3, 'CName1', 0, '2017-10-26',  5, 0.5)
      ,(3, 'CName1', 1, '2017-10-26',  8, 0.5)
      ,(3, 'CName1', 0, '2017-10-26', 11 ,0.5)
      ,(3, 'CName1', 1, '2017-10-26', 13 ,0.5)
      ,(3, 'CName1', 1, '2017-10-26', 16 ,1.0)
      ,(3, 'CName1', 2, '2017-10-26', 20 ,1.0)
;
WITH cte AS
(
SELECT ROW_NUMBER() OVER(ORDER BY dT.CDate2, dT.CHour2) [theOrder]
      ,*
  FROM (
        SELECT DISTINCT T.CDate [Cdate2], dT.CHour2
          FROM @temp T
               CROSS JOIN (SELECT 0 [CHour2] UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4
                           UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9
                           UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL SELECT 12 UNION ALL SELECT 13 UNION ALL SELECT 14
                           UNION ALL SELECT 15 UNION ALL SELECT 16 UNION ALL SELECT 17 UNION ALL SELECT 18 UNION ALL SELECT 19
                           UNION ALL SELECT 20 UNION ALL SELECT 21 UNION ALL SELECT 22 UNION ALL SELECT 23
                          ) AS dT --joins for any missing hours
       ) AS dT LEFT JOIN @temp T ON dT.Cdate2 = T.CDate AND T.CHour = dT.CHour2
)

SELECT COALESCE(dT.ID, cte2.ID) [ID]
      ,COALESCE(dT.[Name], cte2.[Name]) [Name]
      ,COALESCE(dT.[Status], cte2.[Status]) [Status]
      ,dT.Cdate2 [Cdate]
      ,dT.CHour2 [CHour]
      ,COALESCE(dT.[Value], cte2.[Value]) [Value]

  FROM (
        SELECT C1.*
              ,(SELECT MAX(theOrder)
                  FROM cte C2
                 WHERE C2.theOrder <= C1.theOrder AND C2.ID IS NOT NULL
               ) [maxorder]
          FROM cte C1
       ) AS dT INNER JOIN cte cte2 ON dT.maxorder = cte2.theOrder
</code>```

This output matches your requested output.

Body:
I have hourly level data of a unit, with its status and its value. The status and value of the unit changes after certain intervals (not necessarily at every hour). I want to generate hourly level data from existing data. Say for example: I have input such as:

and output required is:

Please find below scripts for required input and output:

Input

SELECT '3' as ID,'CName1' AS Name,'0' AS Status,'2017-10-25' AS CDate,'22' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'2' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'0' AS Status,'2017-10-26' AS CDate,'5' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'8' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'0' AS Status,'2017-10-26' AS CDate,'11' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'13' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'16' AS CHour,1.0 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'2' AS Status,'2017-10-26' AS CDate,'20' AS CHour,1.0 AS Value

Output:

SELECT '3' as ID,'CName1' AS Name,'0' AS Status,'2017-10-25' AS CDate,'22' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'0' AS Status,'2017-10-25' AS CDate,'23' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'0' AS Status,'2017-10-26' AS CDate,'0' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'0' AS Status,'2017-10-26' AS CDate,'1' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'2' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'3' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'4' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'0' AS Status,'2017-10-26' AS CDate,'5' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'0' AS Status,'2017-10-26' AS CDate,'6' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'0' AS Status,'2017-10-26' AS CDate,'7' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'8' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'9' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'10' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'0' AS Status,'2017-10-26' AS CDate,'11' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'0' AS Status,'2017-10-26' AS CDate,'12' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'13' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'14' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'15' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'16' AS CHour,1.0 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'17' AS CHour,1.0 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'18' AS CHour,1.0 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'19' AS CHour,1.0 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'2' AS Status,'2017-10-26' AS CDate,'20' AS CHour,1.0 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'2' AS Status,'2017-10-26' AS CDate,'21' AS CHour,1.0 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'2' AS Status,'2017-10-26' AS CDate,'22' AS CHour,1.0 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'2' AS Status,'2017-10-26' AS CDate,'23' AS CHour,1.0 AS Value

Body:
This is for SQL Server.

Here, I use a CTE that supplies a rownumber to distinguish previous date and time.
The CTE selects distinct Dates cross joined to your hours format: 0 to 23.

In the select statement is the algorithm to identify previous row. I inner join the CTE to itself using this previous rownumber. By inner join this removes earlier dates prior to the first data entry.

This is subqueried. If the row was missing data, then by LEFT JOIN in the cte fields like ID, Name, and Status are NULL.  The Coalesce selects the original (non-null) data, else the most recent data by rownumber.

DECLARE @temp TABLE (ID tinyint, Name varchar(100), Status tinyint, CDate date, CHour tinyint, Value decimal(12,1))
INSERT INTO @temp(ID, Name, Status, CDate, CHour, Value)
VALUES (3, 'CName1', 0, '2017-10-25', 22, 0.5)
      ,(3, 'CName1', 1, '2017-10-26',  2, 0.5)
      ,(3, 'CName1', 0, '2017-10-26',  5, 0.5)
      ,(3, 'CName1', 1, '2017-10-26',  8, 0.5)
      ,(3, 'CName1', 0, '2017-10-26', 11 ,0.5)
      ,(3, 'CName1', 1, '2017-10-26', 13 ,0.5)
      ,(3, 'CName1', 1, '2017-10-26', 16 ,1.0)
      ,(3, 'CName1', 2, '2017-10-26', 20 ,1.0)
;
WITH cte AS
(
SELECT ROW_NUMBER() OVER(ORDER BY dT.CDate2, dT.CHour2) [theOrder]
      ,*
  FROM (
        SELECT DISTINCT T.CDate [Cdate2], dT.CHour2
          FROM @temp T
               CROSS JOIN (SELECT 0 [CHour2] UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4
                           UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9
                           UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL SELECT 12 UNION ALL SELECT 13 UNION ALL SELECT 14
                           UNION ALL SELECT 15 UNION ALL SELECT 16 UNION ALL SELECT 17 UNION ALL SELECT 18 UNION ALL SELECT 19
                           UNION ALL SELECT 20 UNION ALL SELECT 21 UNION ALL SELECT 22 UNION ALL SELECT 23
                          ) AS dT --joins for any missing hours
       ) AS dT LEFT JOIN @temp T ON dT.Cdate2 = T.CDate AND T.CHour = dT.CHour2
)

SELECT COALESCE(dT.ID, cte2.ID) [ID]
      ,COALESCE(dT.[Name], cte2.[Name]) [Name]
      ,COALESCE(dT.[Status], cte2.[Status]) [Status]
      ,dT.Cdate2 [Cdate]
      ,dT.CHour2 [CHour]
      ,COALESCE(dT.[Value], cte2.[Value]) [Value]

  FROM (
        SELECT C1.*
              ,(SELECT MAX(theOrder)
                  FROM cte C2
                 WHERE C2.theOrder <= C1.theOrder AND C2.ID IS NOT NULL
               ) [maxorder]
          FROM cte C1
       ) AS dT INNER JOIN cte cte2 ON dT.maxorder = cte2.theOrder

This output matches your requested output.


问:
Python elegant assignment based on True/False values
I have a variable I want to set depending on the values in three booleans. The most straight-forward way is an if statement followed by a series of elifs:

```<code>if a and b and c:
    name = 'first'
elif a and b and not c:
    name = 'second'
elif a and not b and c:
    name = 'third'
elif a and not b and not c:
    name = 'fourth'
elif not a and b and c:
    name = 'fifth'
elif not a and b and not c:
    name = 'sixth'
elif not a and not b and c:
    name = 'seventh'
elif not a and not b and not c:
    name = 'eighth'
</code>```

This is a bit awkward, and I'm wondering if there's a more Pythonic way to handle this problem. A couple of ideas come to mind.

Dictionary hack:

```<code>name = {a and b and c: 'first',
        a and b and not c: 'second',
        a and not b and c: 'third',
        a and not b and not c: 'fourth',
        not a and b and c: 'fifth',
        not a and b and not c: 'sixth',
        not a and not b and c: 'seventh',
        not a and not b and not c: 'eighth'}[True]
</code>```

I call it a hack because I'm not too wild about seven of the keys being False and overriding each other.

And/or magic

```<code>name = (a and b and c and 'first' or
        a and b and not c and 'second' or
        a and not b and c and 'third' or
        a and not b and not c and 'fourth' or
        not a and b and c and 'fifth' or
        not a and b and not c and 'sixth' or
        not a and not b and c and 'seventh' or
        not a and not b and not c and 'eighth')
</code>```

This works because Python ands and ors return the last value to be evaluated, but you have to know that in order to understand this otherwise bizarre code.

None of these three options is very satisfying. What do you recommend?

答:
How about using a dict?</p>

```<code>name = {(True, True, True): "first", (True, True, False): "second",
        (True, False, True): "third", (True, False, False): "fourth",
        (False, True, True): "fifth", (False, True, False): "sixth",
        (False, False, True): "seventh", (False, False, False): "eighth"}

print name[a,b,c] # prints "fifth" if a==False, b==True, c==True etc.
</code>```

Body:
I have a variable I want to set depending on the values in three booleans. The most straight-forward way is an if statement followed by a series of elifs:

if a and b and c:
    name = 'first'
elif a and b and not c:
    name = 'second'
elif a and not b and c:
    name = 'third'
elif a and not b and not c:
    name = 'fourth'
elif not a and b and c:
    name = 'fifth'
elif not a and b and not c:
    name = 'sixth'
elif not a and not b and c:
    name = 'seventh'
elif not a and not b and not c:
    name = 'eighth'

This is a bit awkward, and I'm wondering if there's a more Pythonic way to handle this problem. A couple of ideas come to mind.

Dictionary hack:

name = {a and b and c: 'first',
        a and b and not c: 'second',
        a and not b and c: 'third',
        a and not b and not c: 'fourth',
        not a and b and c: 'fifth',
        not a and b and not c: 'sixth',
        not a and not b and c: 'seventh',
        not a and not b and not c: 'eighth'}[True]

I call it a hack because I'm not too wild about seven of the keys being False and overriding each other.

And/or magic

name = (a and b and c and 'first' or
        a and b and not c and 'second' or
        a and not b and c and 'third' or
        a and not b and not c and 'fourth' or
        not a and b and c and 'fifth' or
        not a and b and not c and 'sixth' or
        not a and not b and c and 'seventh' or
        not a and not b and not c and 'eighth')

This works because Python ands and ors return the last value to be evaluated, but you have to know that in order to understand this otherwise bizarre code.

None of these three options is very satisfying. What do you recommend?

Body:
How about using a dict?

name = {(True, True, True): "first", (True, True, False): "second",
        (True, False, True): "third", (True, False, False): "fourth",
        (False, True, True): "fifth", (False, True, False): "sixth",
        (False, False, True): "seventh", (False, False, False): "eighth"}

print name[a,b,c] # prints "fifth" if a==False, b==True, c==True etc.


问:
Cannot login in flask - always asking username&password
I watched a tutorial (https://www.youtube.com/watch?v=VW8qJxy4XcQ) and I saw how easy to login to a webpage in flask. I tried it several times, but when I enter the correct username and password (the saving box comes up for a moment to remember my datas) the little box with the edit texts disappears and it asks them again. What am I doing wrong?

Thanks

```<code>from flask import Flask, render_template, request, make_response
import os
app = Flask(__name__)

@app.route('/pass')
def index():
    if request.authorization and request.authorization.username == 'a' and request.authorization.password == 'a':
        return 'logged in'
        #return render_template("index2.html")
    else:
        return make_response('Could not verify!', 401, {'WWW-Authenticate' : 'Basic realm=Login required'})

if __name__ == "__main__":
    app.run(debug=True)
</code>```

virtualhost:

```<code><VirtualHost *:80>
                ServerName 39.234.23.12
                ServerAdmin youemail@email.com
                WSGIScriptAlias / /var/www/FlaskApp/flaskapp.wsgi
                <Directory /var/www/FlaskApp/FlaskApp/>
                        Order allow,deny
                        Allow from all
                </Directory>
                Alias /static /var/www/FlaskApp/FlaskApp/static
                <Directory /var/www/FlaskApp/FlaskApp/static/>
                        Order allow,deny
                        Allow from all
                </Directory>
                ErrorLog ${APACHE_LOG_DIR}/error.log
                LogLevel warn
                CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
</code>```

That didn't work, either despite of doing it locally, not on the google cloud virtual instance:

```<code>import os
from flask import Flask, render_template, request

app = Flask(__name__)

APP_ROOT = os.path.dirname(os.path.abspath(__file__))

@app.route("/")
def index():
    if request.authorization and request.authorization.username == 'a' and request.authorization.password == 'a':
        return "success"
    return "nope"
</code>```

答:
Aside of using authorization you may consider form input. Here is a simple example of creating a simple login system.

app.py:

```<code>from flask import Flask, request, render_template, flash

app = Flask(__name__)
app.secret_key = 'TOO_SECRET_TO_REVEAL'

@app.route('/',methods = ["GET", "POST"])
def index():
    if request.method == "POST":
        username = request.form.get("username", None)
        password = request.form.get("password", None)
        if username == "shovon" and password=="password":
            flash("Login successful")
        else:
            flash("Wrong username or password")
    return render_template("simple_login.html")

if __name__ == '__main__':
    app.run(debug = True)
</code>```

Then in templates folder the simple_login.html contains:

```<code><!DOCTYPE html>
<html>
<head>
    <title>Simple Login</title>
</head>
<body>
    {% with flash_messages = get_flashed_messages() %}
        {% if flash_messages %}
            <ul>
                {% for message in flash_messages %}
                    <li>
                        {{ message }}
                    </li>
                {% endfor %}
            </ul>
        {% endif %}
    {% endwith %}
    <form action="/" method="post">
        Username: <input type="text" name="username" /> <br>
        Password: <input type="password" name="password" /> <br>
        <input type="submit" name="login" value="Login" />
    </form>
</body>
</html>
</code>```

Output:

To learn more about flash view examples in message flashing

Body:
I watched a tutorial (https://www.youtube.com/watch?v=VW8qJxy4XcQ) and I saw how easy to login to a webpage in flask. I tried it several times, but when I enter the correct username and password (the saving box comes up for a moment to remember my datas) the little box with the edit texts disappears and it asks them again. What am I doing wrong?

Thanks

from flask import Flask, render_template, request, make_response
import os
app = Flask(__name__)

@app.route('/pass')
def index():
    if request.authorization and request.authorization.username == 'a' and request.authorization.password == 'a':
        return 'logged in'
        #return render_template("index2.html")
    else:
        return make_response('Could not verify!', 401, {'WWW-Authenticate' : 'Basic realm=Login required'})

if __name__ == "__main__":
    app.run(debug=True)

virtualhost:

<VirtualHost *:80>
                ServerName 39.234.23.12
                ServerAdmin youemail@email.com
                WSGIScriptAlias / /var/www/FlaskApp/flaskapp.wsgi
                <Directory /var/www/FlaskApp/FlaskApp/>
                        Order allow,deny
                        Allow from all
                </Directory>
                Alias /static /var/www/FlaskApp/FlaskApp/static
                <Directory /var/www/FlaskApp/FlaskApp/static/>
                        Order allow,deny
                        Allow from all
                </Directory>
                ErrorLog ${APACHE_LOG_DIR}/error.log
                LogLevel warn
                CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

That didn't work, either despite of doing it locally, not on the google cloud virtual instance:

import os
from flask import Flask, render_template, request

app = Flask(__name__)

APP_ROOT = os.path.dirname(os.path.abspath(__file__))

@app.route("/")
def index():
    if request.authorization and request.authorization.username == 'a' and request.authorization.password == 'a':
        return "success"
    return "nope"

Body:
Aside of using authorization you may consider form input. Here is a simple example of creating a simple login system.

app.py:

from flask import Flask, request, render_template, flash

app = Flask(__name__)
app.secret_key = 'TOO_SECRET_TO_REVEAL'

@app.route('/',methods = ["GET", "POST"])
def index():
    if request.method == "POST":
        username = request.form.get("username", None)
        password = request.form.get("password", None)
        if username == "shovon" and password=="password":
            flash("Login successful")
        else:
            flash("Wrong username or password")
    return render_template("simple_login.html")

if __name__ == '__main__':
    app.run(debug = True)

Then in templates folder the simple_login.html contains:

<!DOCTYPE html>
<html>
<head>
    <title>Simple Login</title>
</head>
<body>
    {% with flash_messages = get_flashed_messages() %}
        {% if flash_messages %}
            <ul>
                {% for message in flash_messages %}
                    <li>
                        {{ message }}
                    </li>
                {% endfor %}
            </ul>
        {% endif %}
    {% endwith %}
    <form action="/" method="post">
        Username: <input type="text" name="username" /> <br>
        Password: <input type="password" name="password" /> <br>
        <input type="submit" name="login" value="Login" />
    </form>
</body>
</html>

Output:

To learn more about flash view examples in message flashing


问:
Left space on first letter CSS
I am using the Google font 'Lato' and I am having problems with having title and text align properly to the left... The font (when large) appears to have a kern space on the first letter and wont align left without space!?

So here also a fiddle:

```<code><h1>Hello</h1> <p>Hello, this is sentance</p>
</code>```

FIDDLE

Also, adding a negative value on the margin-left (magin-left:-10px) just seems like a terrible workaround... and this would not work overall for different font-sizes, unless individually adjusted as needed... surly there must be a better solution?

Can anyone help?

答:
PX units are not such a good choice in this case. I recommend using EM unit if you working with font attributes like line-height etc. Because it's automatically calculated for each of font-size. It should look like this:

```<code>#yourDiv::first-letter {
   margin-left: -0.12em;
}
</code>```

Title: Left space on first letter CSS

Body:
I am using the Google font 'Lato' and I am having problems with having title and text align properly to the left... The font (when large) appears to have a kern space on the first letter and wont align left without space!?

So here also a fiddle:

Hello

Hello, this is sentance

FIDDLE

Also, adding a negative value on the margin-left (magin-left:-10px) just seems like a terrible workaround... and this would not work overall for different font-sizes, unless individually adjusted as needed... surly there must be a better solution?

Can anyone help?

Body:
PX units are not such a good choice in this case. I recommend using EM unit if you working with font attributes like line-height etc. Because it's automatically calculated for each of font-size. It should look like this:

#yourDiv::first-letter {
   margin-left: -0.12em;
}


问:
Vuetify RTL style
I am new to vuetify. I need rtl v-text-field with top-right caption on it. How is that possible? I could not do that in inspector. This what i have for a now:

Any help would be appreciated

答:
there is no RTL support for vuetify right now.
but you can create your own CSS and change what you need.
first of all:
add dir=rtl to your app
and add this styles:

```<code>textarea:focus, input:focus, button:focus { outline: none !important; }

.list__tile__title {
    text-align: right;
}

.toolbar__title {
    margin-right: 16px;
}

.input-group--text-field label {
    position: absolute;
    top: 18px;
    right: 0;
}

.input-group label {
    text-align: right;
    -webkit-transform-origin: top right;
    transform-origin: top right;
}
.input-group.input-group--selection-controls label{
    right: 32px;
    left: auto;
}
.input-group.input-group--selection-controls .icon--selection-control {
    left: auto;
    right: 0;
}
.input-group--selection-controls__ripple {
    -webkit-transform: translate3d(12px,-52%,0);
    transform: translate3d(12px,-52%,0);
    left: auto;
    right: 0;
}
</code>```

it's not complete. but fix some issues

Title: Vuetify RTL style

Body:
there is no RTL support for vuetify right now.
but you can create your own CSS and change what you need.
first of all:
add dir=rtl to your app
and add this styles:

textarea:focus, input:focus, button:focus { outline: none !important; }

.list__tile__title {
    text-align: right;
}

.toolbar__title {
    margin-right: 16px;
}

.input-group--text-field label {
    position: absolute;
    top: 18px;
    right: 0;
}

.input-group label {
    text-align: right;
    -webkit-transform-origin: top right;
    transform-origin: top right;
}
.input-group.input-group--selection-controls label{
    right: 32px;
    left: auto;
}
.input-group.input-group--selection-controls .icon--selection-control {
    left: auto;
    right: 0;
}
.input-group--selection-controls__ripple {
    -webkit-transform: translate3d(12px,-52%,0);
    transform: translate3d(12px,-52%,0);
    left: auto;
    right: 0;
}

it's not complete. but fix some issues


问:
how to convert special characters URL C #
I have the following urls:

```<code>https://example.com/trabajo-abogado-civil/A-Coru%25C3%25B1a-guti%25C3%25A9rrez
</code>```

and when I get the html code, it returns me:

```<code>Excepción producida: 'System.Net.WebException' en System.dll
</code>```

I tried to code to ascii and also UTF-8 but it always returns the exception.

```<code>private string obtenerPaginaHtml(string urlPaginaHtml)
{
    try
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlPaginaHtml);
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        if (response.StatusCode == HttpStatusCode.OK)
        {
            Stream receiveStream = response.GetResponseStream();
            StreamReader readStream = null;

            if (response.CharacterSet == null)
            {
                readStream = new StreamReader(receiveStream);
            }
            else
            {
                readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
            }

            string data = readStream.ReadToEnd();

            response.Close();
            readStream.Close();

            //MessageBox.Show(data);
            return data;
        }
        else
        {
            return "";
        }
    }
    catch (WebException e)
    {
        ThreadController.InvokeIfRequired(log_listBox, () =>
        {
            log_listBox.Items.Add("Error 24 HTML: " + urlPaginaHtml + ": " + e.ToString());
        });
        logTXT("Error 24 en " + urlPaginaHtml + ": " + e.ToString());
        return "";
    }
}
</code>```

The final result would be this:

```<code>  https://example.com/trabajo-abogado-civil/A-Coruña-gutiérrez
</code>```

答:
As @Crowcoder said, your address is double encoded, but even if you properly decode you will get a 404 error message.

I've made some tests with the following code:

```<code>using System;
using System.Web;
using System.Net;
using System.IO;
using System.Text;

public class Program
{
    public static void Main()
    {
        var result = String.Empty;

        var urlPaginaHtml = "https://example.com/trabajo-abogado-civil/A-Coru%25C3%25B1a-guti%25C3%25A9rrez";
        urlPaginaHtml = HttpUtility.UrlDecode(HttpUtility.UrlDecode(urlPaginaHtml));

        //urlPaginaHtml = "https://www.google.com.br/"; <-- WORKS

        Console.WriteLine("URL: " +urlPaginaHtml);

        try
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlPaginaHtml);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            if (response.StatusCode == HttpStatusCode.OK)
            {
                Stream receiveStream = response.GetResponseStream();
                StreamReader readStream = null;

                if (response.CharacterSet == null)
                {
                    readStream = new StreamReader(receiveStream);
                }
                else
                {
                    readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
                }

                //var data = readStream.ReadToEnd();
                result = readStream.ReadToEnd();

                response.Close();
                readStream.Close();

                //MessageBox.Show(data);
                //return data;
            }
            else
            {
                //return "";
            }
            Console.WriteLine("DONE!!!");
            Console.WriteLine(result);
        }
        catch (WebException e)
        {
            Console.WriteLine("#ERROR#: " + e.Message);
        }
    }
}
</code>```

https://dotnetfiddle.net/2Rr8YF

Body:
I have the following urls:

https://example.com/trabajo-abogado-civil/A-Coru%25C3%25B1a-guti%25C3%25A9rrez

and when I get the html code, it returns me:

Excepción producida: 'System.Net.WebException' en System.dll

I tried to code to ascii and also UTF-8 but it always returns the exception.

private string obtenerPaginaHtml(string urlPaginaHtml)
{
    try
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlPaginaHtml);
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        if (response.StatusCode == HttpStatusCode.OK)
        {
            Stream receiveStream = response.GetResponseStream();
            StreamReader readStream = null;

            if (response.CharacterSet == null)
            {
                readStream = new StreamReader(receiveStream);
            }
            else
            {
                readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
            }

            string data = readStream.ReadToEnd();

            response.Close();
            readStream.Close();

            //MessageBox.Show(data);
            return data;
        }
        else
        {
            return "";
        }
    }
    catch (WebException e)
    {
        ThreadController.InvokeIfRequired(log_listBox, () =>
        {
            log_listBox.Items.Add("Error 24 HTML: " + urlPaginaHtml + ": " + e.ToString());
        });
        logTXT("Error 24 en " + urlPaginaHtml + ": " + e.ToString());
        return "";
    }
}

The final result would be this:

  https://example.com/trabajo-abogado-civil/A-Coruña-gutiérrez

Body:
As @Crowcoder said, your address is double encoded, but even if you properly decode you will get a 404 error message.

I've made some tests with the following code:

using System;
using System.Web;
using System.Net;
using System.IO;
using System.Text;

public class Program
{
    public static void Main()
    {
        var result = String.Empty;

        var urlPaginaHtml = "https://example.com/trabajo-abogado-civil/A-Coru%25C3%25B1a-guti%25C3%25A9rrez";
        urlPaginaHtml = HttpUtility.UrlDecode(HttpUtility.UrlDecode(urlPaginaHtml));

        //urlPaginaHtml = "https://www.google.com.br/"; <-- WORKS

        Console.WriteLine("URL: " +urlPaginaHtml);

        try
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlPaginaHtml);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            if (response.StatusCode == HttpStatusCode.OK)
            {
                Stream receiveStream = response.GetResponseStream();
                StreamReader readStream = null;

                if (response.CharacterSet == null)
                {
                    readStream = new StreamReader(receiveStream);
                }
                else
                {
                    readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
                }

                //var data = readStream.ReadToEnd();
                result = readStream.ReadToEnd();

                response.Close();
                readStream.Close();

                //MessageBox.Show(data);
                //return data;
            }
            else
            {
                //return "";
            }
            Console.WriteLine("DONE!!!");
            Console.WriteLine(result);
        }
        catch (WebException e)
        {
            Console.WriteLine("#ERROR#: " + e.Message);
        }
    }
}

https://dotnetfiddle.net/2Rr8YF


问:
The TypeScript Compiler was given no files for compilation, so it will skip compiling
When i am trying to Build my default JavaScript project(BlankApp Apache Cordova) in Visual Studio 2015 preview am getting following error.

The TypeScript Compiler was given no files for compilation, so it will skip compiling.

Steps Taken in visual studio 2015 preview:

File -> New -> Project -> Apache Cordova apps(under Javascript templates).

Run the default project with Android Emulator.

Getting the following error.

Warning    2   The TypeScript Compiler was given no files for compilation, so it will skip compiling.  C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v12.0\TypeScript\Microsoft.TypeScript.targets 97  5   BlankCordovaApp4

答:
Option 1:
Take Project offline, edit project, remove the following lines:

<Import
  Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.Default.props"
  Condition="Exists('$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.Default.props')"/>

and

<Import
  Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.targets"
  Condition="Exists('$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.targets')"
  />

Option 2:
Change "AddTypeScriptReferencePath": true to false in Webessentials-Settings.json


问:
How to Populate a dropdown using Enterprise Library 5.0
Is there a simple code to populate a dropdown box using Enterprise Library 5.0 DAAB?

I've tried this, but it is not working:

```<code>cmbOffice.DataSource = _db.ExecuteDataSet(
      CommandType.Text,
      "select office_id, office_name from office").Tables[0];
cmbOffice.DataBind();
</code>```

答:
cmbOffice.DataSource = _db.ExecuteDataSet(CommandType.Text,"select office_id, office_name from office").Tables[0].defaultView;<br>
cmbOffice.DataBind(); </p>

Body:
Is there a simple code to populate a dropdown box using Enterprise Library 5.0 DAAB?

I've tried this, but it is not working:

cmbOffice.DataSource = _db.ExecuteDataSet(
      CommandType.Text,
      "select office_id, office_name from office").Tables[0];
cmbOffice.DataBind();

Body:
cmbOffice.DataSource = _db.ExecuteDataSet(CommandType.Text,"select office_id, office_name from office").Tables[0].defaultView;

cmbOffice.DataBind();


问:
In Minishift, Web Console API path not changed to public domain setting
My case would be, I would like to share my minishift instance to my intranet network.

It looks like there is no option to choose the network / IP, e.g. if you try to set the virtualbox network interface to "bridge", it would just fail

So I would like to setup port forwarding, e.g. http://blog.brianjohn.com/forwarding-ports-in-os-x-el-capitan.html

In this case I am able to access to the web console, e.g. redirect port of machine IP:PORT to 192.168.64.4:8443 (minishift)

But all the API, e.g. "https://192.168.64.4:8443/api/v1" are still using the internal IP, which of course it can not be accessed externally.

Are there any way to make it work properly?

答:
When I need to access minishift from other hosts, I use SSH tunneling.
First you need to enable SSH access in your OSX and make sure you enable AllowTcpForwarding. Then create another user in your laptop to login via SSH.

From other hosts you need to login using SSH with following command:

```<code>ssh -L 8443:192.168.64.4:8443 user@<you_laptop_IP_address>
</code>```

Keep the user logged in so that you can access your minishift web console using browser to https://localhost:8443

Body:
When I need to access minishift from other hosts, I use SSH tunneling.
First you need to enable SSH access in your OSX and make sure you enable AllowTcpForwarding. Then create another user in your laptop to login via SSH.

From other hosts you need to login using SSH with following command:

ssh -L 8443:192.168.64.4:8443 user@<you_laptop_IP_address>

Keep the user logged in so that you can access your minishift web console using browser to https://localhost:8443


问:
What is the best way to create a tab view within a ViewController
I'm trying to create a design where a section of the ViewController has three buttons that show different content depending on what button is selected. Basically UITabBarController but within a viewcontroller

Basically the deer, fish and the bird icons will be buttons, showing different content in an imageView below. Is there a built in function in Xcode that you recommend for this? Or should I create three buttons, showing/hiding the relevant UIViews? What is the most efficient?

答:
Your image isn't showing up but could a Segmented Control be what you are after?

Hook its Value Changed up to an action in your View Controller and respond to which item is selected by showing/hiding different views for example:

```<code>@IBAction func controlChanged(_ sender: Any) {
    guard let segmentedControl = sender as? UISegmentedControl else { return }

    let activeViewIndex = segmentedControl.selectedSegmentIndex
    // Show the view based on activeViewIndex here
}
</code>```

Body:
Your image isn't showing up but could a Segmented Control be what you are after?

Hook its Value Changed up to an action in your View Controller and respond to which item is selected by showing/hiding different views for example:

@IBAction func controlChanged(_ sender: Any) {
    guard let segmentedControl = sender as? UISegmentedControl else { return }

    let activeViewIndex = segmentedControl.selectedSegmentIndex
    // Show the view based on activeViewIndex here
}