问:
Unable to create a Wordpress multisite network for an existing installation, A Last Hope
I have a website with some large number of posts like (75k posts).

Till now, i am using a plugin called Main Category As Sub-domain to convert categories into sub-domains.

ISSUE - 1 → In recent wordpress 4.7 update, few functions of that plugins are depreciated. I don't think that plugin's author is going update it.

ISSUE - 2 → I tried to use its alternative plugins, but they are having some permalink restrictions which are causing 404 errors for my existing posts. So, i cant use them.

My current permalink structure is /%post_id%/%postname%/

After all, I decided to convert my single WP into Multisite.

I followed all steps in http://codex.wordpress.org/Create_A_Network

But after changing .htaccess and wp-config.php, I logged out.

ISSUE - 3 →When i login again, i am not seeing anything new in WP Dashboard. (i.e) Network is not setup. I tried it many times but no use.

I am not able to understand what is causing this issue.

ISSUE - 4 → Also, i tried to create an alternative WP multisite to export all category posts to specific sub-sites. I know this will work but taking long time to process exporting and importing as i can only export 2000-2500 posts at once.

MY IDEAS

Using .htaccess rules to redirect 404 errors when using alternative
plugins.

Importing and Exporting posts with help of MySQL.

I don't know whether these are possible or not. But

Please help me, setup a network for my site.

Or provide any alternative idea.

Any kind of response would be appreciated.

Thanks in advance.

答: In wp-config.php make define('WP_DEBUG', true);. It will show you what and where the problem is.</p>


来源: stackexchange

问:
Running Phantomjs.exe in a ASP.NET Core in Azure App Service
I have an ReSTful API implemented in .Net Core 2.0.0 and hosted in an App Service in Azure.

I am trying to get one of the Controllers to generate a PDF file using PhantomJS.exe

so I have created this method

summary of the controller is

```<code>        System.Diagnostics.Process pProcess = new System.Diagnostics.Process();
        pProcess.StartInfo.FileName = config.pjlocation;
        pProcess.StartInfo.Arguments = ....; //argument
        pProcess.StartInfo.UseShellExecute = false;
        pProcess.StartInfo.RedirectStandardOutput = true;
        pProcess.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
        pProcess.StartInfo.CreateNoWindow = true; //not diplay a windows
        pProcess.Start();
        output = pProcess.StandardOutput.ReadToEnd(); //The output result
        pProcess.WaitForExit();
</code>```

this works well when I run my controller locally using

```<code>dotnet run
</code>```

on a windows machine with the same version of .Net Core as the one azure uses.

But hitting the API when deployed to azure, the service fails to produce any response for a long time and comes back with this error

The specified CGI application encountered an error and the server
  terminated the process.

the only place I found some traces is the live log stream in azure where a HTML gets dumped into console by azure

HTTP Error 502.3 - Bad Gateway The specified CGI application
  encountered an error and the server terminated the process.

What is happening here and has anyone encountered similar issue? How can I further debug?

答:
You could get the answer from Azure Web App sandbox, PhantomJS is not supported on the Azure WebApp.

Other scenarios that are not supported:

PhantomJS/Selenium: tries to connect to local address, and also uses GDI+.

According to the Azure Web App sandbox, The following PDF generators are supported. If WebApp is not the only choose, you could refer to Azure cloudservie or Azure VM.

SQL Reporting framework: requires the site to run in Basic or higher (not that this currently does not work Functions apps)

EVOPDF: See http://www.evopdf.com/azure-html-to-pdf-converter.aspx for vendor solution

Telerik reporting: requires the site to run in Basic or higher. More info here

Rotativa / wkhtmltopdf: requires the site to run in Basic or higher.

NReco PdfGenerator (wkhtmltopdf): requires subscription plan Basic or higher

ContentLicense: CC BY-SA 3.0

Body:
I have an ReSTful API implemented in .Net Core 2.0.0 and hosted in an App Service in Azure.

I am trying to get one of the Controllers to generate a PDF file using PhantomJS.exe

so I have created this method

summary of the controller is

        System.Diagnostics.Process pProcess = new System.Diagnostics.Process();
        pProcess.StartInfo.FileName = config.pjlocation;
        pProcess.StartInfo.Arguments = ....; //argument
        pProcess.StartInfo.UseShellExecute = false;
        pProcess.StartInfo.RedirectStandardOutput = true;
        pProcess.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
        pProcess.StartInfo.CreateNoWindow = true; //not diplay a windows
        pProcess.Start();
        output = pProcess.StandardOutput.ReadToEnd(); //The output result
        pProcess.WaitForExit();

this works well when I run my controller locally using

dotnet run

on a windows machine with the same version of .Net Core as the one azure uses.

But hitting the API when deployed to azure, the service fails to produce any response for a long time and comes back with this error

The specified CGI application encountered an error and the server
  terminated the process.

the only place I found some traces is the live log stream in azure where a HTML gets dumped into console by azure

HTTP Error 502.3 - Bad Gateway The specified CGI application
  encountered an error and the server terminated the process.

What is happening here and has anyone encountered similar issue? How can I further debug?


问:
how to specify point of sale dashboard for a user in odoo 10?
How i can specify point of sale dashboard for specific user/ users who can see his/ her orders on dashboard when they logged into point of sale via their login account ?

Is there possibility to write expression with multiple OR / And conditions ?

答:
If I understand your question well, this is how to Restrict POS user from viewing other users' orders

Create a new Record Rule (Settings > Security > Record Rules)

Named it anything you want

Object is Point of Sales Orders

Rule Definition: [('user_id','=',user.id)]

Groups Point of Sale / User

Now your POS users should only see orders created by themself.

You can also Assign a specific User to opening session on one POS by

Create a field (Settings > Database Structure > Fields)

Named it: x_user_id

Field type: many2one

Model: pos.config

Relation of object: res.users

Add the field to pos.config.form.view (Settings > User Interface > Views)

<group name="assigned_users" string="Assigned Users">
    <field name="x_user_id" string="Assigned Users" />
</group>

Create a Record Rule (Settings > Security > Record Rules)

Named it anything you want

Object: pos.config

Rule Definition: [('x_user_id','=',user.id)]

Groups: Point of Sale / User

Assign user to a POS. Go to Point of Sale > Configuration > Point of Sale > Select a POS > Assigned Users

Now  except Admin (with Manager role) can open Session on all POS, only assigned user can open sessions in a given POS.


问:
Where to put "Non-Authorization" Access Control Logic, Doesn't seem to fit into ACL?
I am wondering for "Non-Authorization" Access Control Logic eg. One can only add children todos on top level todos. It doesn't seem to fit into ACL's where it seem to be more for Authentication/Authorization Access Control Logic?

Do I put all into my ACL? I must somehow show different error messages tho, eg. 'You cannot perform this action' instead of 'You don't have sufficient permissions to perform this action' ... how might I do this?

答:
You should handle the access logic outside your access list object. I created a frontController plugin for this purpose:

```<code>class Soflomo_Controller_Plugin_Access extends Zend_Controller_Plugin_Abstract
{
    public function dispatchLoopStartup (Zend_Controller_Request_Abstract $request)
    {
        if (!$this->_isAllowed($request)) {
            throw new Zend_Controller_Action_Exception('No permission', 403);
        }
    }

    protected function _isAllowed (Zend_Controller_Request_Abstract $request, $permission = 'view')
    {
        $acl = new Acl(); // Here your logic to fetch a (cached) ACL
        $role = new User(); // Here your logic to fetch role
        $resource = new Page(); // Here your logic to fetch resource

        return $acl->hasRole($role)
            && $acl->has($resource)
            && $acl->isAllowed($role, $resource, $permission);
    }
}
</code>```

In this case, I explicitly check the existence of a role and resource. This is because I have only the ACL rules in my database where the role has access to the resource. All other cases (when user does not have the access) I leave it out of the database.

When you have a different logic, it is perhaps enough to check for $acl->isAllowed($role, $resource, $permission); and leave the $acl->hasRole() and $acl->has() out.

Error handler

I throw a Zend_Controller_Action_Exception with error code 403, but if you don't catch the specific code, it will look like a normal application error. Therefore I added in the ErrorHandler frontController plugin another constant EXCEPTION_NO_PERMISSION and added this to the switch statement:

```<code>case 'Zend_Controller_Action_Exception':
if (404 == $exception->getCode()) {
    $error->type = self::EXCEPTION_NO_ACTION;
} elseif (403 == $exception->getCode()) {
    $error->type = self::EXCEPTION_NO_PERMISSION;
} else {
    $error->type = self::EXCEPTION_OTHER;
}
break;
</code>```

Then you can fetch the error type EXCEPTION_NO_PERMISSION in your ErrorController.

ContentLicense: CC BY-SA 2.5

Body:
You should handle the access logic outside your access list object. I created a frontController plugin for this purpose:

class Soflomo_Controller_Plugin_Access extends Zend_Controller_Plugin_Abstract
{
    public function dispatchLoopStartup (Zend_Controller_Request_Abstract $request)
    {
        if (!$this->_isAllowed($request)) {
            throw new Zend_Controller_Action_Exception('No permission', 403);
        }
    }

    protected function _isAllowed (Zend_Controller_Request_Abstract $request, $permission = 'view')
    {
        $acl = new Acl(); // Here your logic to fetch a (cached) ACL
        $role = new User(); // Here your logic to fetch role
        $resource = new Page(); // Here your logic to fetch resource

        return $acl->hasRole($role)
            && $acl->has($resource)
            && $acl->isAllowed($role, $resource, $permission);
    }
}

In this case, I explicitly check the existence of a role and resource. This is because I have only the ACL rules in my database where the role has access to the resource. All other cases (when user does not have the access) I leave it out of the database.

When you have a different logic, it is perhaps enough to check for $acl->isAllowed($role, $resource, $permission); and leave the $acl->hasRole() and $acl->has() out.

Error handler

I throw a Zend_Controller_Action_Exception with error code 403, but if you don't catch the specific code, it will look like a normal application error. Therefore I added in the ErrorHandler frontController plugin another constant EXCEPTION_NO_PERMISSION and added this to the switch statement:

case 'Zend_Controller_Action_Exception':
if (404 == $exception->getCode()) {
    $error->type = self::EXCEPTION_NO_ACTION;
} elseif (403 == $exception->getCode()) {
    $error->type = self::EXCEPTION_NO_PERMISSION;
} else {
    $error->type = self::EXCEPTION_OTHER;
}
break;

Then you can fetch the error type EXCEPTION_NO_PERMISSION in your ErrorController.


问:
Passing UI objects as Constructor Parameters
public ContactsPanel(Activity activity,GoogleMap mGoogleMap)

I have a Class with this Constructor. This class basically inflates a UI on "activity" with Marker details when a marker is clicked on mGoogleMaps. My questions for the community are:

If I am creating 1st instance of ContactsPanel then am I forcing OS to duplicate memory allocation for the objects activity and mGoogleMap?

And what if I have 10 instances of ContactsPanel? Will that mean 10 Google Maps in memory and 10 Activities in memory? Or will all the objects will be referring to same object, that was originally created?

Thanks!

答:
No, you won't be duplicating instances of activity or googleMaps or any other Ojects which you pass as parameter.

Once you create instance, it will be stored in heap at memory location X, when you invoke ContactPanel(activity,mGoogleMap) then a new instance of ContactsPanel is created at location Y in heap and the variables activity and mGoogleMaps inside ContactPanel are still pointing to X in heap.

EDIT

To answer your question about drawbacks, It's OK if you have N modifiers for single instance of heavy object however the problem comes in memory leak,
Consider you shared your activity instance with 10 objects, now even if you finished your activity , but one of your 10 objects which holds reference to that is still live in memory, it wont let gc to collect activity's memory.


问:
Special characters breaking textbox submission
Currently dealing with a bug if a user submits a special character into a textbox like '/' or '&' the information submits and displays on their profile page but on page reload all input boxes are empty and the user cannot submit any more changes. This is after a page refresh, all the fields I just filled out are now blank, and trying to submit 'test' into the bio i get this console error:

Here's the form html:

```<code><form class="login-signup-form">
    <label for="display-name">Display Name</label>
    <input id="display-name" name="display-name" type="text" placeholder="Name">
    <label for="email">Email</label>
    <input id="email" name="email" type="email" placeholder="Email">
    <label for="twitter-link">Twitter link</label>
    <input id="twitter-link" name="twitter-link" type="url" placeholder="https://">
    <label for="instagram-link">Instagram link</label>
    <input id="instagram-link" name="instagram-link" type="url" placeholder="https://">
    <label for="youtube-link">YouTube link</label>
    <input id="youtube-link" name="youtube-link" type="url" placeholder="https://">
    <label for="web-link">Website</label>
    <input id="web-link" name="web-link" type="url" placeholder="https://">
    <label for="artist-bio">Bio</label>
    <textarea id="artist-bio" name="artist-bio" type="text" rows="5" maxlength="250" placeholder="Share what you want (Max: 250 characters)"></textarea>
    <hr />
    <label for="allow-collaboration">Allow collaboration?</label>
    <input id="allow-collaboration" name="allow-collaboration" type="checkbox">
    <h5>Checking the box will display your email address on your Creator page. This indicates your interest in collaborating with other Unearth creators.</h5>
    <input type="button" value="Submit" onclick="submitAccountInfo();">
</form>
</code>```

The respective Jquery that loads the data into the input fields and update fields:

```<code>$(document).ready(function()
{
    setFormValues();
});
function setFormValues()
{
    if("@(!String.IsNullOrWhiteSpace(Model.AccountInfo.ImageURL))" == "True")
    {
        $("#profile-image").attr("src", "@Model.AccountInfo.ImageURL");
    }
    if("@(!String.IsNullOrWhiteSpace(Model.AccountInfo.DisplayName))" == "True")
    {
        $("#display-name").val("@Html.Raw(Model.AccountInfo.DisplayName)");
    }
    if("@(!String.IsNullOrWhiteSpace(Model.AspNetUser.Email))" == "True")
    {
        $("#email").val("@Html.Raw(Model.AspNetUser.Email)");
    }
    if("@(!String.IsNullOrWhiteSpace(Model.AccountInfo.TwitterURL))" == "True")
    {
        $("#twitter-link").val("@Model.AccountInfo.TwitterURL");
    }
    if("@(!String.IsNullOrWhiteSpace(Model.AccountInfo.InstagramURL))" == "True")
    {
            $("#instagram-link").val("@Model.AccountInfo.InstagramURL");
    }
    if("@(!String.IsNullOrWhiteSpace(Model.AccountInfo.YouTubeURL))" == "True")
    {
        $("#youtube-link").val("@Model.AccountInfo.YouTubeURL");
    }
    if("@(!String.IsNullOrWhiteSpace(Model.AccountInfo.WebURL))" == "True")
    {
        $("#web-link").val("@Model.AccountInfo.WebURL");
    }
    if("@(!String.IsNullOrWhiteSpace(Model.AccountInfo.Bio))" == "True")
    {
        $("#artist-bio").html("@Model.AccountInfo.Bio").text();
    }
    if("@(Model.AccountInfo.AllowCollaborationFL.HasValue ? Model.AccountInfo.AllowCollaborationFL.Value : false)" == "True")
    {
        $("#allow-collaboration").prop("checked", true);
    }
}

    function updateAspNetUserEmail()
{
    var aspNetUser = new Object();
    aspNetUser.Email = $("#email").val();
    $.ajax
    ({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        url: "@Url.Content("~/Account/SubmitEmailInfo/")",
        data: JSON.stringify(aspNetUser),
        success: function(data)
        {
            if(data == true)
            {
                location.reload(true);
            }
        },
        error: function(jqXHR, textStatus, errorThrown)
        {
            //TODO: Indicate Error
        }
        });
}

function submitAccountInfo()
{
    var accountInfo = new Object();
    accountInfo.ImageURL = $("#profile-image").attr("src");
    accountInfo.DisplayName = $("#display-name").val();
    //accountInfo.Email = $("#email").val();
    accountInfo.TwitterURL = $("#twitter-link").val();
    accountInfo.InstagramURL = $("#instagram-link").val();
    accountInfo.YouTubeURL = $("#youtube-link").val();
    accountInfo.WebURL = $("#web-link").val();
    accountInfo.Bio = $("#artist-bio").val();
    accountInfo.AllowCollaborationFL = $("#allow-collaboration").is(":checked");
    $.ajax
    ({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        url: "@Url.Content("~/Account/SubmitAccountInfo/")",
        data: JSON.stringify(accountInfo),
        success: function(data)
        {
            if(data == true)
            {
                updateAspNetUserEmail();
            }
        },
        error: function(jqXHR, textStatus, errorThrown)
        {
            //TODO: Indicate Error
        }
        });
}
</code>```

And lastly, here's my accountcontroller with the Jsonsubmits:

```<code>public JsonResult SubmitEmailInfo(AspNetUser aspNetUser)
{
    try
    {
        var userID = User.Identity.GetUserId();
        aspNetUser.Id = userID;
        var _aspNetUser = EntityDataAccess.GetAspNetUserByID(userID);
        if (_aspNetUser == null)
        {
            aspNetUser = EntityDataAccess.InsertEmailInfo(aspNetUser);
        }
        else
        {
            aspNetUser.Id = _aspNetUser.Id;
            aspNetUser.EmailConfirmed = _aspNetUser.EmailConfirmed;
            aspNetUser.PasswordHash = _aspNetUser.PasswordHash;
            aspNetUser.SecurityStamp = _aspNetUser.SecurityStamp;
            aspNetUser.PhoneNumber = _aspNetUser.PhoneNumber;
            aspNetUser.PhoneNumberConfirmed = _aspNetUser.PhoneNumberConfirmed;
            aspNetUser.TwoFactorEnabled = _aspNetUser.TwoFactorEnabled;
            aspNetUser.LockoutEnabled = _aspNetUser.LockoutEnabled;
            aspNetUser.LockoutEndDateUtc = _aspNetUser.LockoutEndDateUtc;
            aspNetUser.AccessFailedCount = _aspNetUser.AccessFailedCount;
            aspNetUser.UserName = _aspNetUser.UserName;
            aspNetUser = EntityDataAccess.UpdateEmailInfo(aspNetUser);
        }
        return Json(true);
    }
    catch (Exception ex)
    {
        return Json(ex);
    }
}

public JsonResult SubmitAccountInfo(AccountInfo accountInfo)
{
    try
    {
        var userID = User.Identity.GetUserId();
        accountInfo.UserID = userID;
        var _accountInfo = EntityDataAccess.GetAccountInfoByUserID(userID);
        if(_accountInfo == null)
        {
            accountInfo = EntityDataAccess.InsertAccountInfo(accountInfo);
        }
        else
        {
            accountInfo.AccountInfoID = _accountInfo.AccountInfoID;
            accountInfo.CreatorFL = _accountInfo.CreatorFL;
            accountInfo.NeedsVerificationFL = _accountInfo.NeedsVerificationFL;
            accountInfo.VerifiedFL = _accountInfo.VerifiedFL;
            accountInfo.AdminFL = _accountInfo.AdminFL;
            accountInfo = EntityDataAccess.UpdateAccountInfo(accountInfo);
        }
        var algoliaArtistModel = Tools.BuildAlgoliaArtistModel(accountInfo);
        var artistIndexHelper = HttpContext.Application.Get("ArtistIndexHelper") as IndexHelper<ArtistAlgoliaModel>;
        artistIndexHelper.SaveObjectAsync(algoliaArtistModel);
        var algoliaSongModels = Tools.BuildAlgoliaSongModels(accountInfo);
        var songIndexHelper = HttpContext.Application.Get("SongIndexHelper") as IndexHelper<SongAlgoliaModel>;
        songIndexHelper.SaveObjectsAsync(algoliaSongModels);
        return Json(true);
    }
    catch(Exception ex)
    {
        return Json(ex);
    }
}
</code>```

答:
Use Ajax Toolkit
 Example,</p>

```<code> <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>

 <cc1:FilteredTextBoxExtender ID="FilteredTextBoxExtender_txtName" runat="server"
                                  Enabled="True" FilterType="LowercaseLetters,UppercaseLetters,Custom" FilterMode="InvalidChars"
                                  InvalidChars="1234567890<>'" TargetControlID="txtName">
</cc1:FilteredTextBoxExtender>
</code>```

Body:
Currently dealing with a bug if a user submits a special character into a textbox like '/' or '&' the information submits and displays on their profile page but on page reload all input boxes are empty and the user cannot submit any more changes. This is after a page refresh, all the fields I just filled out are now blank, and trying to submit 'test' into the bio i get this console error:

Here's the form html:

<form class="login-signup-form">
    Display Name
    <input id="display-name" name="display-name" type="text" placeholder="Name">
    Email
    <input id="email" name="email" type="email" placeholder="Email">
    Twitter link
    <input id="twitter-link" name="twitter-link" type="url" placeholder="https://">
    Instagram link
    <input id="instagram-link" name="instagram-link" type="url" placeholder="https://">
    YouTube link
    <input id="youtube-link" name="youtube-link" type="url" placeholder="https://">
    Website
    <input id="web-link" name="web-link" type="url" placeholder="https://">
    Bio
    <textarea id="artist-bio" name="artist-bio" type="text" rows="5" maxlength="250" placeholder="Share what you want (Max: 250 characters)"></textarea>

    Allow collaboration?
    <input id="allow-collaboration" name="allow-collaboration" type="checkbox">

Checking the box will display your email address on your Creator page. This indicates your interest in collaborating with other Unearth creators.

    <input type="button" value="Submit" onclick="submitAccountInfo();">
</form>

The respective Jquery that loads the data into the input fields and update fields:

$(document).ready(function()
{
    setFormValues();
});
function setFormValues()
{
    if("@(!String.IsNullOrWhiteSpace(Model.AccountInfo.ImageURL))" == "True")
    {
        $("#profile-image").attr("src", "@Model.AccountInfo.ImageURL");
    }
    if("@(!String.IsNullOrWhiteSpace(Model.AccountInfo.DisplayName))" == "True")
    {
        $("#display-name").val("@Html.Raw(Model.AccountInfo.DisplayName)");
    }
    if("@(!String.IsNullOrWhiteSpace(Model.AspNetUser.Email))" == "True")
    {
        $("#email").val("@Html.Raw(Model.AspNetUser.Email)");
    }
    if("@(!String.IsNullOrWhiteSpace(Model.AccountInfo.TwitterURL))" == "True")
    {
        $("#twitter-link").val("@Model.AccountInfo.TwitterURL");
    }
    if("@(!String.IsNullOrWhiteSpace(Model.AccountInfo.InstagramURL))" == "True")
    {
            $("#instagram-link").val("@Model.AccountInfo.InstagramURL");
    }
    if("@(!String.IsNullOrWhiteSpace(Model.AccountInfo.YouTubeURL))" == "True")
    {
        $("#youtube-link").val("@Model.AccountInfo.YouTubeURL");
    }
    if("@(!String.IsNullOrWhiteSpace(Model.AccountInfo.WebURL))" == "True")
    {
        $("#web-link").val("@Model.AccountInfo.WebURL");
    }
    if("@(!String.IsNullOrWhiteSpace(Model.AccountInfo.Bio))" == "True")
    {
        $("#artist-bio").html("@Model.AccountInfo.Bio").text();
    }
    if("@(Model.AccountInfo.AllowCollaborationFL.HasValue ? Model.AccountInfo.AllowCollaborationFL.Value : false)" == "True")
    {
        $("#allow-collaboration").prop("checked", true);
    }
}

    function updateAspNetUserEmail()
{
    var aspNetUser = new Object();
    aspNetUser.Email = $("#email").val();
    $.ajax
    ({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        url: "@Url.Content("~/Account/SubmitEmailInfo/")",
        data: JSON.stringify(aspNetUser),
        success: function(data)
        {
            if(data == true)
            {
                location.reload(true);
            }
        },
        error: function(jqXHR, textStatus, errorThrown)
        {
            //TODO: Indicate Error
        }
        });
}

function submitAccountInfo()
{
    var accountInfo = new Object();
    accountInfo.ImageURL = $("#profile-image").attr("src");
    accountInfo.DisplayName = $("#display-name").val();
    //accountInfo.Email = $("#email").val();
    accountInfo.TwitterURL = $("#twitter-link").val();
    accountInfo.InstagramURL = $("#instagram-link").val();
    accountInfo.YouTubeURL = $("#youtube-link").val();
    accountInfo.WebURL = $("#web-link").val();
    accountInfo.Bio = $("#artist-bio").val();
    accountInfo.AllowCollaborationFL = $("#allow-collaboration").is(":checked");
    $.ajax
    ({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        url: "@Url.Content("~/Account/SubmitAccountInfo/")",
        data: JSON.stringify(accountInfo),
        success: function(data)
        {
            if(data == true)
            {
                updateAspNetUserEmail();
            }
        },
        error: function(jqXHR, textStatus, errorThrown)
        {
            //TODO: Indicate Error
        }
        });
}

And lastly, here's my accountcontroller with the Jsonsubmits:

public JsonResult SubmitEmailInfo(AspNetUser aspNetUser)
{
    try
    {
        var userID = User.Identity.GetUserId();
        aspNetUser.Id = userID;
        var _aspNetUser = EntityDataAccess.GetAspNetUserByID(userID);
        if (_aspNetUser == null)
        {
            aspNetUser = EntityDataAccess.InsertEmailInfo(aspNetUser);
        }
        else
        {
            aspNetUser.Id = _aspNetUser.Id;
            aspNetUser.EmailConfirmed = _aspNetUser.EmailConfirmed;
            aspNetUser.PasswordHash = _aspNetUser.PasswordHash;
            aspNetUser.SecurityStamp = _aspNetUser.SecurityStamp;
            aspNetUser.PhoneNumber = _aspNetUser.PhoneNumber;
            aspNetUser.PhoneNumberConfirmed = _aspNetUser.PhoneNumberConfirmed;
            aspNetUser.TwoFactorEnabled = _aspNetUser.TwoFactorEnabled;
            aspNetUser.LockoutEnabled = _aspNetUser.LockoutEnabled;
            aspNetUser.LockoutEndDateUtc = _aspNetUser.LockoutEndDateUtc;
            aspNetUser.AccessFailedCount = _aspNetUser.AccessFailedCount;
            aspNetUser.UserName = _aspNetUser.UserName;
            aspNetUser = EntityDataAccess.UpdateEmailInfo(aspNetUser);
        }
        return Json(true);
    }
    catch (Exception ex)
    {
        return Json(ex);
    }
}

public JsonResult SubmitAccountInfo(AccountInfo accountInfo)
{
    try
    {
        var userID = User.Identity.GetUserId();
        accountInfo.UserID = userID;
        var _accountInfo = EntityDataAccess.GetAccountInfoByUserID(userID);
        if(_accountInfo == null)
        {
            accountInfo = EntityDataAccess.InsertAccountInfo(accountInfo);
        }
        else
        {
            accountInfo.AccountInfoID = _accountInfo.AccountInfoID;
            accountInfo.CreatorFL = _accountInfo.CreatorFL;
            accountInfo.NeedsVerificationFL = _accountInfo.NeedsVerificationFL;
            accountInfo.VerifiedFL = _accountInfo.VerifiedFL;
            accountInfo.AdminFL = _accountInfo.AdminFL;
            accountInfo = EntityDataAccess.UpdateAccountInfo(accountInfo);
        }
        var algoliaArtistModel = Tools.BuildAlgoliaArtistModel(accountInfo);
        var artistIndexHelper = HttpContext.Application.Get("ArtistIndexHelper") as IndexHelper<ArtistAlgoliaModel>;
        artistIndexHelper.SaveObjectAsync(algoliaArtistModel);
        var algoliaSongModels = Tools.BuildAlgoliaSongModels(accountInfo);
        var songIndexHelper = HttpContext.Application.Get("SongIndexHelper") as IndexHelper<SongAlgoliaModel>;
        songIndexHelper.SaveObjectsAsync(algoliaSongModels);
        return Json(true);
    }
    catch(Exception ex)
    {
        return Json(ex);
    }
}

Body:
Use Ajax Toolkit
 Example,

 <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>

 <cc1:FilteredTextBoxExtender ID="FilteredTextBoxExtender_txtName" runat="server"
                                  Enabled="True" FilterType="LowercaseLetters,UppercaseLetters,Custom" FilterMode="InvalidChars"
                                  InvalidChars="1234567890<>'" TargetControlID="txtName">
</cc1:FilteredTextBoxExtender>


问:
Getting an exception like "Items collection must be empty before using ItemsSource." while trying to set the itemsource of a child DataGrid in WPF
I have a Datagrid and another DataGrid nested inside the parent DataGrid. I need to set the ItemSource of the child DataGrid as a property of the parent DataContext. I already tried to use RelativeSource for the child itemsource to get the parent datacontext.

xaml code

```<code><DataGrid Grid.Row ="1" x:Name="Grid1" ItemsSource="{Binding Path=md,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" AutoGenerateColumns="False">
    <DataGrid.Columns>
      <DataGridTextColumn Header="Categogy" Width="100"  Binding="{Binding Path =CateName,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
      <DataGridTemplateColumn Header="Characterictics" Width="300">
           <DataGridTemplateColumn.CellTemplate>
             <DataTemplate>
               <DataGrid ItemsSource="{Binding DataContext.list, RelativeSource={RelativeSource AncestorType=DataGrid}}">
                 <DataGridTextColumn Binding="{Binding DataContext.list.Name, RelativeSource={RelativeSource AncestorType=DataGrid}}" />
               </DataGrid>
             </DataTemplate>
           </DataGridTemplateColumn.CellTemplate>
      </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>
</code>```

ViewModel

```<code>Model m = new Model();
m.CateName = "CategoryName";
m.list.Add(new Characteristics() { Name="XX", Value="00"});
m.list.Add(new Characteristics() { Name = "XX", Value = "00" });
m.list.Add(new Characteristics() { Name = "XX", Value = "00" });
md.Add(m);

Model m1 = new Model();
m1.CateName = "CategoryName1";
m1.list.Add(new Characteristics() { Name = "XX", Value = "00" });
m1.list.Add(new Characteristics() { Name = "XX", Value = "00" });
m1.list.Add(new Characteristics() { Name = "XX", Value = "00" });
md.Add(m1);

list = new ObservableCollection<Characteristics>();
list.Add(new Characteristics() { Name = "XX", Value = "00" });
list.Add(new Characteristics() { Name = "XX", Value = "00" });
</code>```

The Characteristics class has properties Name and Model.

Now, I am getting exception like "Items collection must be empty before using ItemsSource."

I am not sure where I am doing wrong?
Can someone please help me to correctly bind the child dataGrid Itemsource?

答:
for the nested DataGrid place DataGridTextColumn into a <DataGrid.Columns> tag

```<code><DataGrid ItemsSource="{Binding list}">
  <DataGrid.Columns>
    <DataGridTextColumn Binding="{Binding Name}" />
  </DataGrid.Columns>
</DataGrid>
</code>```

otherwise DataGridTextColumn is interpreted as Item and causes error with itemsSource

and also fix bindings, they don't need to use parent DataContext

Body:
I have a Datagrid and another DataGrid nested inside the parent DataGrid. I need to set the ItemSource of the child DataGrid as a property of the parent DataContext. I already tried to use RelativeSource for the child itemsource to get the parent datacontext.

xaml code

<DataGrid Grid.Row ="1" x:Name="Grid1" ItemsSource="{Binding Path=md,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" AutoGenerateColumns="False">
    <DataGrid.Columns>
      <DataGridTextColumn Header="Categogy" Width="100"  Binding="{Binding Path =CateName,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
      <DataGridTemplateColumn Header="Characterictics" Width="300">
           <DataGridTemplateColumn.CellTemplate>
             <DataTemplate>
               <DataGrid ItemsSource="{Binding DataContext.list, RelativeSource={RelativeSource AncestorType=DataGrid}}">
                 <DataGridTextColumn Binding="{Binding DataContext.list.Name, RelativeSource={RelativeSource AncestorType=DataGrid}}" />
               </DataGrid>
             </DataTemplate>
           </DataGridTemplateColumn.CellTemplate>
      </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

ViewModel

Model m = new Model();
m.CateName = "CategoryName";
m.list.Add(new Characteristics() { Name="XX", Value="00"});
m.list.Add(new Characteristics() { Name = "XX", Value = "00" });
m.list.Add(new Characteristics() { Name = "XX", Value = "00" });
md.Add(m);

Model m1 = new Model();
m1.CateName = "CategoryName1";
m1.list.Add(new Characteristics() { Name = "XX", Value = "00" });
m1.list.Add(new Characteristics() { Name = "XX", Value = "00" });
m1.list.Add(new Characteristics() { Name = "XX", Value = "00" });
md.Add(m1);

list = new ObservableCollection<Characteristics>();
list.Add(new Characteristics() { Name = "XX", Value = "00" });
list.Add(new Characteristics() { Name = "XX", Value = "00" });

The Characteristics class has properties Name and Model.

Now, I am getting exception like "Items collection must be empty before using ItemsSource."

I am not sure where I am doing wrong?
Can someone please help me to correctly bind the child dataGrid Itemsource?

Body:
for the nested DataGrid place DataGridTextColumn into a <DataGrid.Columns> tag

<DataGrid ItemsSource="{Binding list}">
  <DataGrid.Columns>
    <DataGridTextColumn Binding="{Binding Name}" />
  </DataGrid.Columns>
</DataGrid>

otherwise DataGridTextColumn is interpreted as Item and causes error with itemsSource

and also fix bindings, they don't need to use parent DataContext


问:
error when connecting oracle in python using cx_Oracle
I was trying to connect oracle database using python like below.

```<code>import cx_Oracle
conn = cx_Oracle.connect('user/password@host:port/database')
</code>```

I've faced an error when connecting oracle.
DatabaseError: DPI-1047: 64-bit Oracle Client library cannot be loaded: "libclntsh.so: cannot open shared object file: No such file or directory". See https://oracle.github.io/odpi/doc/installation.html#linux for help.

I've been struggling to figure it out. I used my user name, password, host, port and database('orcl') for example,

'admin/admin@10.10.10.10:1010/orcl'.

Why coudn't it connect?

Ahh, btw I'm running all the code in azure notebooks.

答: This seems a problem with version 6.X.This problem didnot appeared in 5.X.But for my case a little workaround worked.I installed in my physical machine and only thing that i need to do was a pc reboot or reopen the terminal as i have added in the path of environment variables.You can try to install in physical machine instead using azure notebooks.</p>

Body:
I was trying to connect oracle database using python like below.

import cx_Oracle
conn = cx_Oracle.connect('user/password@host:port/database')

I've faced an error when connecting oracle.
DatabaseError: DPI-1047: 64-bit Oracle Client library cannot be loaded: "libclntsh.so: cannot open shared object file: No such file or directory". See https://oracle.github.io/odpi/doc/installation.html#linux for help.

I've been struggling to figure it out. I used my user name, password, host, port and database('orcl') for example,

'admin/admin@10.10.10.10:1010/orcl'.

Why coudn't it connect?

Ahh, btw I'm running all the code in azure notebooks.


问:
Read two bytes into an integer?
I have a byte[] that I've read from a file, and I want to get an int from two bytes in it. Here's an example:

```<code>byte[] bytes = new byte[] {(byte)0x00, (byte)0x2F, (byte)0x01, (byte)0x10, (byte)0x6F};
int value = bytes.getInt(2,4); //This method doesn't exist
</code>```

This should make value equal to 0x0110, or 272 in decimal. But obviously, byte[].getInt() doesn't exist. How can I accomplish this task?

The above array is just an example. Actual values are unknown to me.

答:
Alternatively, you could use:</p>

```<code>int val = (bytes[2] << 8) + bytes[3]
</code>```

Title: Read two bytes into an integer?

Body:
I have a byte[] that I've read from a file, and I want to get an int from two bytes in it. Here's an example:

byte[] bytes = new byte[] {(byte)0x00, (byte)0x2F, (byte)0x01, (byte)0x10, (byte)0x6F};
int value = bytes.getInt(2,4); //This method doesn't exist

This should make value equal to 0x0110, or 272 in decimal. But obviously, byte[].getInt() doesn't exist. How can I accomplish this task?

The above array is just an example. Actual values are unknown to me.

Body:
Alternatively, you could use:

int val = (bytes[2] << 8) + bytes[3]


问:
Best approach for creating http request service?
I created one service for handling all http request. It is working perfectly. But I want to know is there any fault in my approach and also want to know other good approaches like observable?

request.service.js

```<code>import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
import { catchError, map, tap } from 'rxjs/operators';

import { MessageService } from './message.service';

const httpOptions = {
    headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' })
};

interface IRequestOption {
    url: string;
    cxfgroup: string;
    endpoint: string;
    data: object;
}

interface IRequestBody {
    option: IRequestOption;
    log: string;
    error: string;
}

class HTTP {

    private messageService: MessageService;

    constructor(http, messageService, url: string, body: object, log: string, error: string) {
        this.callHTTP(http, url, body, log, error);
        this.messageService = messageService;
    }

    callHTTP(http, url, body, log, error) {
        return http.post(url, body, httpOptions).toPromise()
            .then(this.extractData)
            .catch(this.handleErrorPromise);
    }

    private extractData(res: Response) {
        // let body = res.json();
        // return body['data'] || {};
        return res || {};
    }

    private handleErrorPromise(error: Response | any) {
        console.error(error.message || error);
        return Promise.reject(error.message || error);
    }
}

class RequestFactory {
    private baseURL = 'https://app.domain.com/cxf/';
    /**
     * CXF ENPOINTS
     */
    private endpoints: any = {
        "auth": {
            "getcustomerkeys": "auth/getcustomerkeys"
        }
    };

    call(http, messageService, options: IRequestOption, log: string, error: string) {
        let url: string = options.url ? options.url : this.baseURL;
        if (this.endpoints.hasOwnProperty(options['cxfgroup'])) {
            url += this.endpoints[options.cxfgroup][options.endpoint];
        }

        return new HTTP(http, messageService, url, options.data, log, error);
    }
}

@Injectable()
export class RequestService {

    constructor(private http: HttpClient, private messageService: MessageService) { }

    post(request: IRequestBody) {
        let requestFactory = new RequestFactory();
        requestFactory.call(this.http, this.messageService, request.option, request.log, request.error);
    }

}
</code>```

I'm calling this "post" method using the following code. Here I want
  to set a promise once the request complete i want to show some
  message.

```<code>this.requestService.post({
  option: {
    url: '',
     cxfgroup: 'auth',
      endpoint: 'getcustomerkeys',
       data: {
         userid: 'user@domain.com'
       }
  },
  log: 'login initiated!',
  error: 'customerKeyError'
});
</code>```

答:
Sorry Libu, it's all more "simple" than your code. You don't need create class and class and class. Futhermore the best approach it's always return an Observable.Really there are no advantage to use promise instead of  of observable. If you return an observable you can "chain" (using switchMap), "group" (using fork), etc</p>

```<code>@Injectable()
export class RequestService {
    private baseURL = 'https://app.domain.com/cxf/';
    constructor(private http: HttpClient)

    post(request: IRequestBody) {
        let url: string = options.url ? options.url : this.baseURL;
        if (this.endpoints.hasOwnProperty(options['cxfgroup'])) {
            url += this.endpoints[options.cxfgroup][options.endpoint];
        }
        let requestFactory = new RequestFactory();
        this.http.post(url,this.messageService, request.option)
        .do(console.log(request.log))  //when the request sucesfully
                                       //show in console
        .catch(console.log(request.error)); //if fail, show in console the error
    }
}
</code>```

Body:
I created one service for handling all http request. It is working perfectly. But I want to know is there any fault in my approach and also want to know other good approaches like observable?

request.service.js

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
import { catchError, map, tap } from 'rxjs/operators';

import { MessageService } from './message.service';

const httpOptions = {
    headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' })
};

interface IRequestOption {
    url: string;
    cxfgroup: string;
    endpoint: string;
    data: object;
}

interface IRequestBody {
    option: IRequestOption;
    log: string;
    error: string;
}

class HTTP {

    private messageService: MessageService;

    constructor(http, messageService, url: string, body: object, log: string, error: string) {
        this.callHTTP(http, url, body, log, error);
        this.messageService = messageService;
    }

    callHTTP(http, url, body, log, error) {
        return http.post(url, body, httpOptions).toPromise()
            .then(this.extractData)
            .catch(this.handleErrorPromise);
    }

    private extractData(res: Response) {
        // let body = res.json();
        // return body['data'] || {};
        return res || {};
    }

    private handleErrorPromise(error: Response | any) {
        console.error(error.message || error);
        return Promise.reject(error.message || error);
    }
}

class RequestFactory {
    private baseURL = 'https://app.domain.com/cxf/';
    /**
     * CXF ENPOINTS
     */
    private endpoints: any = {
        "auth": {
            "getcustomerkeys": "auth/getcustomerkeys"
        }
    };

    call(http, messageService, options: IRequestOption, log: string, error: string) {
        let url: string = options.url ? options.url : this.baseURL;
        if (this.endpoints.hasOwnProperty(options['cxfgroup'])) {
            url += this.endpoints[options.cxfgroup][options.endpoint];
        }

        return new HTTP(http, messageService, url, options.data, log, error);
    }
}

@Injectable()
export class RequestService {

    constructor(private http: HttpClient, private messageService: MessageService) { }

    post(request: IRequestBody) {
        let requestFactory = new RequestFactory();
        requestFactory.call(this.http, this.messageService, request.option, request.log, request.error);
    }

}

I'm calling this "post" method using the following code. Here I want
  to set a promise once the request complete i want to show some
  message.

this.requestService.post({
  option: {
    url: '',
     cxfgroup: 'auth',
      endpoint: 'getcustomerkeys',
       data: {
         userid: 'user@domain.com'
       }
  },
  log: 'login initiated!',
  error: 'customerKeyError'
});

Body:
Sorry Libu, it's all more "simple" than your code. You don't need create class and class and class. Futhermore the best approach it's always return an Observable.Really there are no advantage to use promise instead of  of observable. If you return an observable you can "chain" (using switchMap), "group" (using fork), etc

@Injectable()
export class RequestService {
    private baseURL = 'https://app.domain.com/cxf/';
    constructor(private http: HttpClient)

    post(request: IRequestBody) {
        let url: string = options.url ? options.url : this.baseURL;
        if (this.endpoints.hasOwnProperty(options['cxfgroup'])) {
            url += this.endpoints[options.cxfgroup][options.endpoint];
        }
        let requestFactory = new RequestFactory();
        this.http.post(url,this.messageService, request.option)
        .do(console.log(request.log))  //when the request sucesfully
                                       //show in console
        .catch(console.log(request.error)); //if fail, show in console the error
    }
}


问:
Not able to load obj in  for ar.js
Not able to load obj file in following html file for ar.js despite giving the correct paths:

```<code><script src=”https://aframe.io/releases/0.6.1/aframe.min.js"></script>
<script src=”https://jeromeetienne.github.io/AR.js/aframe/build/aframe-ar.js"></script>

<body style=’margin : 0px; overflow: hidden;’>
  <a-scene embedded arjs=’sourceType: webcam;’>
      <a-marker preset=’hiro’>
        <!-- Adding an OBJ file to an AR Project-->
        <a-entity
            obj-model=”obj: url(https://rishavjayswal.github.io/augmented-reality/resources/couch.obj);
            mtl: url(https://rishavjayswal.github.io/augmented-reality/resources/couch.mtl)”>
        </a-entity>

      </a-marker>
  <a-entity camera>
  </a-entity>
  </a-scene>
</body>
</code>```

Getting

GET https://rishavjayswal.github.io/augmented-reality/%E2%80%9Dhttps://aframe.io/releases/0.6.1/aframe.min.js%22 net::ERR_ABORTED

after running. Tried with relative paths for obj and mtl file also:

/resources/couch.obj

Can open the link here: https://rishavjayswal.github.io/augmented-reality/

答:
Your model loads just fine. This is a working example in glitch: https://glitch.com/edit/#!/excellent-face?path=index.html:13:19

I see you are mixing types of quotes around your attribute values. Your HTML is not valid. Use straight double quotes: "

In your obj-model attribute you are using ” and in your arjs attribute you are using ’

Title: Not able to load obj in <a-frame> for ar.js

Body:
Not able to load obj file in following html file for ar.js despite giving the correct paths:

Getting

GET https://rishavjayswal.github.io/augmented-reality/%E2%80%9Dhttps://aframe.io/releases/0.6.1/aframe.min.js%22 net::ERR_ABORTED

after running. Tried with relative paths for obj and mtl file also:

/resources/couch.obj

Can open the link here: https://rishavjayswal.github.io/augmented-reality/


问:
SVG resources? Good forums, help sites, examples?
I am currently doing a SVG project for school and I was wondering if I could be given any good sites with some awesome SVG examples? I can't even find a forum where I can ask questions specific to SVG. </p>

<p>Any help would be appreciated. </p>

答:
As Erno says Inkscape and even Adobe Illustrator are good for drawing svg, I think there's app in the Chrome web store that you can use to draw svg in the browser as well.

There are plenty of examples out there:

http://svg-wow.org/ has some really good work.

Raphael is also worth a look as library to get cross-browser support.

And in terms of forums the svg forums there's a yahoo group called svg-developers.

Body:
I am currently doing a SVG project for school and I was wondering if I could be given any good sites with some awesome SVG examples? I can't even find a forum where I can ask questions specific to SVG.

Any help would be appreciated.


问:
Is there a way to override inline CSS for `overflow`?
If I want override inline css i must use !important or javascript.

But if I want to override, for example, inline width without important I can use max-width or min-width

Is there some way to override inline

```<code>  overflow:hidden
</code>```

答:
If you want to change inline css you should use js, you can override through !important tag but it has high priority so it may affect other css style...

So it's good to use js instead of !important tag.

Body:
If I want override inline css i must use !important or javascript.

But if I want to override, for example, inline width without important I can use max-width or min-width

Is there some way to override inline

  overflow:hidden

ContentLicense: CC BY-SA 4.0


问:
Attachment in Corda :
I tried uploading zip files using uploadAttachemnt method where I got a secureHash as output.
I tried to download the same attachment using the hash as input to openAttachmnet method I got a InputStream.
When I tried to read the contents of the inputStream using BuffeReader it is encrypted. I realised I had to unzip the file and read it so I got this package "import java.util.zip.ZipEntry" to read a zip file content
I am unsure whether I can read the zip file contents using InputStream.
How should I read the zip file contents using the InputStream? If not should I unzip and upload the file ?  </p>

```<code>fun main(args: Array<String>) :String {
    require(args.isNotEmpty()) { "Usage: uploadBlacklist <node address>" }
    args.forEach { arg ->
        val nodeAddress = parse(args[0])
        val rpcConnection = CordaRPCClient(nodeAddress).start("user1", "test")
        val proxy = rpcConnection.proxy

         val attachmentInputStream = File(args[1]).inputStream()
        val attachmentHash = proxy.uploadAttachment(attachmentInputStream)
        print("AtachmentHash"+attachmentHash)

        // Download the attachment
        val inputString = proxy.openAttachment(attachmentHash).bufferedReader().use { it.readText() }
        println("The contents are ")
        print(inputString)

        val file = File("OutputFile.txt")
        file.writeText(inputString)
        rpcConnection.notifyServerAndClose()

    }

    return("File downloaded successfully in the path")
}
</code>```

答:
I had many files inside the zip file. so I tried this code and it worked fine. Thanks for your input joel.</p>

```<code>// downloading the attachment
        val attachmentDownloadInputStream = proxy.openAttachment(attachmentHash)
        val attachmentJar = JarInputStream(attachmentDownloadInputStream)
        var contents =""

        //Reading the contents
        while(attachmentJar.nextJarEntry!=null){
            contents = contents + attachmentJar.bufferedReader().readLine()

        }
        println("The contents are $contents")
</code>```

Title: Attachment in Corda :

Body:
I tried uploading zip files using uploadAttachemnt method where I got a secureHash as output.
I tried to download the same attachment using the hash as input to openAttachmnet method I got a InputStream.
When I tried to read the contents of the inputStream using BuffeReader it is encrypted. I realised I had to unzip the file and read it so I got this package "import java.util.zip.ZipEntry" to read a zip file content
I am unsure whether I can read the zip file contents using InputStream.
How should I read the zip file contents using the InputStream? If not should I unzip and upload the file ?

fun main(args: Array<String>) :String {
    require(args.isNotEmpty()) { "Usage: uploadBlacklist <node address>" }
    args.forEach { arg ->
        val nodeAddress = parse(args[0])
        val rpcConnection = CordaRPCClient(nodeAddress).start("user1", "test")
        val proxy = rpcConnection.proxy

         val attachmentInputStream = File(args[1]).inputStream()
        val attachmentHash = proxy.uploadAttachment(attachmentInputStream)
        print("AtachmentHash"+attachmentHash)

        // Download the attachment
        val inputString = proxy.openAttachment(attachmentHash).bufferedReader().use { it.readText() }
        println("The contents are ")
        print(inputString)

        val file = File("OutputFile.txt")
        file.writeText(inputString)
        rpcConnection.notifyServerAndClose()

    }

    return("File downloaded successfully in the path")
}

Body:
I had many files inside the zip file. so I tried this code and it worked fine. Thanks for your input joel.

// downloading the attachment
        val attachmentDownloadInputStream = proxy.openAttachment(attachmentHash)
        val attachmentJar = JarInputStream(attachmentDownloadInputStream)
        var contents =""

        //Reading the contents
        while(attachmentJar.nextJarEntry!=null){
            contents = contents + attachmentJar.bufferedReader().readLine()

        }
        println("The contents are $contents")


问:
TFS plugin to use with PyCharm
I am looking for a free source code management TFS plugin to use with the PyCharm IDE. I've been looking around and cannot seem to get anything to work properly.</p>

答:
Please try TFS Integration.

Based on the description in the page it should be compatible with PyCharm

Compatible with: IntelliJ IDEA  PhpStorm  WebStorm  PyCharm
  RubyMine  AppCode  GoLand  Rider

Also this for your reference : Using TFS Integration

UPDATE:

It supports PyCharm Community Edition, refer to this link for details : https://plugins.jetbrains.com/plugin/4578-tfs-integration/update/12400.

That's the only plugin for PyCharm for now. The IntelliJ IDEA is required So, you can have a try for IntelliJ IDEA Community Edition to check if that works for you.

Title: TFS plugin to use with PyCharm


问:
Edit form that has ForeignKey to other model
I have a form that a user need to fill up, the model of that form as ForeignKey to another model (Question)

When I create a new form, it works as I expect.
When I try to do edit an existing record I am able to get the relevant data in the template but when I click on submit It fails with no error – when I debug it its failes on form is not valid and that the question is None.

```<code># form
class AnswerForm(forms.ModelForm):
    question = forms.ModelChoiceField(
        label=_(u'question'),
        widget=forms.HiddenInput(),
        queryset=Question.objects.all())
    description = forms.CharField(
        label=_(u'description'),
        widget=forms.Textarea(attrs={'class': 'form-control', 'rows': '4'}),
    max_length=2000,
    required = False)
link = forms.URLField(
    label=_(u'link'),
    max_length=1000,
    required = False)
price = forms.DecimalField(
    label=_(u'price'),
    widget=forms.TextInput(attrs={'class': 'form-control'}),
    #max_length=100,
    required = False)
currency = forms.ModelChoiceField(
    label=_(u'currency'),
    required=False,
    queryset=Currency_converter.objects.all())

class Meta:
    model = Answer
    exclude = ('user','link_domain_name',)
    fields = ['link','price', 'currency','description']

def clean(self):
    cleaned_data = super(AnswerForm, self).clean()
    if cleaned_data.get('link')==''  and cleaned_data.get('price')==None and
cleaned_data.get('description')=='' :
        raise forms.ValidationError(_("You must fill at least one field!"))
    if cleaned_data.get('link')=='' and cleaned_data.get('price')!=None :
        raise forms.ValidationError(_("Add link to the price you found!"))
    if cleaned_data.get('price')!=None and
cleaned_data.get('currency')==None :
        raise forms.ValidationError(_("set currency for the price you
set!"))
    return cleaned_data

        #view
    def answer(request,question_id ,answer_id):
        path_to_pic = filepath_link_as_pictures()
        question = get_object_or_404(Question, pk=question_id)
        if answer_id != '0':
            instance = get_object_or_404(Answer, pk=answer_id)
            if instance.user != request.user:
                return HttpResponseForbidden()
        else:
            instance = Answer()
            instance.question = question
        form = AnswerForm(request.POST or None, instance=instance)
        if request.POST :
           if form.is_valid():
               ....
#HTML
{% for field in form.visible_fields %}
 <div class="form-group">
{{ field.label_tag }}

{% if form.is_bound %}
  {% if field.errors %}
    {% render_field field class="form-control is-invalid" %}
    {% for error in field.errors %}
      <div class="invalid-feedback">
        {{ error }}
      </div>
    {% endfor %}
  {% else %}
    {% render_field field class="form-control is-valid" %}
  {% endif %}
{% else %}
  {% render_field field class="form-control" %}
{% endif %}

{% if field.help_text %}
  <small class="form-text text-muted">{{ field.help_text }}</small>
{% endif %}
 </div>
{% endfor %}
</code>```

It looks like I miss something as I get all the data in the template why don’t I get the question field as hidden filed in the template as well?

Thanks

答:
I found the problem
ModelChoiceField need to be  initial

```<code>initial = { 'question':question})
</code>```

secound thing you need to pass the answer.id as well and it was removed by mistake, so it created a new record instead of update existing one

```<code>{% url 'answer' question.id  form.instance.id|default_if_none:0 %}
</code>```

Body:
I have a form that a user need to fill up, the model of that form as ForeignKey to another model (Question)

When I create a new form, it works as I expect.
When I try to do edit an existing record I am able to get the relevant data in the template but when I click on submit It fails with no error – when I debug it its failes on form is not valid and that the question is None.

# form
class AnswerForm(forms.ModelForm):
    question = forms.ModelChoiceField(
        label=_(u'question'),
        widget=forms.HiddenInput(),
        queryset=Question.objects.all())
    description = forms.CharField(
        label=_(u'description'),
        widget=forms.Textarea(attrs={'class': 'form-control', 'rows': '4'}),
    max_length=2000,
    required = False)
link = forms.URLField(
    label=_(u'link'),
    max_length=1000,
    required = False)
price = forms.DecimalField(
    label=_(u'price'),
    widget=forms.TextInput(attrs={'class': 'form-control'}),
    #max_length=100,
    required = False)
currency = forms.ModelChoiceField(
    label=_(u'currency'),
    required=False,
    queryset=Currency_converter.objects.all())

class Meta:
    model = Answer
    exclude = ('user','link_domain_name',)
    fields = ['link','price', 'currency','description']

def clean(self):
    cleaned_data = super(AnswerForm, self).clean()
    if cleaned_data.get('link')==''  and cleaned_data.get('price')==None and
cleaned_data.get('description')=='' :
        raise forms.ValidationError(_("You must fill at least one field!"))
    if cleaned_data.get('link')=='' and cleaned_data.get('price')!=None :
        raise forms.ValidationError(_("Add link to the price you found!"))
    if cleaned_data.get('price')!=None and
cleaned_data.get('currency')==None :
        raise forms.ValidationError(_("set currency for the price you
set!"))
    return cleaned_data

        #view
    def answer(request,question_id ,answer_id):
        path_to_pic = filepath_link_as_pictures()
        question = get_object_or_404(Question, pk=question_id)
        if answer_id != '0':
            instance = get_object_or_404(Answer, pk=answer_id)
            if instance.user != request.user:
                return HttpResponseForbidden()
        else:
            instance = Answer()
            instance.question = question
        form = AnswerForm(request.POST or None, instance=instance)
        if request.POST :
           if form.is_valid():
               ....
#HTML
{% for field in form.visible_fields %}

{{ field.label_tag }}

{% if form.is_bound %}
  {% if field.errors %}
    {% render_field field class="form-control is-invalid" %}
    {% for error in field.errors %}

        {{ error }}

    {% endfor %}
  {% else %}
    {% render_field field class="form-control is-valid" %}
  {% endif %}
{% else %}
  {% render_field field class="form-control" %}
{% endif %}

{% if field.help_text %}
  {{ field.help_text }}
{% endif %}

{% endfor %}

It looks like I miss something as I get all the data in the template why don’t I get the question field as hidden filed in the template as well?

Thanks

Body:
I found the problem
ModelChoiceField need to be  initial

initial = { 'question':question})

secound thing you need to pass the answer.id as well and it was removed by mistake, so it created a new record instead of update existing one

{% url 'answer' question.id  form.instance.id|default_if_none:0 %}


问:
Restricting std::sort to random access iterators
I was just wondering, since you can only pass random access iterators to std::sort anyway, why not enforce that restriction by defining it only for random access iterators in the first place?

```<code>#include <iterator>
#include <type_traits>

template <typename ForwardIterator>
typename std::enable_if<
    std::is_same<
        typename std::iterator_traits<ForwardIterator>::iterator_category,
        std::random_access_iterator_tag>::value,
    void>
::type sort(ForwardIterator begin, ForwardIterator end)
{
    // ...
}
</code>```

I find a single line error message a lot easier to read than pages and pages of error messages resulting from type errors far down in the implementation.

You could do the same with other algorithms. The standard C++ core language has always been expressive enough for that task, right? So, any particular reason why this was not done?

答:
My guess is that SFINAE was invented (or discovered) after the standard library implementations had reached a certain maturity. After that, changes to the core library had to be very justified in order to prevent the introduction of regressions and I guess that mere cosmetics are somewhat hard to justify.

That said, the GCC for example already does have a lot of diagnostics for template-related error messages, e.g. macros that perform a kind of concept checking. For example, the GCC-libstdc++ has the following:

```<code>// concept requirements
__glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept<
   _RandomAccessIterator>)
__glibcxx_function_requires(_LessThanComparableConcept<_ValueType>)
__glibcxx_requires_valid_range(__first, __last);
</code>```

Body:
I was just wondering, since you can only pass random access iterators to std::sort anyway, why not enforce that restriction by defining it only for random access iterators in the first place?

#include <iterator>
#include <type_traits>

template <typename ForwardIterator>
typename std::enable_if<
    std::is_same<
        typename std::iterator_traits<ForwardIterator>::iterator_category,
        std::random_access_iterator_tag>::value,
    void>
::type sort(ForwardIterator begin, ForwardIterator end)
{
    // ...
}

I find a single line error message a lot easier to read than pages and pages of error messages resulting from type errors far down in the implementation.

You could do the same with other algorithms. The standard C++ core language has always been expressive enough for that task, right? So, any particular reason why this was not done?

Body:
My guess is that SFINAE was invented (or discovered) after the standard library implementations had reached a certain maturity. After that, changes to the core library had to be very justified in order to prevent the introduction of regressions and I guess that mere cosmetics are somewhat hard to justify.

That said, the GCC for example already does have a lot of diagnostics for template-related error messages, e.g. macros that perform a kind of concept checking. For example, the GCC-libstdc++ has the following:

// concept requirements
__glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept<
   _RandomAccessIterator>)
__glibcxx_function_requires(_LessThanComparableConcept<_ValueType>)
__glibcxx_requires_valid_range(__first, __last);


问:
How to upload images to Digital Ocean Spaces using AWS SDK for Android?
Since Digital Ocean Spaces API is compatible with AWS SDK, how to upload images to Digital Ocean Spaces programmatically using AWS SDK for Android?</p>

答:
Add sdk to your build.gradle in your android studio project:

```<code>compile 'com.amazonaws:aws-android-sdk-core:2.6.9'
compile 'com.amazonaws:aws-android-sdk-s3:2.6.9'
compile 'com.amazonaws:aws-android-sdk-ddb:2.6.9'
</code>```

Add the following service in your manifest file:

```<code><service android:name="com.amazonaws.mobileconnectors.s3.transferutility.TransferService"
    android:enabled="true" />
</code>```

Basic steps:

1.You first create AWS Credentials for accessing S3 using BasicAWSCredentails class

2.Pass AWS Credentials to AmazonS3 instance

3.You then pass AmazonS3 object to TransferUtility class

4.You assign your BucketName, FileName  and FileObject(which is to be transefer) to TransferObserver class

5.Finally you track your transfer details using setTransferListener of TransferObserver class

Code (tested and worked):

```<code>    AmazonS3Client s3;
    BasicAWSCredentials credentials;
    TransferUtility transferUtility;
    final TransferObserver observer;
    String key = "YOUR_SPACES_KEY";
    String secret = "YOUR_SPACES_SECRET_KEY";

    credentials = new BasicAWSCredentials(key, secret);
    s3 = new AmazonS3Client(credentials);
    s3.setEndpoint("https://BUCKET_NAME.nyc3.digitaloceanspaces.com/DIRECTORY_IF_NEEDED");

    transferUtility = new TransferUtility(s3, activity);
    CannedAccessControlList filePermission = CannedAccessControlList.PublicRead;

    observer = transferUtility.upload(
            "", //empty bucket name, included in endpoint
            "FILE_NAME.PNG",
            new File(), //a File object that you want to upload
            filePermission
    );

    observer.setTransferListener(new TransferListener() {
        @Override
        public void onStateChanged(int id, TransferState state) {
            if (state.COMPLETED.equals(observer.getState())) {
                Toast.makeText(activity, "Space upload completed !!", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {
        }

        @Override
        public void onError(int id, Exception ex) {
            Toast.makeText(activity, "Space upload error: " + ex.getMessage(), Toast.LENGTH_SHORT).show();
        }
    });
</code>```

Reference from: http://yasirameen.com/2016/10/uploading-file-to-amazon-s3/

Body:
Add sdk to your build.gradle in your android studio project:

compile 'com.amazonaws:aws-android-sdk-core:2.6.9'
compile 'com.amazonaws:aws-android-sdk-s3:2.6.9'
compile 'com.amazonaws:aws-android-sdk-ddb:2.6.9'

Add the following service in your manifest file:

<service android:name="com.amazonaws.mobileconnectors.s3.transferutility.TransferService"
    android:enabled="true" />

Basic steps:

1.You first create AWS Credentials for accessing S3 using BasicAWSCredentails class

2.Pass AWS Credentials to AmazonS3 instance

3.You then pass AmazonS3 object to TransferUtility class

4.You assign your BucketName, FileName  and FileObject(which is to be transefer) to TransferObserver class

5.Finally you track your transfer details using setTransferListener of TransferObserver class

Code (tested and worked):

    AmazonS3Client s3;
    BasicAWSCredentials credentials;
    TransferUtility transferUtility;
    final TransferObserver observer;
    String key = "YOUR_SPACES_KEY";
    String secret = "YOUR_SPACES_SECRET_KEY";

    credentials = new BasicAWSCredentials(key, secret);
    s3 = new AmazonS3Client(credentials);
    s3.setEndpoint("https://BUCKET_NAME.nyc3.digitaloceanspaces.com/DIRECTORY_IF_NEEDED");

    transferUtility = new TransferUtility(s3, activity);
    CannedAccessControlList filePermission = CannedAccessControlList.PublicRead;

    observer = transferUtility.upload(
            "", //empty bucket name, included in endpoint
            "FILE_NAME.PNG",
            new File(), //a File object that you want to upload
            filePermission
    );

    observer.setTransferListener(new TransferListener() {
        @Override
        public void onStateChanged(int id, TransferState state) {
            if (state.COMPLETED.equals(observer.getState())) {
                Toast.makeText(activity, "Space upload completed !!", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {
        }

        @Override
        public void onError(int id, Exception ex) {
            Toast.makeText(activity, "Space upload error: " + ex.getMessage(), Toast.LENGTH_SHORT).show();
        }
    });

Reference from: http://yasirameen.com/2016/10/uploading-file-to-amazon-s3/


问:
What is the difference between CoroutineContext and Job in kotlinx.coroutines?
In kotlinx.coroutines library all coroutine builders like launch, async, etc take CoroutineContext parameter but also have an additional parent parameter with a type of Job. What is the difference between CoroutineContext and Job?

答:
The Job represents a coroutine or some kind of an aggregate task that is being performed. A Job is a CoroutineContext.Element, which means that it can be stored in the coroutine context. The CoroutineContext is a collection of different coroutine context elements, with job being just one such element.

In fact, coroutine context is more like a map, as you can use coroutine element keys to retrieve elements from it. For example, if you have a value ctx of type CoroutineContext, then you can retrieve the job from it with ctx[Job] expression. Further details can be found in the corresponding section of coroutines design document and the documentation for CoroutineContext.

When a new coroutine is started, the full context can be specified. If this context contains a job, then the corresponding job becomes a parent for the new coroutine.

The parent parameter to coroutine builders like launch is just a convenience to make parent job specification more explicit. As documentation for launch highlights here that the explicitly specified parent job takes precedence over the job that was specified in the context. The actual example on how it can be used is given in this section of the guide.


问:
rails HABTM to has many through
```<code>class QuestionSet
  has_and_belongs_to_many :questions,
                      class_name: 'Exam',
                      join_table: 'question_question_sets',
                      foreign_key: 'question_set_id',
                      association_foreign_key: 'question_id'

end

class Question
  has_and_belongs_to_many :question_sets,
                      class_name: 'Exam',
                      join_table: 'question_question_sets',
                      foreign_key: 'question_id',
                      association_foreign_key: 'question_set_id'

end
</code>```

The above models are inherited from the base model Exam(using rails STI) and the join table contains two fields: question_id and question_set_id. Now I need to convert this association into has_many through.

I have tried as follows:

```<code>class QuestionQuestionSet
  has_many :questions
  has_many :question_sets
end

class Question
  has_many :question_question_sets, foreign_key: :question_id
  has_many :question_sets, through: :question_question_sets
end

class QuestionSet
  has_many :question_question_sets, foreign_key: :question_set_id
  has_many :questions, through: :question_question_sets
end
</code>```

答:
Even after editing your models, it's necessary to create a new join table since the previous one (created by habtm) doesn't have and "id" column.
As a reference you can follow the steps indicated in http://www.chrisrolle.com/en/blog/migration-path-from-habtm-to-has_many-through</p>

Title: rails HABTM to has many through

Body:
class QuestionSet
  has_and_belongs_to_many :questions,
                      class_name: 'Exam',
                      join_table: 'question_question_sets',
                      foreign_key: 'question_set_id',
                      association_foreign_key: 'question_id'

end

class Question
  has_and_belongs_to_many :question_sets,
                      class_name: 'Exam',
                      join_table: 'question_question_sets',
                      foreign_key: 'question_id',
                      association_foreign_key: 'question_set_id'

end

The above models are inherited from the base model Exam(using rails STI) and the join table contains two fields: question_id and question_set_id. Now I need to convert this association into has_many through.

I have tried as follows:

class QuestionQuestionSet
  has_many :questions
  has_many :question_sets
end

class Question
  has_many :question_question_sets, foreign_key: :question_id
  has_many :question_sets, through: :question_question_sets
end

class QuestionSet
  has_many :question_question_sets, foreign_key: :question_set_id
  has_many :questions, through: :question_question_sets
end


问:
JSON field set to null vs field not there
Is there a way, in golang, to see if I can differentiate between a json field being set to null vs a json field not being there when unmarshalled into a struct? Because both set the value in the struct to be nil, but I need to know if the field was there to begin with and to see if someone set it to null.

```<code>{
  "somefield1":"somevalue1",
  "somefield2":null
}
</code>```

VS

```<code>{
  "somefield1":"somevalue1",
}
</code>```

Both jsons will be nil when unmarshalled into a struct.
Any useful resources will be very appreciated!

答:
By using github.com/golang/protobuf/ptypes/struct and jsonpb github.com/golang/protobuf/jsonpb, you can do like this:

```<code>func TestFunTest(t *testing.T) {
    p := &pb.KnownTypes{}
    e := UnmarshalString(`{"val":null}`, p)
    fmt.Println(e, p)
    p = &pb.KnownTypes{}
    e = UnmarshalString(`{"val":1}`, p)
    fmt.Println(e, p)
    p = &pb.KnownTypes{}
    e = UnmarshalString(`{"val":"string"}`, p)
    fmt.Println(e, p)
    p = &pb.KnownTypes{}
    e = UnmarshalString(`{}`, p)
    fmt.Println(e, p)
}
</code>```

Output:

```<code>[ `go test -test.run="^TestFunTest$"` | done: 1.275431416s ]
    <nil> val:<null_value:NULL_VALUE >
    <nil> val:<number_value:1 >
    <nil> val:<string_value:"string" >
    <nil>
    PASS
</code>```

Body:
Is there a way, in golang, to see if I can differentiate between a json field being set to null vs a json field not being there when unmarshalled into a struct? Because both set the value in the struct to be nil, but I need to know if the field was there to begin with and to see if someone set it to null.

{
  "somefield1":"somevalue1",
  "somefield2":null
}

VS

{
  "somefield1":"somevalue1",
}

Both jsons will be nil when unmarshalled into a struct.
Any useful resources will be very appreciated!

Body:
By using github.com/golang/protobuf/ptypes/struct and jsonpb github.com/golang/protobuf/jsonpb, you can do like this:

func TestFunTest(t *testing.T) {
    p := &pb.KnownTypes{}
    e := UnmarshalString(`{"val":null}`, p)
    fmt.Println(e, p)
    p = &pb.KnownTypes{}
    e = UnmarshalString(`{"val":1}`, p)
    fmt.Println(e, p)
    p = &pb.KnownTypes{}
    e = UnmarshalString(`{"val":"string"}`, p)
    fmt.Println(e, p)
    p = &pb.KnownTypes{}
    e = UnmarshalString(`{}`, p)
    fmt.Println(e, p)
}

Output:

[ `go test -test.run="^TestFunTest$"` | done: 1.275431416s ]
    <nil> val:<null_value:NULL_VALUE >
    <nil> val:<number_value:1 >
    <nil> val:<string_value:"string" >
    <nil>
    PASS


问:
How to break a line of chained methods in Python?
I have a line of the following code (don't blame for naming conventions, they are not mine):

```<code>subkeyword = Session.query(
    Subkeyword.subkeyword_id, Subkeyword.subkeyword_word
).filter_by(
    subkeyword_company_id=self.e_company_id
).filter_by(
    subkeyword_word=subkeyword_word
).filter_by(
    subkeyword_active=True
).one()
</code>```

I don't like how it looks like (not too readable) but I don't have any better idea to limit lines to 79 characters in this situation. Is there a better way of breaking it (preferably without backslashes)?

答:
According to Python Language Reference

You can use a backslash.

Or simply break it. If a bracket is not paired, python will not treat that as a line. And under such circumstance, the indentation of following lines doesn't matter.

Body:
I have a line of the following code (don't blame for naming conventions, they are not mine):

subkeyword = Session.query(
    Subkeyword.subkeyword_id, Subkeyword.subkeyword_word
).filter_by(
    subkeyword_company_id=self.e_company_id
).filter_by(
    subkeyword_word=subkeyword_word
).filter_by(
    subkeyword_active=True
).one()

I don't like how it looks like (not too readable) but I don't have any better idea to limit lines to 79 characters in this situation. Is there a better way of breaking it (preferably without backslashes)?


问:
Angular showing issue ... not getting proper
I am new to angular JS. Please take a look. This is my app.js file

```<code>angular.module("CrudDemoApp",["CrudDemoApp.controllers","ngRoute"]);
</code>```

this is my controllers.js file

```<code>angular.module("CrudDemoApp.controllers", []);
controllers("MainController", function ($scope)
{
    $scope.message = "Main Controller";
});
</code>```

this is the my body part

```<code><body ng-app="CrudDemoApp">
<div ng-controller="MainController">
{{message}}
</div>
</body>
</code>```

firstly it is saying "Uncaught ReferenceError: controllers is not defined
at then it is saying
Error: [ng:areq] http://errors.angularjs.org/1.5.6/ng/areq?p0=MainController&p1=not%20a%20function%2C%20got%20undefined

答:
```<code>angular.module("CrudDemoApp.controllers", []) //remove semicolon here adding the controller to this module
  .controller("MainController", function ($scope) // dot before controller, remove "s"
  {
      $scope.message = "Main Controller";
  });
</code>```

notice the dot and lack of pluralization on controller

You should have probably seen some other errors before the ones you mentioned always work from the first one down sometimes 1 error causes the next.

Body:
I am new to angular JS. Please take a look. This is my app.js file

angular.module("CrudDemoApp",["CrudDemoApp.controllers","ngRoute"]);

this is my controllers.js file

angular.module("CrudDemoApp.controllers", []);
controllers("MainController", function ($scope)
{
    $scope.message = "Main Controller";
});

this is the my body part

{{message}}

firstly it is saying "Uncaught ReferenceError: controllers is not defined
at then it is saying
Error: [ng:areq] http://errors.angularjs.org/1.5.6/ng/areq?p0=MainController&p1=not%20a%20function%2C%20got%20undefined

Body:
angular.module("CrudDemoApp.controllers", []) //remove semicolon here adding the controller to this module
  .controller("MainController", function ($scope) // dot before controller, remove "s"
  {
      $scope.message = "Main Controller";
  });

notice the dot and lack of pluralization on controller

You should have probably seen some other errors before the ones you mentioned always work from the first one down sometimes 1 error causes the next.


问:
django authentication package: 'auth' not registered as a namespace
I'm trying to build a simple website with user authentication based on this tutorial, but I'm running into the above error. As per the instructions I set a url as folllows:

```<code>url('^accounts/', include('django.contrib.auth.urls'))
</code>```

I got this error in response: 'auth' is not a registered namespace So I tried to register a namespace as the tutorial repo shows:

```<code>url('^accounts/', include('django.contrib.auth.urls', namespace="auth")),
</code>```

then I get the error :
    Specifying a namespace in include() without providing an app_name

I realised that the tutorial is using django 1.8.3, but I'm on 2.0. The issue is resolved when I switch to the same django version in virtualenv, but I'm now having to a change a number of other things across the project to keep it from breaking. Any way to fix without require django 1.8? Thanks.

答:
If this is django 2+, you need to put app_name = 'x' in your application's url.py file. For example, if in /project/project/urls.py you have:

```<code>path('', include('app.urls', namespace='app'))
</code>```

Then in the corresponding url file (in /project/app/urls.py) you need to specify the app_name parameter with:

```<code>app_name = 'app'  #the weird code
urlpatterns = [
    path('', views.index, name = 'index'), #this can be anything
]
</code>```

Body:
I'm trying to build a simple website with user authentication based on this tutorial, but I'm running into the above error. As per the instructions I set a url as folllows:

url('^accounts/', include('django.contrib.auth.urls'))

I got this error in response: 'auth' is not a registered namespace So I tried to register a namespace as the tutorial repo shows:

url('^accounts/', include('django.contrib.auth.urls', namespace="auth")),

then I get the error :
    Specifying a namespace in include() without providing an app_name

I realised that the tutorial is using django 1.8.3, but I'm on 2.0. The issue is resolved when I switch to the same django version in virtualenv, but I'm now having to a change a number of other things across the project to keep it from breaking. Any way to fix without require django 1.8? Thanks.

Body:
If this is django 2+, you need to put app_name = 'x' in your application's url.py file. For example, if in /project/project/urls.py you have:

path('', include('app.urls', namespace='app'))

Then in the corresponding url file (in /project/app/urls.py) you need to specify the app_name parameter with:

app_name = 'app'  #the weird code
urlpatterns = [
    path('', views.index, name = 'index'), #this can be anything
]


问:
Delphi simple xml parse
I need to parse out some values from xml file. The problem is - that I must do it with Delphi =(.
the file is quite simple

```<code><?xml version="1.0"?>
<Items version="1.0">
  <Item BackupFileName="d:\data.bak">
    <Rating Rate="TOP"/>
  </Item>
  <Item BackupFileName="d:\data2.bak">
    <Rating Rate="OTHER"/>
  </Item>
  ....
</Items>
</code>```

And I just need an array of strings with this filepaths {"d:\data.bak", "d:\data2.bak", ... }
 I have googled a little and found a solution (as I thought) like

```<code> url := 'D:\Backups.xml';
  xml := CreateOleObject('Microsoft.XMLDOM') as IXMLDOMDocument;
  xml.async := False;
  xml.load(url); // or use loadXML to load XML document using a supplied string
  if xml.parseError.errorCode <> 0 then
    raise Exception.Create('XML Load error:' + xml.parseError.reason);

  nodes_row := xml.selectNodes('/Items');
  for i := 0 to nodes_row.length - 1 do
  begin
    node := nodes_row.item[i];
    result := node.selectSingleNode('Item').text;
end;
</code>```

But result seems to be always void. Could you please provide or refer an easy solution for this?

答: Use the IXMLNode.Attributes property Or the IXMLNode.AttributeNodes property, since your nodes don't contain text, you actually looking for attribute text.

Title: Delphi simple xml parse

Body:
I need to parse out some values from xml file. The problem is - that I must do it with Delphi =(.
the file is quite simple

<?xml version="1.0"?>
<Items version="1.0">
  <Item BackupFileName="d:\data.bak">
    <Rating Rate="TOP"/>
  </Item>
  <Item BackupFileName="d:\data2.bak">
    <Rating Rate="OTHER"/>
  </Item>
  ....
</Items>

And I just need an array of strings with this filepaths {"d:\data.bak", "d:\data2.bak", ... }
 I have googled a little and found a solution (as I thought) like

 url := 'D:\Backups.xml';
  xml := CreateOleObject('Microsoft.XMLDOM') as IXMLDOMDocument;
  xml.async := False;
  xml.load(url); // or use loadXML to load XML document using a supplied string
  if xml.parseError.errorCode <> 0 then
    raise Exception.Create('XML Load error:' + xml.parseError.reason);

  nodes_row := xml.selectNodes('/Items');
  for i := 0 to nodes_row.length - 1 do
  begin
    node := nodes_row.item[i];
    result := node.selectSingleNode('Item').text;
end;

But result seems to be always void. Could you please provide or refer an easy solution for this?


问:
Using jQuery, window.resize Event is not triggered?
GOAL: dynamically change height of each division element so that opposing elements in adjacent columns align horizontally -- like UL LI LI, but without the actual list.

If the window is super wide, each item may only have 1 line; but with window shrinkage, each item may have a unique line count; e.g.

```<code>item 1      item 2
  1 line      2 lines

item 3       item 4
  3 lines      1 line
</code>```

My desired result is to adjust all items to 3 lines tall via

```<code>$(window).on('resize', function() { ...});
</code>```

However, this window.resize Event is not triggered?

WHY?

HTML:

```<code><div class="parent">
    <div class="column extraPaddingOnRight">
<a href="links/headstone.pdf">Nancy at Arlington National Cemetery</a><p>
    </div>
</div>
<!-- other DIV links follow -->
</code>```

The CSS:

```<code>.extraPaddingOnRight {
    padding-right: 1.5em;
}

.column {
    float: left;
    /* Theoretically 50%, but less because of extraPaddingOnRight */
    width: 40%;
}
</code>```

JS:

```<code>$(document).ready(function() {

    function resizer() {
        var $maxItemHeight = 0, $thisItemHeight;

        $('div.column a').each(function() {
            $thisItemHeight = $(this).height();
            if ($thisItemHeight > $maxItemHeight)
                $maxItemHeight = $thisItemHeight;
        });

        $('div.column a').each(function() {
            $(this).css( {
                height: $maxItemHeight + 'px';
            });
        });
    }

    $(window).on('resize', function() {
    /*
        alert('ok');   // not triggered?
    */
        resizer;
    });
});
</code>```

答:
It seems you have a simple syntax error at the line

```<code>height: $maxItemHeight + 'px';
</code>```

remove the ;, that is not allowed in an object definition and the error should be visible in the browser console when loading the page.

Also to call your resizer function use resizer(); or simply $(window).on('resize', resizer);

Complete working example, you may need to change the path to your jQuery script.

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Test</title>
    <script src="jquery.js"></script>
    <script>
        $(document).ready(function() {

    function resizer() {
        var $maxItemHeight = 0, $thisItemHeight;

        $('div.column a').each(function() {
            $thisItemHeight = $(this).height();
            if ($thisItemHeight > $maxItemHeight)
                $maxItemHeight = $thisItemHeight;
        });

        $('div.column a').each(function() {
            $(this).css( {
                height: $maxItemHeight + 'px'
            });
        });
    }

    $(window).on('resize', function() {

        alert('ok');   // not triggered?

        // resizer;
    });
});
    </script>
</head>
<body>
<div id="testid">foo</div>
<button id="btnTest">Click me</button>
</body>
</html>
</code>```

Body:
GOAL: dynamically change height of each division element so that opposing elements in adjacent columns align horizontally -- like UL LI LI, but without the actual list.

If the window is super wide, each item may only have 1 line; but with window shrinkage, each item may have a unique line count; e.g.

item 1      item 2
  1 line      2 lines

item 3       item 4
  3 lines      1 line

My desired result is to adjust all items to 3 lines tall via

$(window).on('resize', function() { ...});

However, this window.resize Event is not triggered?

WHY?

HTML:

Nancy at Arlington National Cemetery

The CSS:

.extraPaddingOnRight {
    padding-right: 1.5em;
}

.column {
    float: left;
    /* Theoretically 50%, but less because of extraPaddingOnRight */
    width: 40%;
}

JS:

$(document).ready(function() {

    function resizer() {
        var $maxItemHeight = 0, $thisItemHeight;

        $('div.column a').each(function() {
            $thisItemHeight = $(this).height();
            if ($thisItemHeight > $maxItemHeight)
                $maxItemHeight = $thisItemHeight;
        });

        $('div.column a').each(function() {
            $(this).css( {
                height: $maxItemHeight + 'px';
            });
        });
    }

    $(window).on('resize', function() {
    /*
        alert('ok');   // not triggered?
    */
        resizer;
    });
});

Body:
It seems you have a simple syntax error at the line

height: $maxItemHeight + 'px';

remove the ;, that is not allowed in an object definition and the error should be visible in the browser console when loading the page.

Also to call your resizer function use resizer(); or simply $(window).on('resize', resizer);

Complete working example, you may need to change the path to your jQuery script.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Test</title>
    <script src="jquery.js"></script>
    <script>
        $(document).ready(function() {

    function resizer() {
        var $maxItemHeight = 0, $thisItemHeight;

        $('div.column a').each(function() {
            $thisItemHeight = $(this).height();
            if ($thisItemHeight > $maxItemHeight)
                $maxItemHeight = $thisItemHeight;
        });

        $('div.column a').each(function() {
            $(this).css( {
                height: $maxItemHeight + 'px'
            });
        });
    }

    $(window).on('resize', function() {

        alert('ok');   // not triggered?

        // resizer;
    });
});
    </script>
</head>
<body>
<div id="testid">foo</div>
<button id="btnTest">Click me</button>
</body>
</html>


问:
Share instance inside local project with different modules
My project strucutred like following

```<code>myproj
   src
      server
         main.go
      helpres
          helper1.go
          helpr2.go
       utils
          utils1.go
          utils2.go
</code>```

This is the code in the main.go function

```<code>import “myproj/utils”
import “myproj/helpers”

var log obj    *obj

func init() {
    log = initLog()
    util.passLog(log)
    helper.passLog(log)
    //And then helper and util can use it ...is it the right way to do it ?
}

func main(){

    log.write()

}
</code>```

Now I was able to use obj1 inside the server -> main.go,
but I want to use the same instance also in helper1.go and utils2.go
instead create the new one on each module,(later on I call to some functiona from helper and util inside the server->main.go)
How should I do it in golfing?

答:
Sharing objects between packages is not recommended because it will very likely get messy when things goes wrong. Debugging and finding out where obj was called from or mutated will become difficult. Instead, try to pass the obj as a parameter to helper1 and utils2.

If you really really do want to share the object, change the name to start with a capital letter, Obj. This way the variable is exported from your package and can be used from elsewhere. Note that this will expose Obj to everyone who wants to grab it and (mis)use it.

Edit:
Pass the obj to a function in helper:

```<code>helper.doSomethingHelpfulWith(obj)
</code>```

Body:
My project strucutred like following

myproj
   src
      server
         main.go
      helpres
          helper1.go
          helpr2.go
       utils
          utils1.go
          utils2.go

This is the code in the main.go function

import “myproj/utils”
import “myproj/helpers”

var log obj    *obj

func init() {
    log = initLog()
    util.passLog(log)
    helper.passLog(log)
    //And then helper and util can use it ...is it the right way to do it ?
}

func main(){

    log.write()

}

Now I was able to use obj1 inside the server -> main.go,
but I want to use the same instance also in helper1.go and utils2.go
instead create the new one on each module,(later on I call to some functiona from helper and util inside the server->main.go)
How should I do it in golfing?

Body:
Sharing objects between packages is not recommended because it will very likely get messy when things goes wrong. Debugging and finding out where obj was called from or mutated will become difficult. Instead, try to pass the obj as a parameter to helper1 and utils2.

If you really really do want to share the object, change the name to start with a capital letter, Obj. This way the variable is exported from your package and can be used from elsewhere. Note that this will expose Obj to everyone who wants to grab it and (mis)use it.

Edit:
Pass the obj to a function in helper:

helper.doSomethingHelpfulWith(obj)


问:
merging my local branch with remote master
I am new to git. I am working on a codebase with a team.
The status of my remote repository is:

```<code>git remote show origin                                # show the status
Remote branches:
....
                     master                             tracked
                     branch_to_be_merged                 tracked
...
Local branches configured for git pull:
master                                                 merges with remote master
branch_to_be_merged                                      merges with remote branch_to_be_merged

Local refs configured for git push:
master                                                 pushes to master
branch_to_be_merged                                       pushes to  branch_to_be_merged
</code>```

I have been working on a feature  on branch_to_be_merged, while master was actively developed.
Now I need to make my feature available to the public, and I would be merging using the following series of git commands.

Is the following correct?

```<code>git fetch origin                #make sure I am updated with latest remote changes
git checkout -b branch_to_be_merged   # the currently checked out branch is the one of interest
git branch                      # check I am on the branch I would like to merge later (it should now show *branch_to_be_merged)
git pull origin master           # apply the latest remote changes to my local branch_to_be_merged [I EXPECT CONFLICTS HERE]
git push branch_to_be_merged     # push the changes to remote
git checkout -b master           # the currently checked out branch is master
git branch                      # check I am on the branch I would like to merge later (it should now show *master)
git pull origin master           # apply the latest remote changes to my local master
git merge branch_to_be_merged    # merge  branch_to_be_merged to local master
git push master                 # publish the updates to master
</code>```

答: You do not need to use the -b switch when checking out master, as the branch already exists</p>

Body:
I am new to git. I am working on a codebase with a team.
The status of my remote repository is:

git remote show origin                                # show the status
Remote branches:
....
                     master                             tracked
                     branch_to_be_merged                 tracked
...
Local branches configured for git pull:
master                                                 merges with remote master
branch_to_be_merged                                      merges with remote branch_to_be_merged

Local refs configured for git push:
master                                                 pushes to master
branch_to_be_merged                                       pushes to  branch_to_be_merged

I have been working on a feature  on branch_to_be_merged, while master was actively developed.
Now I need to make my feature available to the public, and I would be merging using the following series of git commands.

Is the following correct?

git fetch origin                #make sure I am updated with latest remote changes
git checkout -b branch_to_be_merged   # the currently checked out branch is the one of interest
git branch                      # check I am on the branch I would like to merge later (it should now show *branch_to_be_merged)
git pull origin master           # apply the latest remote changes to my local branch_to_be_merged [I EXPECT CONFLICTS HERE]
git push branch_to_be_merged     # push the changes to remote
git checkout -b master           # the currently checked out branch is master
git branch                      # check I am on the branch I would like to merge later (it should now show *master)
git pull origin master           # apply the latest remote changes to my local master
git merge branch_to_be_merged    # merge  branch_to_be_merged to local master
git push master                 # publish the updates to master


问:
What's Is the Best File Format for Configuration Files
I am creating a framework in PHP and need to have a few configuration files. Some of these files will unavoidably have a large number of entries.

What format would be the best for these config files?

Here is my quantification of best:

Easily parsed by PHP. It would be nice if I didn't have to write any parsing code but this is not a deal breaker.

Remains easily read by humans even when there are a large amount of entries

Is a widely used standard, no custom formats

Succinctness is appreciated

I started out using XML, but quickly gave up for obvious reasons. I've thought of JSON and YAML but wanted to see what else is out there.

答:
Why don´t you use a PHP file for the configuration?

The benefits are clear:

possible errors will get caught automatically

no need to use/create a custom parser

it´s widely understood by PHP programmers

you can have some custom logic, for example using custom configurations for development, others for production, etc

Other frameworks like Django and rails use a config file which is a script.

OwnerDisplayName: macinjosh

LastEditorDisplayName: InSciTek Jeff

OwnerDisplayName: Tiago