问:
Smooth grabbing
I've made a simple grabbing demo page. It doesn't have any easing/acceleration. I would like to do the same easing/acceleration as on kulesh.info (Flash website) using JavaScript. How can I do that?

Any examples of smooth grabbing (scrolling, dragging) in JavaScript would be helpful as well as a language agnostic algorithm.

答:
You can get the flash look by using an easing equation sometimes referred to as zeno's paradox.

```<code>position += (destination - position) / damping
</code>```

I modified your jsFiddle to make use of it: Have a look

If you'd like me to give a more detailed description of zeno's paradox, let me know and I'll post one here with an image or two.

Title: Smooth grabbing

Body:
You can get the flash look by using an easing equation sometimes referred to as zeno's paradox.

position += (destination - position) / damping

I modified your jsFiddle to make use of it: Have a look

If you'd like me to give a more detailed description of zeno's paradox, let me know and I'll post one here with an image or two.


来源: stackexchange

问:
How to disable the "local declaration of 'foo' hides instance variable" warning?
I understand what the warning says. This is exactly how scoping rules work. I appreciate that some people want a nanny. I don't. How can I disable this warning?</p>

答:
Update for Xcode 8.3 - Bug in compiler yields "Declaration shadows a local variable" in some instances when it intentional... and the nanny panics.

For example in Objective C:

Given

```<code>typedef BOOL ( ^BoolBoolBlock ) ( BOOL );
</code>```

And the nature of Apple Blocks will make any variable declared in the immediate outer scope to a Block, a global to the block (pseudo globals). This results in the warnings (and errors if warnings == errors in your settings) on the line BOOL theResult = false;:

```<code>- (BoolBoolBlock) boolBoolBlock {
    BoolBoolBlock    theResult = nil;

    theResult = ^BOOL ( unused BOOL is ) {
        BOOL    theResult = false; // hides (shadows) the outer theResult (a good thing)

        /*
         call back code goes here,
         all variables local in scope to this method are global to the block so be careful
         */
        return theResult;
    };

    return theResult;
}
</code>```

The nanny sees BoolBoolBlock    theResult = nil; getting shadow-blocked by BOOL    theResult = false; which is actually intentional for two reasons in this case:

by convention in my code ALL return values are theResult no matter what

is a positive side effects because I am morally opposed to globals.

In other words this entire construct is setup to block the pseudo global mechanisms of Apple Blocks and put structure on that chaos. Blocking the method's "theResult" from use in the block that the method returns is a good thing ... yet the nanny has a hissy fit.

To calm the nanny down (get rid of warnings or possibly errors if you have the discipline to set warnings as errors), you simply make this setting change in your Project File -> Build Settings -> filter on "Other" -> Hidden Local Variables -> change to "No" ... or visually:

ContentLicense: CC BY-SA 3.0

Body:
Update for Xcode 8.3 - Bug in compiler yields "Declaration shadows a local variable" in some instances when it intentional... and the nanny panics.

For example in Objective C:

Given

typedef BOOL ( ^BoolBoolBlock ) ( BOOL );

And the nature of Apple Blocks will make any variable declared in the immediate outer scope to a Block, a global to the block (pseudo globals). This results in the warnings (and errors if warnings == errors in your settings) on the line BOOL theResult = false;:

- (BoolBoolBlock) boolBoolBlock {
    BoolBoolBlock    theResult = nil;

    theResult = ^BOOL ( unused BOOL is ) {
        BOOL    theResult = false; // hides (shadows) the outer theResult (a good thing)

        /*
         call back code goes here,
         all variables local in scope to this method are global to the block so be careful
         */
        return theResult;
    };

    return theResult;
}

The nanny sees BoolBoolBlock    theResult = nil; getting shadow-blocked by BOOL    theResult = false; which is actually intentional for two reasons in this case:

by convention in my code ALL return values are theResult no matter what

is a positive side effects because I am morally opposed to globals.

In other words this entire construct is setup to block the pseudo global mechanisms of Apple Blocks and put structure on that chaos. Blocking the method's "theResult" from use in the block that the method returns is a good thing ... yet the nanny has a hissy fit.

To calm the nanny down (get rid of warnings or possibly errors if you have the discipline to set warnings as errors), you simply make this setting change in your Project File -> Build Settings -> filter on "Other" -> Hidden Local Variables -> change to "No" ... or visually:


问:
Should I perform input validation on the forms or in the class set method?
Say I have a database which stores information on customers, and there is an application with various forms to register customers, edit customers, delete customers, etc...

Should input validation (for example, checking the customer's post code is in the correct format) be placed in the Customer class or be done on the form?  Currently I have it in the class and I am throwing a custom exception if the value is not of the correct format.

答:
It depends on the architecture of you app.
If you want your app to be extensible and modular, I recomnd you to recpect for  MVC Pattern (Model,View,Controller).
In this case the Model is: Customer Class (That stores only the data of the customer
The View is : The Form
And you should put the control of the data : checking the inputs, storing data in db etc.. (the business logic) in a class Named for exemple CustomerController.
MVC Model</p>


问:
Why this different behaviour while indexing the array using character?
I am trying to write a c++ program to find the first non-repeated character and if all the characters are repeated it would return -1.

I have designed a solution that keeps track of the count of characters using a integer array which I index using the respective character whose count has to be stored.

Program 1:
Gives erroneous output...
http://ide.geeksforgeeks.org/wxOYog

```<code>#include<iostream>
#include<cstring>
using namespace std;
int map[256];
string returnFirstRepeatingChar(string str,int n)
{
    int i=0,flag=1;
    string result;
    for(i=0;i<n;i++)
        map[str[i]]++;

    for(i=0;i<n;i++)
    {
        if(map[str[i]]==1)
        {
            flag=0;
            result = str[i];
            break;
        }
    }
    if(flag)
        return "-1";
    else
        return result;
}
int main()
{
    //code
    int t,N,*arr,i,j;
    cin>>t;
    string str;
    while(t--)
    {
        cin>>N;
        memset(&map,0,256);
        cin>>str;
        cout<<returnFirstRepeatingChar(str,N)<<endl;
    }
    return 0;
}
</code>```

Program 2:
Gives correct output...
http://ide.geeksforgeeks.org/jJvJPu

```<code>#include<iostream>
#include<cstring>
using namespace std;
int map[256];
string returnFirstRepeatingChar(string str,int n)
{
    int i=0,flag=1;
    string result;
    for(i=0;i<n;i++)
        map[str[i]-97]++;           //changed from above program

    for(i=0;i<n;i++)
    {
        if(map[str[i]-97]==1)       //changed from above program
        {
            flag=0;
            result = str[i];
            break;
        }
    }
    if(flag)
        return "-1";
    else
        return result;
}
int main()
{
    //code
    int t,N,*arr,i,j;
    cin>>t;
    string str;
    while(t--)
    {
        cin>>N;
        memset(&map,0,256);
        cin>>str;
        cout<<returnFirstRepeatingChar(str,N)<<endl;
    }
    return 0;
}
</code>```

Only difference between the two programs is location of required counts in the array map..
In the program 1, it starts from 97 (ascii of a)
In the program 2, it starts from 0.

But program 2 gives correct output, but the program 1 isn't. Why?

```<code>Eg: for input: abcdefghij
program 1 output: f
program 2 output: a
</code>```

答:
One important issue here is this line:

```<code>memset(&map,0,256);
</code>```

Here you are zeroing only the first 256/sizeof(int). In case the sizeof(int) is 4, this makes the first 64 int.
However, your program is using the elements which index is greater than 97, hence the issue appearing.
Hence it should be

```<code>memset(&map,0,256*sizeof(int));
</code>```

or could be also simply written as

```<code>memset(map,0,sizeof(map));
</code>```

Remember: the 3rd parameter of memset is "the number of bytes to fill", not "the number of elements of your array"

Body:
I am trying to write a c++ program to find the first non-repeated character and if all the characters are repeated it would return -1.

I have designed a solution that keeps track of the count of characters using a integer array which I index using the respective character whose count has to be stored.

Program 1:
Gives erroneous output...
http://ide.geeksforgeeks.org/wxOYog

#include<iostream>
#include<cstring>
using namespace std;
int map[256];
string returnFirstRepeatingChar(string str,int n)
{
    int i=0,flag=1;
    string result;
    for(i=0;i<n;i++)
        map[str[i]]++;

    for(i=0;i<n;i++)
    {
        if(map[str[i]]==1)
        {
            flag=0;
            result = str[i];
            break;
        }
    }
    if(flag)
        return "-1";
    else
        return result;
}
int main()
{
    //code
    int t,N,*arr,i,j;
    cin>>t;
    string str;
    while(t--)
    {
        cin>>N;
        memset(&map,0,256);
        cin>>str;
        cout<<returnFirstRepeatingChar(str,N)<<endl;
    }
    return 0;
}

Program 2:
Gives correct output...
http://ide.geeksforgeeks.org/jJvJPu

#include<iostream>
#include<cstring>
using namespace std;
int map[256];
string returnFirstRepeatingChar(string str,int n)
{
    int i=0,flag=1;
    string result;
    for(i=0;i<n;i++)
        map[str[i]-97]++;           //changed from above program

    for(i=0;i<n;i++)
    {
        if(map[str[i]-97]==1)       //changed from above program
        {
            flag=0;
            result = str[i];
            break;
        }
    }
    if(flag)
        return "-1";
    else
        return result;
}
int main()
{
    //code
    int t,N,*arr,i,j;
    cin>>t;
    string str;
    while(t--)
    {
        cin>>N;
        memset(&map,0,256);
        cin>>str;
        cout<<returnFirstRepeatingChar(str,N)<<endl;
    }
    return 0;
}

Only difference between the two programs is location of required counts in the array map..
In the program 1, it starts from 97 (ascii of a)
In the program 2, it starts from 0.

But program 2 gives correct output, but the program 1 isn't. Why?

Eg: for input: abcdefghij
program 1 output: f
program 2 output: a

Body:
One important issue here is this line:

memset(&map,0,256);

Here you are zeroing only the first 256/sizeof(int). In case the sizeof(int) is 4, this makes the first 64 int.
However, your program is using the elements which index is greater than 97, hence the issue appearing.
Hence it should be

memset(&map,0,256*sizeof(int));

or could be also simply written as

memset(map,0,sizeof(map));

Remember: the 3rd parameter of memset is "the number of bytes to fill", not "the number of elements of your array"


问:
AngularJS Directive, passing scope objects in post link function
I have a HTML template which I'm using for an angular directive. I need to fire some javascript on the HTML template after it has been compiled (I need to fire jQuery Steps to make the HTML into a wizard)

Sample directive HTML:

```<code><div class='example'>{{passThrough.value1}}</div>
</code>```

and my angular directive would be

```<code>app.directive('accountWizard', function () {
return {
    templateUrl: '../Scripts/angular/directives/templates/AccountWizard.html',
    replace: true,
    transclude: true,
    scope: {
        passThrough: "="
    },
    link: function (scope, elem, attr) {
        scope.bindAccountDirective();
    }
};
</code>```

});

The HTML in the main page would be something like

```<code><account-wizard pass-through="angularObject"/>
</code>```

My problem is that the HTML directive, when rendered, simply has "{{passThrough.value1}}" as text inside the div tag, it's not actually compiling the angular object and returning its value.

When debugging in Chrome, I can see the angular object 'passThrough' in the scope parameter of the link function.

I know I need to do something in the link function to compile and render the directive, but I can't find what that needs to be.

All i need is a simple 'you need to use this....' and I'll work out how to do it from Angular documentation.

Basically, let's say passThrough.value1 = Test Value, I need my directive HTML to compile to

```<code><div class='example'>Test Value</div>
</code>```

and then, I need to run the jQuery steps function on the HTML after the angular object's have been rendered

p.s. the scope.bindAccountDirective() function is a wrapper method for firing jQuery steps.

```<code>$scope.bindAccountDirective = function () {

        $("#frmShippingAccount.wizard-big").steps({
            bodyTag: "fieldset",
            transitionEffect: "slideLeft",
            onStepChanging: function (event, currentIndex, newIndex) {

                // Always allow going backward even if the current step contains invalid fields!
                if (currentIndex > newIndex) {
                    return true;
                }

                var form = $(this);

                // Clean up if user went backward before
                if (currentIndex < newIndex) {
                    // To remove error styles
                    $(".body:eq(" + newIndex + ") label.error", form).remove();
                    $(".body:eq(" + newIndex + ") .error", form).removeClass("error");
                }

                // Disable validation on fields that are disabled or hidden.
                form.validate().settings.ignore = ":disabled,:hidden";

                // Start validation; Prevent going forward if false
                return form.valid();

            },
            onFinishing: function (event, currentIndex) {

                var form = $(this);

                // Disable validation on fields that are disabled.
                // At this point it's recommended to do an overall check (mean ignoring only disabled fields)
                form.validate().settings.ignore = ":disabled";

                // Start validation; Prevent form submission if false
                return form.valid();
            },
            onFinished: function (event, currentIndex) {

                var form = $("#frmShippingAccount");

                $("#savePrompt h1").text("Saving...");

                $scope.saveShippingAccount($scope.shippingAccount);

            }
        }).validate({
            framework: 'bootstrap',
            icon: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            errorPlacement: function (error, element) { }
        });
}
</code>```

UPDATED SOLUTION

Using $timeout() in the link function worked perfectly. It waited for AngularJS to render the passThrough object as it's value, and then fired the bindAccountDirective() function.

```<code>app.directive('accountWizard', function ($timeout) {
    return {
        templateUrl:  '../Scripts/angular/directives/templates/AccountWizard.html',
        replace: true,
        scope: {
            passThrough: "="
        },
        link: function (scope, elem, attr) {
            $timeout(function(){ scope.bindAccountDirective() }, 0 false);
        }
};
</code>```

Body:
I have a HTML template which I'm using for an angular directive. I need to fire some javascript on the HTML template after it has been compiled (I need to fire jQuery Steps to make the HTML into a wizard)

Sample directive HTML:

{{passThrough.value1}}

and my angular directive would be

app.directive('accountWizard', function () {
return {
    templateUrl: '../Scripts/angular/directives/templates/AccountWizard.html',
    replace: true,
    transclude: true,
    scope: {
        passThrough: "="
    },
    link: function (scope, elem, attr) {
        scope.bindAccountDirective();
    }
};

});

The HTML in the main page would be something like

<account-wizard pass-through="angularObject"/>

My problem is that the HTML directive, when rendered, simply has "{{passThrough.value1}}" as text inside the div tag, it's not actually compiling the angular object and returning its value.

When debugging in Chrome, I can see the angular object 'passThrough' in the scope parameter of the link function.

I know I need to do something in the link function to compile and render the directive, but I can't find what that needs to be.

All i need is a simple 'you need to use this....' and I'll work out how to do it from Angular documentation.

Basically, let's say passThrough.value1 = Test Value, I need my directive HTML to compile to

Test Value

and then, I need to run the jQuery steps function on the HTML after the angular object's have been rendered

p.s. the scope.bindAccountDirective() function is a wrapper method for firing jQuery steps.

$scope.bindAccountDirective = function () {

        $("#frmShippingAccount.wizard-big").steps({
            bodyTag: "fieldset",
            transitionEffect: "slideLeft",
            onStepChanging: function (event, currentIndex, newIndex) {

                // Always allow going backward even if the current step contains invalid fields!
                if (currentIndex > newIndex) {
                    return true;
                }

                var form = $(this);

                // Clean up if user went backward before
                if (currentIndex < newIndex) {
                    // To remove error styles
                    $(".body:eq(" + newIndex + ") label.error", form).remove();
                    $(".body:eq(" + newIndex + ") .error", form).removeClass("error");
                }

                // Disable validation on fields that are disabled or hidden.
                form.validate().settings.ignore = ":disabled,:hidden";

                // Start validation; Prevent going forward if false
                return form.valid();

            },
            onFinishing: function (event, currentIndex) {

                var form = $(this);

                // Disable validation on fields that are disabled.
                // At this point it's recommended to do an overall check (mean ignoring only disabled fields)
                form.validate().settings.ignore = ":disabled";

                // Start validation; Prevent form submission if false
                return form.valid();
            },
            onFinished: function (event, currentIndex) {

                var form = $("#frmShippingAccount");

                $("#savePrompt h1").text("Saving...");

                $scope.saveShippingAccount($scope.shippingAccount);

            }
        }).validate({
            framework: 'bootstrap',
            icon: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            errorPlacement: function (error, element) { }
        });
}

UPDATED SOLUTION

Using $timeout() in the link function worked perfectly. It waited for AngularJS to render the passThrough object as it's value, and then fired the bindAccountDirective() function.

app.directive('accountWizard', function ($timeout) {
    return {
        templateUrl:  '../Scripts/angular/directives/templates/AccountWizard.html',
        replace: true,
        scope: {
            passThrough: "="
        },
        link: function (scope, elem, attr) {
            $timeout(function(){ scope.bindAccountDirective() }, 0 false);
        }
};


问:
MVVM Handle all un handled keystrokes on ViewModel
I don't know if this is a good way to work but i need to handle all unhandled keystrokes on my ViewModel so my idea was to use a Behavior on my ShellView that would relay all unhandled keystrokes to the ViewModel..

But the problem is how do i get all unhandled key presses?

Here is my first try to just catch them

```<code>Public Class ForwardKeyBehavior
    Inherits Behavior(Of DependencyObject)

    Protected Overrides Sub OnAttached()
        Keyboard.AddKeyDownHandler(Me.AssociatedObject, AddressOf OnKeyPressed)
        Keyboard.AddPreviewKeyDownHandler(Me.AssociatedObject, AddressOf OnPreviewKeyPressed)
        MyBase.OnAttached()
    End Sub

    Protected Overrides Sub OnDetaching()
        Keyboard.RemoveKeyDownHandler(Me.AssociatedObject, AddressOf OnKeyPressed)
        MyBase.OnDetaching()
    End Sub

    Private Sub OnPreviewKeyPressed(ByVal sender As Object, ByVal e As KeyEventArgs)

    End Sub

    Private Sub OnKeyPressed(ByVal sender As Object, ByVal e As KeyEventArgs)
        If (Not e.Handled) Then
            Trace.Write(e.Key.ToString())
        End If
    End Sub

End Class
</code>```

But it seems that e.Handled always is false so what am i missing even if i press a key in a textbox?

答:
You set e.Handled = True to tell the program that the event has been handled and to stop executing any other functions that are registered to that event.

For example, if you hook up two methods to the KeyPressed event, and the first one sets e.Handled = True, then the 2nd event will never get executed.

I am guessing that all you really need to do is make sure your UnhandledKeyPressedEvent comes last in the event sequence, and that any other KeyPressed events set e.Handled = True to prevent the UnhandledKeyPressedEvent from executing.

ContentLicense: CC BY-SA 2.5

Body:
I don't know if this is a good way to work but i need to handle all unhandled keystrokes on my ViewModel so my idea was to use a Behavior on my ShellView that would relay all unhandled keystrokes to the ViewModel..

But the problem is how do i get all unhandled key presses?

Here is my first try to just catch them

Public Class ForwardKeyBehavior
    Inherits Behavior(Of DependencyObject)

    Protected Overrides Sub OnAttached()
        Keyboard.AddKeyDownHandler(Me.AssociatedObject, AddressOf OnKeyPressed)
        Keyboard.AddPreviewKeyDownHandler(Me.AssociatedObject, AddressOf OnPreviewKeyPressed)
        MyBase.OnAttached()
    End Sub

    Protected Overrides Sub OnDetaching()
        Keyboard.RemoveKeyDownHandler(Me.AssociatedObject, AddressOf OnKeyPressed)
        MyBase.OnDetaching()
    End Sub

    Private Sub OnPreviewKeyPressed(ByVal sender As Object, ByVal e As KeyEventArgs)

    End Sub

    Private Sub OnKeyPressed(ByVal sender As Object, ByVal e As KeyEventArgs)
        If (Not e.Handled) Then
            Trace.Write(e.Key.ToString())
        End If
    End Sub

End Class

But it seems that e.Handled always is false so what am i missing even if i press a key in a textbox?


问:
How to extract portion of a line in ruby?
I have a line say

line = "start running at Sat April 1 07:30:37 2017"

and I want to extract

"Sat April 1 07:30:37 2017"

I tried this...

```<code>line = "start running at Sat April 1 07:30:37 2017"
if (line =~ /start running at/)
   line.split("start running at ").last
end
</code>```

... but is there any other way of doing this?

答:
The shortest would be line["Sat April 1 07:30:37 2017"] which would return your "Sat April 1 07:30:37 2017" string if present and nil if not.
The [] notation on a String is a shorthand for getting a substring out of the string and can be used with another string or a Regular Expression. See https://ruby-doc.org/core-2.2.0/String.html#method-i-5B-5D

In case the string is unknown you can use this shorthand also like Cary suggested

```<code>line[/start running at (.*)/, 1]
</code>```

In case you want to be sure the date extracted is valid you would need the regular expression from his answer but you still could use this method.

Body:
I have a line say

line = "start running at Sat April 1 07:30:37 2017"

and I want to extract

"Sat April 1 07:30:37 2017"

I tried this...

line = "start running at Sat April 1 07:30:37 2017"
if (line =~ /start running at/)
   line.split("start running at ").last
end

... but is there any other way of doing this?

Body:
The shortest would be line["Sat April 1 07:30:37 2017"] which would return your "Sat April 1 07:30:37 2017" string if present and nil if not.
The [] notation on a String is a shorthand for getting a substring out of the string and can be used with another string or a Regular Expression. See https://ruby-doc.org/core-2.2.0/String.html#method-i-5B-5D

In case the string is unknown you can use this shorthand also like Cary suggested

line[/start running at (.*)/, 1]

In case you want to be sure the date extracted is valid you would need the regular expression from his answer but you still could use this method.


问:
Dynamics CRM Plugin-For a input publication value, search for subscription, if found add it to the contact on create/update
The below code seems to work when a contact is created, for input value publication it searches and associates an existing subscription. But the same code wont work for update of a contact. Any opinions as to why this may be happening in my plugin?

if (!String.IsNullOrEmpty(publication))
{
    //Query for existing Publication
    var publicationQuery = new QueryByAttribute("msdynhcp_publicationnewsletter");
    //publicationQuery.ColumnSet.AllColumns = true;
    publicationQuery.Attributes.AddRange("msdynhcp_publicationname");
    publicationQuery.Values.AddRange(publication);
    publicationQuery.TopCount = 1;

    //Call Query
    EntityCollection publicationIds = organizationService.RetrieveMultiple(publicationQuery);

    if (publicationIds.Entities.Count > 0)
    {
        //Query for existing subscription
        var subscriptionQuery = new QueryExpression("msdynhcp_subscription");

        var linkedContact = new LinkEntity("msdynhcp_subscription", "contact", "msdynhcp_contactlookup", "contact" + "id", JoinOperator.Inner);
        linkedContact.LinkCriteria = new FilterExpression(LogicalOperator.And);
        linkedContact.LinkCriteria.AddCondition("contact" + "id", ConditionOperator.Equal, ContactId);
        subscriptionQuery.LinkEntities.Add(linkedContact);

        var linkedPublication = new LinkEntity("msdynhcp_subscription", "msdynhcp_publicationnewsletter", "msdynhcp_publicationlookup", "msdynhcp_publicationnewsletter" + "id", JoinOperator.Inner);
        linkedPublication.LinkCriteria = new FilterExpression(LogicalOperator.And);
        linkedPublication.LinkCriteria.AddCondition("msdynhcp_publicationnewsletter" + "id", ConditionOperator.Equal, publicationIds[0].Id);
        subscriptionQuery.LinkEntities.Add(linkedContact);

        subscriptionQuery.TopCount = 1;

        //Call Query
        EntityCollection subscriptionIDs = organizationService.RetrieveMultiple(subscriptionQuery);

        if (subscriptionIDs.Entities.Count == 0)
        {
            //New Subscription
            var crmSubscription = new Entity("msdynhcp_subscription");
            crmSubscription["msdynhcp_utcdatetimestamp"] = DateTime.UtcNow;
            crmSubscription["msdynhcp_enabledactive"] = true;

            //Call Create
            var id = organizationService.Create(crmSubscription);

            //Call Associate
            organizationService.Associate("msdynhcp_subscription", id, new Relationship("msdynhcp_contact_new_subscription_contactlookup"),
                new EntityReferenceCollection(new List<EntityReference>() { new EntityReference("contact", new Guid(ContactId)) }));
            //Call Associate
            organizationService.Associate("msdynhcp_subscription", id, new Relationship("msdynhcp_new_publicationnewsletter_new_subscription_publicationlookup"),
                new EntityReferenceCollection(new List<EntityReference>() { new EntityReference("msdynhcp_publicationnewsletter", publicationIds.Entities[0].Id) }));
        }
    }
}
```

答: In an effort to "teach a man to fish" rather then telling you what's wrong, why don't you just debug it yourself?  You can use the Plugin Registration tool to create a serialized version of the plugin context, and then debug that yourself.</p>


问:
Angular2 Templates: How to bind keydown.arrow to whole div instead of only control elements?
I have a simple navigator component with some buttons and a date-picker subcomponent. Now the idea is, that I can bind keydown.arrowleft etc. for the whole div (which has css style of 100% height and width). It's template looks like this:

```<code><div id="ck-navigator" (keydown.arrowleft)="decrementDate();
    $event.preventDefault()" (keydown.arrowright)="incrementDate();
$event.preventDefault()">
    <button (click)="decrementDate()" class="fa fa-2x fa-chevron-left">
    </button>
    <ck-date-picker [date]="date" (dateChange)="changeDate($event)">
    </ck-date-picker>
    <button (click)="incrementDate()" class="fa fa-2x fa-chevron-right"></button>
</div>
</code>```

I don't show the component code, it does not matter for this question (afaik).
This is working, but only if I actively select a button or the date-picker in advance (aka a control element). Is there a possibility to extend the keybinding to the whole div (i.e. if I just click somewhere on the site). Sorry for my lack of understanding the DOM and thanks for any push in the right direction.

答:
If what you want is to detect key events on the whole page what you need is probably to add @HostListener to your component. It is gona let you manage events in the whole page/window.

Seeing an example.

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

[your @Component stuff ..... ]

```<code>@HostListener("window:keydown", ['$event'])

 onKeyDown(event:KeyboardEvent) {

    console.log(`Pressed ${event.key}!`);
  }
</code>```

Furthermore could help you to know that when you want to refer specific items you can use ElementRef class and ViewChild by importing them from angular/core. Then manage DOM components as:

```<code>@ViewChild('DOM_Id') element: ElementRef;
</code>```

Maybe it helps. Peace

Body:
I have a simple navigator component with some buttons and a date-picker subcomponent. Now the idea is, that I can bind keydown.arrowleft etc. for the whole div (which has css style of 100% height and width). It's template looks like this:

    <button (click)="decrementDate()" class="fa fa-2x fa-chevron-left">
    </button>
    <ck-date-picker [date]="date" (dateChange)="changeDate($event)">
    </ck-date-picker>
    <button (click)="incrementDate()" class="fa fa-2x fa-chevron-right"></button>

I don't show the component code, it does not matter for this question (afaik).
This is working, but only if I actively select a button or the date-picker in advance (aka a control element). Is there a possibility to extend the keybinding to the whole div (i.e. if I just click somewhere on the site). Sorry for my lack of understanding the DOM and thanks for any push in the right direction.

Body:
If what you want is to detect key events on the whole page what you need is probably to add @HostListener to your component. It is gona let you manage events in the whole page/window.

Seeing an example.

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

[your @Component stuff ..... ]

@HostListener("window:keydown", ['$event'])

 onKeyDown(event:KeyboardEvent) {

    console.log(`Pressed ${event.key}!`);
  }

Furthermore could help you to know that when you want to refer specific items you can use ElementRef class and ViewChild by importing them from angular/core. Then manage DOM components as:

@ViewChild('DOM_Id') element: ElementRef;

Maybe it helps. Peace


问:
Is there XML, XSLT, and XPATH support in the new Microsoft Edge browser?
Does anyone have information about XML, XSLT, or XPATH support in the new Microsoft Edge browser?

In specific: When I use the JavaScript function transformToDocument(), it ends with the following error message: “Error in transformNode: Invalid argument”.

The same code is working with IE 10, IE 11, Chrome, Safari, etc., but unfortunately is not working with the new browser.

答:
Microsoft Edge supports XSLT:

MSXML6 is the only version of MSXML implemented in Microsoft Edge, which uses it only to implement XSLT [W3C-XSLT].

XPath:

Microsoft Edge provides [XPATH] functionality natively; see [MS-XPATH] for more information.

and XML (XML DOM, XML Namespaces, XHTML and the responseXML property of the XMLHTTPRequest object).

References

[MS-ISO8859]: Microsoft Implementations

[MS-XHTML]: [W3C-XHTML1.0] Section 3.2, User Agent Conformance

[MS-XMLH]: Internet Explorer XML 1.0 (Fifth Edition) Standards Support Document

[MS-XPATH]: Microsoft XML XPath Standards Support Document


问:
How to positioning divs float left but also to top

How to make Divs inside div float left with no spaces; As you can see on the image have spaces, i am using these codes;

```<code>main {position:relative;left:339.5px;top:40px;width:1018px;height:1000px;-webkit-box-shadow:inset 0px 0px 40px;}

main div {float:left;margin:1px;-webkit-box-shadow:inset 0px 0px 20px;}
#div_size1 {width:336px;height:200px;}
#div_size2 {width:336px;height:300px;}
#div_size3 {width:336px;height:100px;}

<main>
<div id="div_size1">
</div>
<div id="div_size2">
</div>
<div id="div_size3">
</div>
<div id="div_size3">
</div>
<div id="div_size3">
</div>
<div id="div_size2">
</div>
<div id="div_size2">
</div>
<div id="div_size1">
</div>
<div id="div_size2">
</div>
<div id="div_size3">
</div>
<div id="div_size3">
</div>
</main>
</code>```

答: If you want it fixed and if I was building this layout I would have 2 "colum" Divs. The first 1 would be 2 boxes wide. And the other one would be 1 box wide. Left and Right. The 5 boxes on the right would be in the right column div. Then with the left column I would further separate that. I would put 2 "row" divs. The bottom would would have the bottom 1 box (div_size3). Then with the top row I would separate that by inserting 2 colum divs. The left one would have 3 boxes and the right one 2 boxes.  </p>

Body:
How to make Divs inside div float left with no spaces; As you can see on the image have spaces, i am using these codes;

main {position:relative;left:339.5px;top:40px;width:1018px;height:1000px;-webkit-box-shadow:inset 0px 0px 40px;}

main div {float:left;margin:1px;-webkit-box-shadow:inset 0px 0px 20px;}
#div_size1 {width:336px;height:200px;}
#div_size2 {width:336px;height:300px;}
#div_size3 {width:336px;height:100px;}


问:
Why can't I create new classes in AX any more?
I created a new class in AX. After an AX restart the class was no longer in the AOT. If I now try to create a new class I get this error message:

"Unable to save . Unable to save Class Class2. Id 50001 already exists."

How can I fix that problem?

答:
You may have a data corruption in your .aod or .aoi index.

Select Reindex from Tools\Development tools\Application objects.
This will recreate the .aoi file and this may solve your problem.

The reindex operation may take several minutes.


问:
Routing to different controllers depending on authentication
In rewriting an app using Symfony2, I'm attempting to preserve some legacy behaviour and am looking for a clean solution.

My goal is to have the URI "/" display a splash page if the user is not logged in, and the same URI display a per-user dashboard if they are logged in.

The solution also needs to be scalable - there are several pages on the "public" site which have different representations on the "private" site (i.e. the index, support, about, contact, etc) - because of this I can't simply use a catch-all route and forward to the correct controller myself.

I have one potential solution, which I will post as an answer, but I'm looking for advice on better approaches.

答:
I'm on symfony3, but here's my approach. After login, I send all users to /login/redirect, with the controller shown below. It's simple and uses the built-in ROLES_* functionality.

```<code>/**
 * Redirect users after login based on various checks
 *
 * @Route("/login/redirect", name="_login_redirect")
 */
public function loginRedirectAction()
{
    // Send user to admin page or order page based on credentials
    if ($this->isGranted('ROLE_SUPERUSER')) {
        return $this->redirectToRoute('admin_home');
    } elseif ($this->isGranted('ROLE_ADMIN')) {
        return $this->redirectToRoute('dashboard');
    } else {
        return $this->redirectToRoute('order_page');
    }
}
</code>```

To handle those not logged in, I use some simple logic in my twig template. Note that symfony automatically gives all logged in users a ROLES_USER role.

```<code>    {% if is_granted('ROLE_USER') %}
        {# User is logged in, do something appropriate #}
        <li>{{ app.user ? app.user.name : '' }}</li>
        {# Useful stuff #}
    {% else %}
        {# Show login link, or give other info #}
        <li><a href="{{ path('security_login') }}">Login</a></li>
    {% endif %}
</code>```

Body:
I'm on symfony3, but here's my approach. After login, I send all users to /login/redirect, with the controller shown below. It's simple and uses the built-in ROLES_* functionality.

/**
 * Redirect users after login based on various checks
 *
 * @Route("/login/redirect", name="_login_redirect")
 */
public function loginRedirectAction()
{
    // Send user to admin page or order page based on credentials
    if ($this->isGranted('ROLE_SUPERUSER')) {
        return $this->redirectToRoute('admin_home');
    } elseif ($this->isGranted('ROLE_ADMIN')) {
        return $this->redirectToRoute('dashboard');
    } else {
        return $this->redirectToRoute('order_page');
    }
}

To handle those not logged in, I use some simple logic in my twig template. Note that symfony automatically gives all logged in users a ROLES_USER role.

    {% if is_granted('ROLE_USER') %}
        {# User is logged in, do something appropriate #}
        <li>{{ app.user ? app.user.name : '' }}</li>&nbsp;
        {# Useful stuff #}
    {% else %}
        {# Show login link, or give other info #}
        <li><a href="{{ path('security_login') }}">Login</a></li>
    {% endif %}


问:
Is there a way to nuke all AWS resources in an AWS account?
I have an AWS account where multiple EC2 instances, load balancers, target groups, security groups etc are setup by multiple owners.
We use terraform to set this up but sometimes due to corruption, the state becomes inconsistent. Current mechanism to recover is to manually destroy all resources in that account owned by a particular owner.
Is there an easy way to nuke all resources in an AWS account belonging to a particular owner?</p>

答:
Agree with the other answer that there is no easy way delete orphan resources.

But I see the original issue is that the terraform state is corrupted.
You can checkout the terraform import feature which lets you generate state file from aws resources. In that way you can connect your config to resources again.


问:
Swapping using 2d arrays in C++
I want to sort an array which contains names according to their length, but the following program gives a compiler error when I try to swap them using a function. Please help me identify my mistake.</p>

```<code>void sort(char name1[][50])
{
    for (int i = 0; i < 5; i++)
    {
        if (strlen(name1[i])>strlen(name1[i+1]))
        {
            char temp[50];
            temp=name1[i];
            name1[i]=name1[i+1];
            name1[i+1]=temp;
        }
    }
}
</code>```

答:
Use strcpy() to copy one array to other

```<code>void sort( char name1[][50])
{

    for(int i=0; i< 5;  i++)
    {
        if(strlen(name1[i])>strlen(name1[i+1]))
        {
        char temp[50];
        strcpy(temp,name1[i]);
        strcpy(name1[i],name1[i+1]);
        strcpy(name1[i+1],temp);
        }
    }
}
</code>```

Title: Swapping using 2d arrays in C++

Body:
I want to sort an array which contains names according to their length, but the following program gives a compiler error when I try to swap them using a function. Please help me identify my mistake.

void sort(char name1[][50])
{
    for (int i = 0; i < 5; i++)
    {
        if (strlen(name1[i])>strlen(name1[i+1]))
        {
            char temp[50];
            temp=name1[i];
            name1[i]=name1[i+1];
            name1[i+1]=temp;
        }
    }
}

Body:
Use strcpy() to copy one array to other

void sort( char name1[][50])
{

    for(int i=0; i< 5;  i++)
    {
        if(strlen(name1[i])>strlen(name1[i+1]))
        {
        char temp[50];
        strcpy(temp,name1[i]);
        strcpy(name1[i],name1[i+1]);
        strcpy(name1[i+1],temp);
        }
    }
}


问:
How to create more than one circular progress bar?
I find this code for progress bar circle, But this code just creates one progress bar circle.

I need to create more one progress bar.

This code:

http://jsfiddle.net/Aapn8/3410/

```<code><div class="chart" id="graph" data-percent="88"></div>
</code>```

JS

```<code>var el = document.getElementById('graph'); // get canvas

var options = {
    percent:  el.getAttribute('data-percent') || 25,
    size: el.getAttribute('data-size') || 220,
    lineWidth: el.getAttribute('data-line') || 15,
    rotate: el.getAttribute('data-rotate') || 0
}

var canvas = document.createElement('canvas');
var span = document.createElement('span');
span.textContent = options.percent + '%';

if (typeof(G_vmlCanvasManager) !== 'undefined') {
    G_vmlCanvasManager.initElement(canvas);
}

var ctx = canvas.getContext('2d');
canvas.width = canvas.height = options.size;

el.appendChild(span);
el.appendChild(canvas);

ctx.translate(options.size / 2, options.size / 2); // change center
ctx.rotate((-1 / 2 + options.rotate / 180) * Math.PI); // rotate -90 deg

//imd = ctx.getImageData(0, 0, 240, 240);
var radius = (options.size - options.lineWidth) / 2;

var drawCircle = function(color, lineWidth, percent) {
        percent = Math.min(Math.max(0, percent || 1), 1);
        ctx.beginPath();
        ctx.arc(0, 0, radius, 0, Math.PI * 2 * percent, false);
        ctx.strokeStyle = color;
        ctx.lineCap = 'round'; // butt, round or square
        ctx.lineWidth = lineWidth
        ctx.stroke();
};

drawCircle('#efefef', options.lineWidth, 100 / 100);
drawCircle('#555555', options.lineWidth, options.percent / 100);
</code>```

Thank you.

答:
You have already done the hard-work. wrap your code in a function which accepts a DOM element and create circle based on it.

```<code>var elems = document.querySelectorAll('.chart'); // get canvas
elems.forEach(function(el) {
  createCircle(el);
})

function createCircle(el) {
  //Logic to create circle
}
</code>```

var elems = document.querySelectorAll('.chart'); // get canvas
elems.forEach(function(el) {
  createCircle(el);
})

function createCircle(el) {
  var options = {
    percent: el.getAttribute('data-percent') || 25,
    size: el.getAttribute('data-size') || 220,
    lineWidth: el.getAttribute('data-line') || 15,
    rotate: el.getAttribute('data-rotate') || 0
  }

  var canvas = document.createElement('canvas');
  var span = document.createElement('span');
  span.textContent = options.percent + '%';

  if (typeof(G_vmlCanvasManager) !== 'undefined') {
    G_vmlCanvasManager.initElement(canvas);
  }

  var ctx = canvas.getContext('2d');
  canvas.width = canvas.height = options.size;

  el.appendChild(span);
  el.appendChild(canvas);

  ctx.translate(options.size / 2, options.size / 2); // change center
  ctx.rotate((-1 / 2 + options.rotate / 180) * Math.PI); // rotate -90 deg

  //imd = ctx.getImageData(0, 0, 240, 240);
  var radius = (options.size - options.lineWidth) / 2;

  var drawCircle = function(color, lineWidth, percent) {
    percent = Math.min(Math.max(0, percent || 1), 1);
    ctx.beginPath();
    ctx.arc(0, 0, radius, 0, Math.PI * 2 * percent, false);
    ctx.strokeStyle = color;
    ctx.lineCap = 'round'; // butt, round or square
    ctx.lineWidth = lineWidth
    ctx.stroke();
  };

  drawCircle('#efefef', options.lineWidth, 100 / 100);
  drawCircle('#555555', options.lineWidth, options.percent / 100);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
  position: relative;
  margin: 80px;
  width: 220px;
  height: 220px;
}

canvas {
  display: block;
  position: absolute;
  top: 0;
  left: 0;
}

span {
  color: #555;
  display: block;
  line-height: 220px;
  text-align: center;
  width: 220px;
  font-family: sans-serif;
  font-size: 40px;
  font-weight: 100;
  margin-left: 5px;
}

input {
  width: 200px;
}

span {}</code>```

```

Update Fiddle

Body:
I find this code for progress bar circle, But this code just creates one progress bar circle.

I need to create more one progress bar.

This code:

http://jsfiddle.net/Aapn8/3410/

JS

var el = document.getElementById('graph'); // get canvas

var options = {
    percent:  el.getAttribute('data-percent') || 25,
    size: el.getAttribute('data-size') || 220,
    lineWidth: el.getAttribute('data-line') || 15,
    rotate: el.getAttribute('data-rotate') || 0
}

var canvas = document.createElement('canvas');
var span = document.createElement('span');
span.textContent = options.percent + '%';

if (typeof(G_vmlCanvasManager) !== 'undefined') {
    G_vmlCanvasManager.initElement(canvas);
}

var ctx = canvas.getContext('2d');
canvas.width = canvas.height = options.size;

el.appendChild(span);
el.appendChild(canvas);

ctx.translate(options.size / 2, options.size / 2); // change center
ctx.rotate((-1 / 2 + options.rotate / 180) * Math.PI); // rotate -90 deg

//imd = ctx.getImageData(0, 0, 240, 240);
var radius = (options.size - options.lineWidth) / 2;

var drawCircle = function(color, lineWidth, percent) {
        percent = Math.min(Math.max(0, percent || 1), 1);
        ctx.beginPath();
        ctx.arc(0, 0, radius, 0, Math.PI * 2 * percent, false);
        ctx.strokeStyle = color;
        ctx.lineCap = 'round'; // butt, round or square
        ctx.lineWidth = lineWidth
        ctx.stroke();
};

drawCircle('#efefef', options.lineWidth, 100 / 100);
drawCircle('#555555', options.lineWidth, options.percent / 100);

Thank you.

Body:
You have already done the hard-work. wrap your code in a function which accepts a DOM element and create circle based on it.

var elems = document.querySelectorAll('.chart'); // get canvas
elems.forEach(function(el) {
  createCircle(el);
})

function createCircle(el) {
  //Logic to create circle
}

var elems = document.querySelectorAll('.chart'); // get canvas
elems.forEach(function(el) {
  createCircle(el);
})

function createCircle(el) {
  var options = {
    percent: el.getAttribute('data-percent') || 25,
    size: el.getAttribute('data-size') || 220,
    lineWidth: el.getAttribute('data-line') || 15,
    rotate: el.getAttribute('data-rotate') || 0
  }

  var canvas = document.createElement('canvas');
  var span = document.createElement('span');
  span.textContent = options.percent + '%';

  if (typeof(G_vmlCanvasManager) !== 'undefined') {
    G_vmlCanvasManager.initElement(canvas);
  }

  var ctx = canvas.getContext('2d');
  canvas.width = canvas.height = options.size;

  el.appendChild(span);
  el.appendChild(canvas);

  ctx.translate(options.size / 2, options.size / 2); // change center
  ctx.rotate((-1 / 2 + options.rotate / 180) * Math.PI); // rotate -90 deg

  //imd = ctx.getImageData(0, 0, 240, 240);
  var radius = (options.size - options.lineWidth) / 2;

  var drawCircle = function(color, lineWidth, percent) {
    percent = Math.min(Math.max(0, percent || 1), 1);
    ctx.beginPath();
    ctx.arc(0, 0, radius, 0, Math.PI * 2 * percent, false);
    ctx.strokeStyle = color;
    ctx.lineCap = 'round'; // butt, round or square
    ctx.lineWidth = lineWidth
    ctx.stroke();
  };

  drawCircle('#efefef', options.lineWidth, 100 / 100);
  drawCircle('#555555', options.lineWidth, options.percent / 100);
}

div {
  position: relative;
  margin: 80px;
  width: 220px;
  height: 220px;
}

canvas {
  display: block;
  position: absolute;
  top: 0;
  left: 0;
}

span {
  color: #555;
  display: block;
  line-height: 220px;
  text-align: center;
  width: 220px;
  font-family: sans-serif;
  font-size: 40px;
  font-weight: 100;
  margin-left: 5px;
}

input {
  width: 200px;
}

span {}

<div class="chart" data-percent="88"></div>
<div class="chart" data-percent="32"></div>

Update Fiddle


问:
Not using forms and not doing a submit and yet page refreshes - why?
The code below does not use a form and does not do a submit and yet on click of a button the page is reloaded.  A reload should not occur based on everything I have read.  I don't understand why.  Can anyone help?

I also tried adding event function to the button (see updated source code) and have updated the source below.  It did now work

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

    $('input[type=button]').hover(function() {
        $(this).toggleClass('ui-state-hover');
    });

    // get the php vars into local vars
    var req_status = '<?=$req_status?>';
    var member_id  = '<?=$mbr_id?>';
    var group_id   = '<?=$grp_id?>';

    if (req_status == 'member-is-grp-ldr') {
        $("#ok").prop('value', 'Unsubscribe');
        $('#ok').prop('disabled',true);
        $('#ok').addClass('ui-state-disabled');
    } else if (req_status == 'member-not-in-group') {
        $("#ok").prop('value', 'Resubscribe');
        $('#ok').prop('disabled',false);
    } else if (req_status == 'member-removed') {
        $("#ok").prop('value', 'Resubscribe');
        $('#ok').prop('disabled',false);
        $("#close").prop('value', 'Close');
    } else {
        $("#ok").prop('value', 'Unsubscribe');
        $('#ok').prop("disabled",false);
    }

   $('#ok').on('click', function(e) {
        e.preventDefault();
        if ($('#ok').val() == "Unsubscribe") {
            $.post('./ajax_group_unsubscribe.php', {function:'unsubscribe', member_id:member_id, group_id:group_id}, function(status) {
                if (status = 'true') {
                    $("#ok").prop('value', 'Resubscribe');
                    $('#ok').prop('disabled',false);
                    $('#ok').removeClass('ui-state-disabled');
                    $("#close").prop('value', 'Close');
                    document.getElementById('remark').innerHTML = "You have been removed from the group:";
                };
            });
        } else if ($('#ok').val() == "Resubscribe") {
            $.post('./ajax_group_unsubscribe.php', {function:'subscribe', member_id:member_id, group_id:group_id }, function(status) {
                if (status = 'true') {
                    $("#ok").prop('value', 'Unsubscribe');
                    $('#ok').prop('disabled',false);
                    $('#ok').removeClass('ui-state-disabled');
                    $("#close").prop('value', 'Close');
                    document.getElementById('remark').innerHTML = "You have been added to the group:";
                };
            });
        }
    });
});

</SCRIPT>
</HEAD>

<BODY>
    <div id="page-wrap">
        <div id="header_wrapper">
            Group Unsubscribe Request
        </div>
        <div id="groups_bg">
            <?php
                if ($req_status == "member-in-group") {
                    echo "<p id='remark'>Confirm you no longer want to receive messages for the group:</p>";
                    echo "<p><em>" . $grp_name . "</em></p>";
                } else if ($req_status == "member-not-in-group") {
                    echo "<p id='remark'>You are not currently in the group:</p>";
                    echo "<p><em>" . $grp_name . "</em></p>";
                } else if ($req_status == "member-removed") {
                    echo "<p id='remark'>You will no longer receive messages for the group:</p>";
                    echo "<p><em>" . $grp_name . "</em></p>";
                } else {
                    echo "<p id='remark'>You are the group leader and may not unsubscribe from the group:</p>";
                    echo "<p><em>" . $grp_name . "</em></p>";
                }
            ?>
            <br>
            <div style="text-align:center;">
            <input type="button" id="ok" name="ok" class='ui-button ui-widget ui-state-default ui-corner-all' value="Unsubscribe">
            <input type="button" id="close"  name="close"  class='ui-button ui-widget ui-state-default ui-corner-all' value="Cancel" onclick="window.open('', '_self', ''); window.close();">
            </div>
        </div>
    </div>
</BODY>
</HTML>
</code>```

Here is the ajax code:

```<code>/* get a database object */
$db = new DatabaseA();

/* get the member id and group id */
$function  = $_POST['function'];
$member_id = $_POST['member_id'];
$group_id  = $_POST['group_id'];

/* initialize the return status - booleans not returned */
$ret_status = 'false';

/* if the member id and group id were provided then */
if ( ! empty($member_id) && ! empty($group_id) ) {

    /* get organization id for the group */
    $group_info = get_group_info($db, $group_id, "org_id, group_name");
    $org_id = $group_info['org_id'];
    $grp_name = $group_info['group_name'];

    /* get the group leader */
    $grp_ldr_id = get_group_leader($db, $group_id);

    /* if the member is not the group leader then */
    if ($member_id <> $grp_ldr_id) {

        /* if the member is unsubscribing then */
        if ( $function = "Unsubscribe" && ! empty($org_id) ) {

            /* delete the member from the group */
            remove_member_from_group($db, $member_id, $group_id, $org_id);

            /* notify the group leader */
            send_member_email($db, $grp_ldr_id, "Group Member Update", "Member " . $mbrfirst_name . " " . $mbrlast_name . " has unsubscribed from your group: " . $grp_name);

            /* indicate the member was unsubscribed */
            $ret_status = 'true';

        /* else if the member is resubscribing then */
        } else if ($function = "Resubscribe" && ! empty($org_id) ) {

            /* add the member to the group */
            add_member_to_group($db, $member_id, $group_id, $org_id);

            /* notify the group leader */
            send_member_email($db, $grp_ldr_id, "Group Member Update", "Member " . $mbrfirst_name . " " . $mbrlast_name . " has resubscribed to your group: " . $grp_name);

            /* indicate the member was subscribed */
            $ret_status = 'true';
        }
    }
}

/* return to the caller */
return ($ret_status);
</code>```

答:
Instead of <input></input> You should use <button type="button"></button>.
Clicking on an input is interpreted as submiting.

Body:
The code below does not use a form and does not do a submit and yet on click of a button the page is reloaded.  A reload should not occur based on everything I have read.  I don't understand why.  Can anyone help?

I also tried adding event function to the button (see updated source code) and have updated the source below.  It did now work

            Group Unsubscribe Request

            <?php
                if ($req_status == "member-in-group") {
                    echo "
Confirm you no longer want to receive messages for the group:
";
                    echo "
" . $grp_name . "
";
                } else if ($req_status == "member-not-in-group") {
                    echo "
You are not currently in the group:
";
                    echo "
" . $grp_name . "
";
                } else if ($req_status == "member-removed") {
                    echo "
You will no longer receive messages for the group:
";
                    echo "
" . $grp_name . "
";
                } else {
                    echo "
You are the group leader and may not unsubscribe from the group:
";
                    echo "
" . $grp_name . "
";
                }
            ?>

            <input type="button" id="ok" name="ok" class='ui-button ui-widget ui-state-default ui-corner-all' value="Unsubscribe">
            <input type="button" id="close"  name="close"  class='ui-button ui-widget ui-state-default ui-corner-all' value="Cancel" onclick="window.open('', '_self', ''); window.close();">

Here is the ajax code:

/* get a database object */
$db = new DatabaseA();

/* get the member id and group id */
$function  = $_POST['function'];
$member_id = $_POST['member_id'];
$group_id  = $_POST['group_id'];

/* initialize the return status - booleans not returned */
$ret_status = 'false';

/* if the member id and group id were provided then */
if ( ! empty($member_id) && ! empty($group_id) ) {

    /* get organization id for the group */
    $group_info = get_group_info($db, $group_id, "org_id, group_name");
    $org_id = $group_info['org_id'];
    $grp_name = $group_info['group_name'];

    /* get the group leader */
    $grp_ldr_id = get_group_leader($db, $group_id);

    /* if the member is not the group leader then */
    if ($member_id <> $grp_ldr_id) {

        /* if the member is unsubscribing then */
        if ( $function = "Unsubscribe" && ! empty($org_id) ) {

            /* delete the member from the group */
            remove_member_from_group($db, $member_id, $group_id, $org_id);

            /* notify the group leader */
            send_member_email($db, $grp_ldr_id, "Group Member Update", "Member " . $mbrfirst_name . " " . $mbrlast_name . " has unsubscribed from your group: " . $grp_name);

            /* indicate the member was unsubscribed */
            $ret_status = 'true';

        /* else if the member is resubscribing then */
        } else if ($function = "Resubscribe" && ! empty($org_id) ) {

            /* add the member to the group */
            add_member_to_group($db, $member_id, $group_id, $org_id);

            /* notify the group leader */
            send_member_email($db, $grp_ldr_id, "Group Member Update", "Member " . $mbrfirst_name . " " . $mbrlast_name . " has resubscribed to your group: " . $grp_name);

            /* indicate the member was subscribed */
            $ret_status = 'true';
        }
    }
}

/* return to the caller */
return ($ret_status);


问:
Docker on CentOS 7.2: kernel:unregister_netdevice: waiting for lo to become free. Usage count = 1
I'm running Docker on CentOS 7, from time to time there's the following message displayed:

```<code>Message from syslogd@dev-master at Mar 29 17:23:03 ...
  kernel:unregister_netdevice: waiting for lo to become free. Usage count = 1
</code>```

I've googled a lot, read a lot of resources found and tried many ways like keeping my system updated, upgrading kernel etc, but the message still keeps showing up, it's not too often but sooner or later I'll see it. Also I found issue for this problem on docker github is still open, then my questions are:

What does this message mean? Could somebody give me a simple explanation why docker causes it?

Is there any workaround for this?

If it could not be fixed yet(the issue is still open), will it affect the server or services running inside docker container? Will it be a serious performance issue because it also happens on our production servers?

Docker version:

```<code>Client:
 Version:      1.11.1
 API version:  1.23
 Go version:   go1.5.4
 Git commit:   5604cbe
 Built:        Wed Apr 27 00:34:42 2016
 OS/Arch:      linux/amd64

Server:
 Version:      1.11.1
 API version:  1.23
 Go version:   go1.5.4
 Git commit:   5604cbe
 Built:        Wed Apr 27 00:34:42 2016
 OS/Arch:      linux/amd64
</code>```

OS info:

```<code>CentOS 7, with kernel version: 4.6.0-1.el7.elrepo.x86_64
</code>```

I really appreciate for any info/tips or resources, thanks a lot.

答: Your best source of information is the issue you linked to docker#5618. This is a kernel bug, and has not yet been resolved. The issue is "triggered" by docker because starting/stopping containers also creates network interfaces for containers when they are created/destroyed.</p>

Body:
I'm running Docker on CentOS 7, from time to time there's the following message displayed:

Message from syslogd@dev-master at Mar 29 17:23:03 ...
  kernel:unregister_netdevice: waiting for lo to become free. Usage count = 1

I've googled a lot, read a lot of resources found and tried many ways like keeping my system updated, upgrading kernel etc, but the message still keeps showing up, it's not too often but sooner or later I'll see it. Also I found issue for this problem on docker github is still open, then my questions are:

What does this message mean? Could somebody give me a simple explanation why docker causes it?

Is there any workaround for this?

If it could not be fixed yet(the issue is still open), will it affect the server or services running inside docker container? Will it be a serious performance issue because it also happens on our production servers?

Docker version:

Client:
 Version:      1.11.1
 API version:  1.23
 Go version:   go1.5.4
 Git commit:   5604cbe
 Built:        Wed Apr 27 00:34:42 2016
 OS/Arch:      linux/amd64

Server:
 Version:      1.11.1
 API version:  1.23
 Go version:   go1.5.4
 Git commit:   5604cbe
 Built:        Wed Apr 27 00:34:42 2016
 OS/Arch:      linux/amd64

OS info:

CentOS 7, with kernel version: 4.6.0-1.el7.elrepo.x86_64

I really appreciate for any info/tips or resources, thanks a lot.


问:
Is it possible to "hide" a sub directory after rewriting root to that directory?
What I'm trying to accomplish is basically hide the fact that the page is served from a subdirectory.

I currently have the following .htaccess

```<code>RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} !^/blog
RewriteRule (.*) /blog/$1
</code>```

This does what I want. It serves pages from /blog while giving the user the impression of being in the root directory.

However if the user visits http://www.example.com/blog they get the same page. If possible I would actually like them to get /blog/blog.

The main reason this worries me is not because of real users but because of robots that might index the page with the wrong URL.

答:
This is possible but you have to cheat a little. Essentially THE_REQUEST never changes during rewriting so you can test for that.

```<code>RewriteEngine On
RewriteBase /
RewriteCond %{THE_REQUEST} /blog
RewriteRule . - [F]
RewriteCond %{REQUEST_URI} !^/blog
RewriteRule (.*) /blog/$1
</code>```

http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewritecond

Body:
What I'm trying to accomplish is basically hide the fact that the page is served from a subdirectory.

I currently have the following .htaccess

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} !^/blog
RewriteRule (.*) /blog/$1

This does what I want. It serves pages from /blog while giving the user the impression of being in the root directory.

However if the user visits http://www.example.com/blog they get the same page. If possible I would actually like them to get /blog/blog.

The main reason this worries me is not because of real users but because of robots that might index the page with the wrong URL.

Body:
This is possible but you have to cheat a little. Essentially THE_REQUEST never changes during rewriting so you can test for that.

RewriteEngine On
RewriteBase /
RewriteCond %{THE_REQUEST} /blog
RewriteRule . - [F]
RewriteCond %{REQUEST_URI} !^/blog
RewriteRule (.*) /blog/$1

http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewritecond


问:
Adding JSON array to DynamoDB Item
I understand that I can create "Lists" only from primitive data types, so look at my (Node.js using AWS Document Client) code as pseudo code.  My objective is to attach a JSON array to an item so that I can later retrieve/update/delete the device (and corresponding data) from the customer's record.  I understand I may be able to use Maps to do this, but I'm a beginner and the documentation regarding how to do that using document client is unclear to me.

This is what I am trying to do:

```<code>var deviceData = {
    'deviceID': deviceID,
    'attributes': [
        {'firmwareVersion': firmwareVersion},
        {'productID': productID},
        {'knickName': 'New Device'},
        {'dateAdded': (new Date()).getTime()}
    ]
};

var newCustomerData = {
    TableName: process.env.customerMasterFile,
    Key: {
        'email': email
    },
    ReturnValues: 'UPDATED_NEW',
    UpdateExpression: 'ADD #device :device SET #customerEmailDomain = :customerEmailDomain, #friendlyName = :friendlyName, #created = :created, #updated = :updated',
    ExpressionAttributeNames: {
        '#device': 'deviceList',
        '#customerEmailDomain': 'customerEmaiDomain',
        '#friendlyName': 'friendlyName',
        '#created': 'createAccountTime',
        '#updated': 'updateAccountTime',
    },
    ExpressionAttributeValues: {
        ':device': docClient.createSet([deviceData]),  // I know this is incorrect...
        ':customerEmailDomain': customerEmailDomain,
        ':friendlyName': friendlyName,
        ':created': (new Date()).getTime(),
        ':updated': (new Date()).getTime()
    }
};

docClient.update(newCustomerData, function(err, data) {
    if (err) console.log(err);
    else console.log(data);
});
</code>```

答:
Normally, JSON data will be persisted as Map on DynamoDB. If you store JSON array on DynamoDB, it will be stored as "List of Map" data type on DynamoDB which will make it difficult to update, delete, retrieve without knowing the index of the List data type (i.e. device). It is not recommended to use "List of Map" if you need to accomplish update/delete without knowing the index of list (i.e. index of an array).

1) Changed to SET for all attributes including device

To store single JSON object as Map which will allow to update/delete without knowing the index of an array:-

```<code>var params = {
    TableName: process.env.customerMasterFile,
    Key: {
        'email': email
    },
    ReturnValues: 'UPDATED_NEW',
    UpdateExpression: 'SET #device = :device, #customerEmailDomain = :customerEmailDomain ,#friendlyName = :friendlyName, #created = :created, #updated = :updated',
    ExpressionAttributeNames: {
        '#device': 'deviceList',
        '#customerEmailDomain': 'customerEmaiDomain',
        '#friendlyName': 'friendlyName',
        '#created': 'createAccountTime',
        '#updated': 'updateAccountTime',
    },
    ExpressionAttributeValues: {
        ':device': deviceData,
        ':customerEmailDomain': customerEmailDomain,
        ':friendlyName': friendlyName,
        ':created': (new Date()).getTime(),
        ':updated': (new Date()).getTime()
    }
};
</code>```

Sample device as Map:-

Alternate Approach:-

Add device id as sort key of the table

The attributes email and device id forms the unique combination for an item on DynamoDB

You can accomplish the update/delete easily with this data model

Title: Adding JSON array to DynamoDB Item

Body:
I understand that I can create "Lists" only from primitive data types, so look at my (Node.js using AWS Document Client) code as pseudo code.  My objective is to attach a JSON array to an item so that I can later retrieve/update/delete the device (and corresponding data) from the customer's record.  I understand I may be able to use Maps to do this, but I'm a beginner and the documentation regarding how to do that using document client is unclear to me.

This is what I am trying to do:

var deviceData = {
    'deviceID': deviceID,
    'attributes': [
        {'firmwareVersion': firmwareVersion},
        {'productID': productID},
        {'knickName': 'New Device'},
        {'dateAdded': (new Date()).getTime()}
    ]
};

var newCustomerData = {
    TableName: process.env.customerMasterFile,
    Key: {
        'email': email
    },
    ReturnValues: 'UPDATED_NEW',
    UpdateExpression: 'ADD #device :device SET #customerEmailDomain = :customerEmailDomain, #friendlyName = :friendlyName, #created = :created, #updated = :updated',
    ExpressionAttributeNames: {
        '#device': 'deviceList',
        '#customerEmailDomain': 'customerEmaiDomain',
        '#friendlyName': 'friendlyName',
        '#created': 'createAccountTime',
        '#updated': 'updateAccountTime',
    },
    ExpressionAttributeValues: {
        ':device': docClient.createSet([deviceData]),  // I know this is incorrect...
        ':customerEmailDomain': customerEmailDomain,
        ':friendlyName': friendlyName,
        ':created': (new Date()).getTime(),
        ':updated': (new Date()).getTime()
    }
};

docClient.update(newCustomerData, function(err, data) {
    if (err) console.log(err);
    else console.log(data);
});

Body:
Normally, JSON data will be persisted as Map on DynamoDB. If you store JSON array on DynamoDB, it will be stored as "List of Map" data type on DynamoDB which will make it difficult to update, delete, retrieve without knowing the index of the List data type (i.e. device). It is not recommended to use "List of Map" if you need to accomplish update/delete without knowing the index of list (i.e. index of an array).

1) Changed to SET for all attributes including device

To store single JSON object as Map which will allow to update/delete without knowing the index of an array:-

var params = {
    TableName: process.env.customerMasterFile,
    Key: {
        'email': email
    },
    ReturnValues: 'UPDATED_NEW',
    UpdateExpression: 'SET #device = :device, #customerEmailDomain = :customerEmailDomain ,#friendlyName = :friendlyName, #created = :created, #updated = :updated',
    ExpressionAttributeNames: {
        '#device': 'deviceList',
        '#customerEmailDomain': 'customerEmaiDomain',
        '#friendlyName': 'friendlyName',
        '#created': 'createAccountTime',
        '#updated': 'updateAccountTime',
    },
    ExpressionAttributeValues: {
        ':device': deviceData,
        ':customerEmailDomain': customerEmailDomain,
        ':friendlyName': friendlyName,
        ':created': (new Date()).getTime(),
        ':updated': (new Date()).getTime()
    }
};

Sample device as Map:-

Alternate Approach:-

Add device id as sort key of the table

The attributes email and device id forms the unique combination for an item on DynamoDB

You can accomplish the update/delete easily with this data model


问:
Ejabberd mod_muc and mod_muc_room differentiation
Im looking at ejabberd code and realized that there are two modules that left me very confusing.

mod_muc.erl and mod_muc_room.erl. Im not really sure how to differentiate between them. Any inputs or examples as to when each of the modules come to play and what exactly is each one serving. ?

Thanks!

答:
mod_muc serves as muc service for ejabberd server per host.All requests related to room service has to go via mod_muc.

mod_muc_room serves purpose of MUC room(as name suggests).It is a kind of room level abstraction.All operations related to room(joining, leaving, messaging) will be handled by this.mod_muc sends request to mod_muc_room


问:
Convert array of objects into object
This is my object:

```<code>initialState:any = [{'checked':true}, {'checked':false}, {'checked':true}, {'checked':false}, {'checked':true}, {'checked':false}];
</code>```

This is the output that I expect:

```<code>var params = {
    "device0":"true",
    "device1":"true",
    "device2":"false",
    "device3":"true",
    "device4":"false",
    "device5":"true",
    "device6":"false",
    "device7":"true"
}
</code>```

I have an array of objects. I want to take value from an object and want to build single object as mentioned above.

答:
Few records inside the array you provided are different than the result you expect the same as it's length.

var initialState = [{'checked':true},{'checked':false},{'checked':true},{'checked':false},{'checked':true},{'checked':false}],
    params = {};

    initialState.forEach((v,i) => params['device' + i] = v.checked);
    console.log(params);```

Title: Convert array of objects into object

Body:
This is my object:

initialState:any = [{'checked':true}, {'checked':false}, {'checked':true}, {'checked':false}, {'checked':true}, {'checked':false}];

This is the output that I expect:

var params = {
    "device0":"true",
    "device1":"true",
    "device2":"false",
    "device3":"true",
    "device4":"false",
    "device5":"true",
    "device6":"false",
    "device7":"true"
}

I have an array of objects. I want to take value from an object and want to build single object as mentioned above.


问:
Why does Smalltalk support first class functions, but not other functional features?
An answer to Is Javascript a Functional Programming Language? said that:

Functional programming means that the program is conceptualized as a evaluation of a function, rather than a control flow. The code is a description of functions, and has no inherent concept of a control flow.

I've learnt that when a language supported first class functions, and had no control flows, from its design objective, it must be defined as a functional language.

So why does Smalltalk, a functional language, not support other functional features, such as immutability, algebraic data types, pattern matching, partial application?

答:
Smalltalk was designed on top of the following features provided by the Virtual Machine

Object allocation: The #basicNew and #basicNew: primitives

Automatic deallocation: The GC

Message sends: The send family of bytecodes

Blocks: The [:arg | ...] syntax (see below)

Non-local returns: The [:arg | ... ^result] syntax

Late binding: The method lookup mechanism

Native code compilation: The interpreter (see below)

Modern implementations added

Block Closures: Which replaced blocks

Fast compilation: The JIT compiler, which replaced the interpreter

Stack unwind: The #ensure: message

Note that other "features" such as the Smalltalk Compiler, the Debugger or the Exception mechanism are not in the list because they can be derived from others (i.e., they are implemented in user code.)

These features where identified as the fundamental building blocks for a general purpose Object Oriented environment meant to run on the bare metal (i.e. with no Operating System support.)

What the designers had in mind wasn't Functional Programming. Instead they had in mind the every thing is an object and every computation is a message send uniform metaphor. To this end, blocks and non-local returns played the role of modeling "functions" as objects too so to make sure that every known concept got included in the OO paradigm. This doesn't mean that they had functional programming as a goal. They didn't include other features (functional or not) because they were trying to identify a minimal set of primitive elements that would support a general purpose system with no hindrances.


问:
Handling pthread_cond_wait in subprocess.Popen
I have a c code which is using pthread and specifically pthread_cond_wait. My problem is that if I am calling this c executable from my python code using subprocess.Popen it's not working correctly, it looks like it's buffering data instead of printing in real time. Following is my c code:

```<code>#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <pthread.h>
#include "linux_nfc_api.h"

pthread_cond_t condition = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

nfcTagCallback_t g_TagCB;
nfc_tag_info_t g_tagInfos;

void onTagArrival(nfc_tag_info_t *pTagInfo){
    printf("Tag detected\n");
    int i = 0;
    for(i = 0x00; i < (*pTagInfo).uid_length; i++){
        printf("%02X ", (unsigned char) (*pTagInfo).uid[i]);
    }
    g_tagInfos = *pTagInfo;
    pthread_cond_signal(&condition);
}

void onTagDeparture(void){
    printf("Tag removed\n");
}

int main(int argc, char ** argv) {
    g_TagCB.onTagArrival = onTagArrival;
    g_TagCB.onTagDeparture = onTagDeparture;
    nfcManager_doInitialize();
    nfcManager_registerTagCallback(&g_TagCB);
    nfcManager_enableDiscovery(DEFAULT_NFA_TECH_MASK, 0x01, 0, 0);

    unsigned char page = 0x00;
    int i;
    int res = 0x00;
    unsigned char cmd_send[3] = {0x02, 0x20, 0x00};
    unsigned char cmd_response[255];
    printf("Waiting for tag...\n");
    do{
        pthread_cond_wait(&condition, &mutex); //problem

        memset(cmd_response, 0x00, 255);

        printf("SEND APDU: ");
        for(i=0; i < sizeof(cmd_send); i++){
            printf("%02X ",cmd_send[i]);
        }

        res = nfcTag_transceive(g_tagInfos.handle, cmd_send, 3, cmd_response, 255, 500);
        printf("RECV APDU (%d): ",res);
        for(i=0; i<res; i++){
            printf("%02X ",cmd_response[i]);
        }
    }while(1);
    nfcManager_doDeinitialize();
}
</code>```

I found out that problem is due to pthread_cond_wait. My python keeps on buffering and it prints all data after python program is closed instead of real time. Following is my python code:

```<code>import sys
from subprocess import Popen, PIPE, call

proc = Popen(['App'], stdout=PIPE)
for line in iter(proc.stdout.readline, ''):
    print line
</code>```

Thus is there any way to handle this situation considering the fact I will not be able to change my c code?

答:
Try:

```<code>import sys
from subprocess import Popen, PIPE, call

proc = Popen(['App'], stdout=PIPE, stderr=PIPE)
output, errors = proc.communicate()
print output.decode()
</code>```

Why:

See python docs:

Warning - Use communicate() rather than .stdin.write, .stdout.read or
  .stderr.read to avoid deadlocks due to any of the other OS pipe
  buffers filling up and blocking the child process.

Body:
I have a c code which is using pthread and specifically pthread_cond_wait. My problem is that if I am calling this c executable from my python code using subprocess.Popen it's not working correctly, it looks like it's buffering data instead of printing in real time. Following is my c code:

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <pthread.h>
#include "linux_nfc_api.h"

pthread_cond_t condition = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

nfcTagCallback_t g_TagCB;
nfc_tag_info_t g_tagInfos;

void onTagArrival(nfc_tag_info_t *pTagInfo){
    printf("Tag detected\n");
    int i = 0;
    for(i = 0x00; i < (*pTagInfo).uid_length; i++){
        printf("%02X ", (unsigned char) (*pTagInfo).uid[i]);
    }
    g_tagInfos = *pTagInfo;
    pthread_cond_signal(&condition);
}

void onTagDeparture(void){
    printf("Tag removed\n");
}

int main(int argc, char ** argv) {
    g_TagCB.onTagArrival = onTagArrival;
    g_TagCB.onTagDeparture = onTagDeparture;
    nfcManager_doInitialize();
    nfcManager_registerTagCallback(&g_TagCB);
    nfcManager_enableDiscovery(DEFAULT_NFA_TECH_MASK, 0x01, 0, 0);

    unsigned char page = 0x00;
    int i;
    int res = 0x00;
    unsigned char cmd_send[3] = {0x02, 0x20, 0x00};
    unsigned char cmd_response[255];
    printf("Waiting for tag...\n");
    do{
        pthread_cond_wait(&condition, &mutex); //problem

        memset(cmd_response, 0x00, 255);

        printf("SEND APDU: ");
        for(i=0; i < sizeof(cmd_send); i++){
            printf("%02X ",cmd_send[i]);
        }

        res = nfcTag_transceive(g_tagInfos.handle, cmd_send, 3, cmd_response, 255, 500);
        printf("RECV APDU (%d): ",res);
        for(i=0; i<res; i++){
            printf("%02X ",cmd_response[i]);
        }
    }while(1);
    nfcManager_doDeinitialize();
}

I found out that problem is due to pthread_cond_wait. My python keeps on buffering and it prints all data after python program is closed instead of real time. Following is my python code:

import sys
from subprocess import Popen, PIPE, call

proc = Popen(['App'], stdout=PIPE)
for line in iter(proc.stdout.readline, ''):
    print line

Thus is there any way to handle this situation considering the fact I will not be able to change my c code?

Body:
Try:

import sys
from subprocess import Popen, PIPE, call

proc = Popen(['App'], stdout=PIPE, stderr=PIPE)
output, errors = proc.communicate()
print output.decode()

Why:

See python docs:

Warning - Use communicate() rather than .stdin.write, .stdout.read or
  .stderr.read to avoid deadlocks due to any of the other OS pipe
  buffers filling up and blocking the child process.


问:
Move scrollview to original state
I want to move up the view when the keyboard appears and move the view back when the keyboard disappears. I use an scrollview for this.

I have this almost working. The bug that I have is this:

You trigger the keyboard to show

You trigger the keyboard to hide

Things are going great so far.

You trigger the keyboard to show

You trigger the keyboard to hide <-- This doesn't work anymore, but the first time it works perfectly.

The code when the keyboard shows up (this works overtime):

```<code>func keyboardWasShown(notification: NSNotification) {
    var userInfo = notification.userInfo!
    let keyboardFrame:CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
    let buttonOrigin: CGPoint = btn.frame.origin
    let buttonHeight: CGFloat = btn.frame.size.height
    var visibleRect: CGRect = view.frame

    visibleRect.size.height -= keyboardFrame.size.height
    if !visibleRect.contains(buttonOrigin) {
        let scrollPoint = CGPoint(x: CGFloat(0.0), y: CGFloat(buttonOrigin.y - visibleRect.size.height + (buttonHeight + 8)))
        scrollView.setContentOffset(scrollPoint, animated: true)
    }
}
</code>```

The code when the keyboard is going to hide (This code works the first time, it doesn't work the second time):

```<code>func keyboardWillBeHidden(notification: NSNotification){
    var info = notification.userInfo!
    let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size

    let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, -keyboardSize!.height, 0.0)

    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets
    self.view.endEditing(true)
    self.scrollView.isScrollEnabled = false
}
</code>```

This is how my view looks like:

Everything needs to move up when the keyboard is showing. Moving up works:

But when the keyboard disappears it doesn't work:

答:
I would not bother to scroll the scrollview, but instead move the scrollview itself.

Get the outlet of the scrollview bottom constraint, and, supposing the scrollview is fullscreen, set the  constraint to zero when  the keyboard is hidden, and then set it to the keyboard height (correct value is in the notification of keyboardwillshow).

Pseudo code looks like this :

```<code>func keyboardWillShow(notification: NSNotification) {
    self.scrollviewBottomConstraint.constant = notification.keyboardheight;
    self.layoutifneeded(); //I suggest you put this in a 0.3 second animation block
}

func keyboardWillHide(notification: NSNotification) {
    self.scrollviewBottomConstraint.constant = 0;
    self.layoutIfNeeded(); //I suggest you put this in a 0.3 second animation block
}
</code>```

Title: Move scrollview to original state

Body:
I want to move up the view when the keyboard appears and move the view back when the keyboard disappears. I use an scrollview for this.

I have this almost working. The bug that I have is this:

You trigger the keyboard to show

You trigger the keyboard to hide

Things are going great so far.

You trigger the keyboard to show

You trigger the keyboard to hide <-- This doesn't work anymore, but the first time it works perfectly.

The code when the keyboard shows up (this works overtime):

func keyboardWasShown(notification: NSNotification) {
    var userInfo = notification.userInfo!
    let keyboardFrame:CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
    let buttonOrigin: CGPoint = btn.frame.origin
    let buttonHeight: CGFloat = btn.frame.size.height
    var visibleRect: CGRect = view.frame

    visibleRect.size.height -= keyboardFrame.size.height
    if !visibleRect.contains(buttonOrigin) {
        let scrollPoint = CGPoint(x: CGFloat(0.0), y: CGFloat(buttonOrigin.y - visibleRect.size.height + (buttonHeight + 8)))
        scrollView.setContentOffset(scrollPoint, animated: true)
    }
}

The code when the keyboard is going to hide (This code works the first time, it doesn't work the second time):

func keyboardWillBeHidden(notification: NSNotification){
    var info = notification.userInfo!
    let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size

    let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, -keyboardSize!.height, 0.0)

    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets
    self.view.endEditing(true)
    self.scrollView.isScrollEnabled = false
}

This is how my view looks like:

Everything needs to move up when the keyboard is showing. Moving up works:

But when the keyboard disappears it doesn't work:

Body:
I would not bother to scroll the scrollview, but instead move the scrollview itself.

Get the outlet of the scrollview bottom constraint, and, supposing the scrollview is fullscreen, set the  constraint to zero when  the keyboard is hidden, and then set it to the keyboard height (correct value is in the notification of keyboardwillshow).

Pseudo code looks like this :

func keyboardWillShow(notification: NSNotification) {
    self.scrollviewBottomConstraint.constant = notification.keyboardheight;
    self.layoutifneeded(); //I suggest you put this in a 0.3 second animation block
}

func keyboardWillHide(notification: NSNotification) {
    self.scrollviewBottomConstraint.constant = 0;
    self.layoutIfNeeded(); //I suggest you put this in a 0.3 second animation block
}


问:
React-Native-Router-Flux - Left align title on Android
I'm using React-native-router-flux for an Android app, and by default the title seems to be centered. How can I left align it instead so it looks the way a Native Android Toolbar looks?

Thank you!

答:
You can override the renderBackButton function in your Router to show the title instead of the back button. Something like this:

```<code>class Router extends React.Component {
  renderTitle = (props) => {
    return <Text style={...}>{props.leftTitle}</Text>
  };

  render() {
    return (
      <Router>
        <Scene key="myScene" leftTitle="My Title" renderBackButton={this.renderTitle} />
      </Router>
    );
  }
}
</code>```

I don't specify the title props so the scene won't render a title in the middle. Instead, I use my own leftTitle prop.

Body:
You can override the renderBackButton function in your Router to show the title instead of the back button. Something like this:

class Router extends React.Component {
  renderTitle = (props) => {
    return <Text style={...}>{props.leftTitle}</Text>
  };

  render() {
    return (
      <Router>
        <Scene key="myScene" leftTitle="My Title" renderBackButton={this.renderTitle} />
      </Router>
    );
  }
}

I don't specify the title props so the scene won't render a title in the middle. Instead, I use my own leftTitle prop.


问:
Adding a Git subrepository to Mercurial
I've been trying to set up a project using bitbucket which has project dependencies hosted on github. Using the Hg-Git Mercurial plugin I am able to almost get there.

But when it comes time to push, things become troublesome.

The documentation for Mercurial subrepositories states:

2.4 Push

Mercurial will automatically attempt to first push all subrepos of the current repository when you push. This will ensure new changesets in subrepos are available when referenced by top-level repositories.

But this causes a big issue since I don't want to push all the subrepositories (why would I?) — I only have read access to them, so github won't allow it. Only the main repository needs to be pushed to the remote server, but I can't figure out how to do it. hg wants to take control and push all subrepositories, regardless of whether or not there are changes. Is there some way to bypass this feature?

The only things which need to be pushed are .hgsub and .hgsubstate. Once they've been pushed via alternative routes (updating to a changeset where the subrepositories don't exist), it's possible to then update and pull the changes from the remote repositories, but if I were to push again whilst on a changeset with the subrepositories, the whole ordeal repeats itself.

答: For future reference, the development branch of mercurial (and thus the upcoming 1.8 release) now supports native git subrepos. This particular case is implemented very nicely and a push from the root repository will only tell the git subrepo to push if its remote repository is not known to have the current commit.</p>

Title: Adding a Git subrepository to Mercurial


问:
why i can't extends SimpleSwingGUIApplication?
i need to extends SimpleSwingGUIApplication for my GUI application but i have an error :
not found : type SimpleSwingGUIApplication

there is my code :

import scala.swing._

class GUI extends SimpleSwingGUIApplication{}
thanks for your answer :)

答:
It's not in the standard Scala libraries:

http://www.scala-lang.org/api/current/?search=SimpleSwingGUIApplication

...and if you try Googling it, it's not anywhere.  Spelling error?


问:
Using 'goto' to move from if to else
I know that there's no goto in java, but I ask on general if there are a method to goto from if to else
example :

```<code>public void decToAsci(String decimal) {
    String nb = "";
    int number;
    for (int i = 0; i < decimal.length(); i++) {
        Character c = decimal.charAt(i);
        if (!c.equals(' ')) {
            nb += decimal.charAt(i);
            if (i == decimal.length() - 1)
                //here i want to jump to else
                // i can do it like this :
                // System.out.print( (char) Integer.parseInt(nb) + " ");
                // but i repeat code in else here ..i just want to jump to else
        } else {
            number = Integer.parseInt(nb);
            System.out.print((char) number + " ");
            nb = "";
            number = 0;
        }
    }
}
</code>```

I try this :

```<code>if (!c.equals(' ')) {
    nb += decimal.charAt(i);
    if (i == decimal.length() - 1) continue label;
} else {
    label: the code in else
}
</code>```

But not worked, not worked with break label also. I understand that continue, break. Are used between son and parent like that? :

```<code>label:
for(int i=0 ; i<n ; i++)
    if (cond) break label;
</code>```

I ask about a method that can jump from if to else (2 sons)

(not a son and a parent but jumping between 2 sons )

I think even with goto on c and c++ 4 example we can't do it

答:
Java does not have goto. But, if I understand you, you might use a switch, the default behavior is fall-through so something like

```<code>int number;
for(int i=0 ; i<decimal.length() ; i++ )
{
    Character c = decimal.charAt(i);
    switch (c) {
    default: // <-- c is not ' '
         nb += decimal.charAt(i);
         if (i != decimal.length() - 1) {
             break;
         }
         // i == decimal.length() - 1, fall-through
    case ' ': // <-- c is ' ', or it fell through
        number = Integer.parseInt(nb);
        System.out.print( (char) number + " ");
        nb = "";
        number = 0;
    }
}
</code>```

Title: Using 'goto' to move from if to else

Body:
I know that there's no goto in java, but I ask on general if there are a method to goto from if to else
example :

public void decToAsci(String decimal) {
    String nb = "";
    int number;
    for (int i = 0; i < decimal.length(); i++) {
        Character c = decimal.charAt(i);
        if (!c.equals(' ')) {
            nb += decimal.charAt(i);
            if (i == decimal.length() - 1)
                //here i want to jump to else
                // i can do it like this :
                // System.out.print( (char) Integer.parseInt(nb) + " ");
                // but i repeat code in else here ..i just want to jump to else
        } else {
            number = Integer.parseInt(nb);
            System.out.print((char) number + " ");
            nb = "";
            number = 0;
        }
    }
}

I try this :

if (!c.equals(' ')) {
    nb += decimal.charAt(i);
    if (i == decimal.length() - 1) continue label;
} else {
    label: the code in else
}

But not worked, not worked with break label also. I understand that continue, break. Are used between son and parent like that? :

label:
for(int i=0 ; i<n ; i++)
    if (cond) break label;

I ask about a method that can jump from if to else (2 sons)

(not a son and a parent but jumping between 2 sons )

I think even with goto on c and c++ 4 example we can't do it

Body:
Java does not have goto. But, if I understand you, you might use a switch, the default behavior is fall-through so something like

int number;
for(int i=0 ; i<decimal.length() ; i++ )
{
    Character c = decimal.charAt(i);
    switch (c) {
    default: // <-- c is not ' '
         nb += decimal.charAt(i);
         if (i != decimal.length() - 1) {
             break;
         }
         // i == decimal.length() - 1, fall-through
    case ' ': // <-- c is ' ', or it fell through
        number = Integer.parseInt(nb);
        System.out.print( (char) number + " ");
        nb = "";
        number = 0;
    }
}


问:
find names of table who is in the same department sql
I was asked during an interview about this SQL question.

Given Employee table

LastName    DepartmentID
Rafferty    31
Jones       33
Heisenberg  33
Robinson    34
Smith       34
Daniel      34
Williams    NULL
```

<p>and Department table</p>

<pre class="lang-none prettyprint-override"><code>DepartmentID    DepartmentName
31              Sales
33              Engineering
34              Clerical
35              Marketing
</code>```

How could I find ALL of the employees who is at the same department as 'Robinson'? (through a generic way)

Is join (inner join) something that he wanted me to do?

答:
You can use IN:

```<code>select *
from employee
where departmentId in (
        select departmentId
        from employee
        where LastName = 'Robinson'
        );
</code>```

Using JOIN:

```<code>select e.*
from employee e
join (
    select distinct departmentId
    from employee
    where LastName = 'Robinson'
    ) e2 on e1.departmentId = e2.departmentId;
</code>```

Body:
I was asked during an interview about this SQL question.

Given Employee table

LastName    DepartmentID
Rafferty    31
Jones       33
Heisenberg  33
Robinson    34
Smith       34
Daniel      34
Williams    NULL

and Department table

DepartmentID    DepartmentName
31              Sales
33              Engineering
34              Clerical
35              Marketing

How could I find ALL of the employees who is at the same department as 'Robinson'? (through a generic way)

Is join (inner join) something that he wanted me to do?

Body:
You can use IN:

select *
from employee
where departmentId in (
        select departmentId
        from employee
        where LastName = 'Robinson'
        );

Using JOIN:

select e.*
from employee e
join (
    select distinct departmentId
    from employee
    where LastName = 'Robinson'
    ) e2 on e1.departmentId = e2.departmentId;


问:
Cant start onlyoffice-document server without docker?
I had installed onlyoffice document server on my ubuntu 14.04 machine but after I restarted the server all the applications of onlyoffice shutdown and I am not able to restart them. It currently shows 502 gateway error.</p>

答:
Possible reason - problem with supervisor, but that problem was on Ubuntu 16.04 with systemd
It was solved via

```<code># Make sure Supervisor comes up after a reboot.
sudo systemctl enable supervisor

# Bring Supervisor up right now.
sudo systemctl start supervisor
</code>```

See https://github.com/ONLYOFFICE/DocumentServer/issues/77

Body:
Possible reason - problem with supervisor, but that problem was on Ubuntu 16.04 with systemd
It was solved via

# Make sure Supervisor comes up after a reboot.
sudo systemctl enable supervisor

# Bring Supervisor up right now.
sudo systemctl start supervisor

See https://github.com/ONLYOFFICE/DocumentServer/issues/77


问:
How to sort posts on Wordpress search page
I'm building a site search page using WPSOLR and need to have a form that allows users to choose to sort search results by either ascending or descending alphabetical order. I am looking into writing a filter to serve this purpose but could use some general guidance on the topic. Has anyone done something like this before with Wordpress? Thanks in advance.</p>

答:
If your field name is 'field1', just use the parameter:
&wpsolr_sort=field1_str_asc
or
&wpsolr_sort=field1_str_desc

Some fields are predefined and come with the plugin. You can see them when you setup the sorts in the wpsolr admin.

You also have predefined filters to modify the Solarium query as you wish (without using parameters if you want to do it silently). This filter contains an example to add 3 sorts:
https://www.wpsolr.com/guide-category/actions-and-filters/#2787