问:
Angularjs checkbox checked onload but gives undefined when unchecked first time inside nested ng-repeat
I am using AngularJS, Ionic (v 1) frameworks. On load of the mobile app screen, the checkboxes are to displayed as checked & then user may check or uncheck the checkboxes. The checkboxes are checked on load fine, however, when first time user unchecks a checkbox then the checkbox status value is undefined even though the checkbox is seen to be unchecked. After this when it is checked then it works fine whereby either the checkbox value is true or false depending upon if user checked it or unchecked it. Below if the html section of the code that is displaying the nested ng-repeat and checkboxes displayed. Also, there are multiple checkboxes that can be displayed and that is why second ng-repeat is used to load all the values for the checkboxes. Below the HTML code is the Javascript functions in controllers.

The togglegroup & isgroupshown functions are used to show or hide the checkboxes when the user clicks on the icon next to Extras.

HTML

```<code><form name="list" class="list">
<div ng-repeat="(i, item) in menu_items track by $index">
<div class="item item-divider">
{{item.p_name}}
</div>
<select ng-show="item.Customizable == 1" ng-model="data.cmbIngredient[i]">
<option selected="selected" value="">Select the size</option>
<option ng-repeat="x in item.ProductSizes" value="{{x}}">
{{x.ProductName}}: €{{x.ProductPrice | number:2}}
</option>
</select>
<div>
{{item.p_description}}
</div>
<!-- if the Extras value equates to 1 then the checkbox is displayed-->
<div ng-show="item.Extras == 1">
<i ng-click="toggleGroup(item)" class="icon balanced icon" ng-class="isGroupShown(item) ? 'ion-minus' : 'ion-plus-round'"></i> Extras
<label ng-repeat="(j, ext) in item.ExtraDetails track by $index" class="checkbox" ng-show="isGroupShown(item)">

<input type="checkbox" ng-checked="1" ng-change="AddExtras(data.data[j].chkextras[i],item.p_id)" ng-model="data.data[j].chkextras[i]"> {{ext.CIngredientName}}

</label>
</div>
</div>
</form>
</code>```

Controller functions

```<code>$scope.AddExtras=function(extraStatus,pid){
if(extraStatus == true){
    //pass it to service
}
else if (extraStatus == false){
    //pass it to a service
}
};
$scope.toggleGroup = function(group) {
if ($scope.isGroupShown(group)) {
$scope.shownGroup = null;
} else {
$scope.shownGroup = group;
}
};
$scope.isGroupShown = function(group) {
return $scope.shownGroup === group;
};
</code>```

答:
You should be looking for something like this.
ng-true/false-value</p>

Body:
I am using AngularJS, Ionic (v 1) frameworks. On load of the mobile app screen, the checkboxes are to displayed as checked & then user may check or uncheck the checkboxes. The checkboxes are checked on load fine, however, when first time user unchecks a checkbox then the checkbox status value is undefined even though the checkbox is seen to be unchecked. After this when it is checked then it works fine whereby either the checkbox value is true or false depending upon if user checked it or unchecked it. Below if the html section of the code that is displaying the nested ng-repeat and checkboxes displayed. Also, there are multiple checkboxes that can be displayed and that is why second ng-repeat is used to load all the values for the checkboxes. Below the HTML code is the Javascript functions in controllers.

The togglegroup & isgroupshown functions are used to show or hide the checkboxes when the user clicks on the icon next to Extras.

HTML

<form name="list" class="list">

{{item.p_name}}

<select ng-show="item.Customizable == 1" ng-model="data.cmbIngredient[i]">
<option selected="selected" value="">Select the size</option>
<option ng-repeat="x in item.ProductSizes" value="{{x}}">
{{x.ProductName}}: €{{x.ProductPrice | number:2}}
</option>
</select>

{{item.p_description}}

 Extras

<input type="checkbox" ng-checked="1" ng-change="AddExtras(data.data[j].chkextras[i],item.p_id)" ng-model="data.data[j].chkextras[i]"> {{ext.CIngredientName}}

</form>

Controller functions

$scope.AddExtras=function(extraStatus,pid){
if(extraStatus == true){
    //pass it to service
}
else if (extraStatus == false){
    //pass it to a service
}
};
$scope.toggleGroup = function(group) {
if ($scope.isGroupShown(group)) {
$scope.shownGroup = null;
} else {
$scope.shownGroup = group;
}
};
$scope.isGroupShown = function(group) {
return $scope.shownGroup === group;
};


来源: stackexchange

问:
VBA EXCEL - Small code optimization for on-worksheet open macro
I am looking to speed up an on-worksheet open macro I have in excel.

Every time the worksheet is opened, I would like it to autofit x rows and then hide any rows that have a 0 in it.

The macro works fine, but I think there must be a better/faster way to hide all relevant rows. Any help would be appreciated.

```<code>Private Sub Worksheet_Activate()
    Rows("14:859").EntireRow.AutoFit
Application.ScreenUpdating = False
Dim c As Range
    For Each c In Range("O1:O859").Cells
        If c.Value = "0" Then
            c.EntireRow.Hidden = True
        End If
    Next c
Application.ScreenUpdating = True
End Sub
</code>```

答:
Try this version:</p>

```<code>Option Explicit

Private Sub Worksheet_Activate()
  Const LAST_ROW = 859
  Const CL = 15             'O column
  Const RO = 14
  Const HIDE_ROWS = True    'or False

  Dim ur As Variant, hr As Range, R As Long

  Application.ScreenUpdating = False

  Rows(RO & ":" & LAST_ROW).EntireRow.AutoFit

  ur = Range(Cells(1, CL), Cells(LAST_ROW, CL))
  For R = 1 To LAST_ROW
    If Len(ur(R, 1)) = 0 Then Exit For
    If ur(R, 1) = 0 Then
        If hr Is Nothing Then Set hr = Cells(R, 1) Else: Set hr = Union(hr, Cells(R, 1))
    End If
  Next
  hr.EntireRow.Hidden = HIDE_ROWS

  Application.ScreenUpdating = True
End Sub
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am looking to speed up an on-worksheet open macro I have in excel.

Every time the worksheet is opened, I would like it to autofit x rows and then hide any rows that have a 0 in it.

The macro works fine, but I think there must be a better/faster way to hide all relevant rows. Any help would be appreciated.

Private Sub Worksheet_Activate()
    Rows("14:859").EntireRow.AutoFit
Application.ScreenUpdating = False
Dim c As Range
    For Each c In Range("O1:O859").Cells
        If c.Value = "0" Then
            c.EntireRow.Hidden = True
        End If
    Next c
Application.ScreenUpdating = True
End Sub

Body:
Try this version:

Option Explicit

Private Sub Worksheet_Activate()
  Const LAST_ROW = 859
  Const CL = 15             'O column
  Const RO = 14
  Const HIDE_ROWS = True    'or False

  Dim ur As Variant, hr As Range, R As Long

  Application.ScreenUpdating = False

  Rows(RO & ":" & LAST_ROW).EntireRow.AutoFit

  ur = Range(Cells(1, CL), Cells(LAST_ROW, CL))
  For R = 1 To LAST_ROW
    If Len(ur(R, 1)) = 0 Then Exit For
    If ur(R, 1) = 0 Then
        If hr Is Nothing Then Set hr = Cells(R, 1) Else: Set hr = Union(hr, Cells(R, 1))
    End If
  Next
  hr.EntireRow.Hidden = HIDE_ROWS

  Application.ScreenUpdating = True
End Sub


问:
REST Client for Ruby Gives ActionController::InvalidAuthenticityToken
I have a RESTful Rails application with a resource called "Foo". I'm trying to use REST Client to do a put:

```<code>resource = RestClient::Resource.new 'http://localhost:3000/foos/1', :user => 'me', :password => 'secret'
resource.put :name => 'somethingwitty', :content_type => 'application/xml'
</code>```

But my app raises:

```<code>ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):
/usr/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/request_forgery_protection.rb:86:in `verify_authenticity_token'
</code>```

It seems like my app isn't getting the message that this is an XML request and that the AuthenticityToken should be ignored. Maybe I'm not using REST Client correctly. Any ideas on why I'm getting the exception?

答:
Since your application is a Rails app, it might be easier to use ActiveResource for the client.

Something like:

```<code>require 'active_resource'

class Foo < ActiveResource::Base
  self.site = 'http://localhost:3000/'
end

foo = Foo.new(:name => 'somethingwitty')
foo.save
</code>```

You can read up on how to do the authentication on the rdoc site.

ContentLicense: CC BY-SA 2.5

Body:
I have a RESTful Rails application with a resource called "Foo". I'm trying to use REST Client to do a put:

resource = RestClient::Resource.new 'http://localhost:3000/foos/1', :user => 'me', :password => 'secret'
resource.put :name => 'somethingwitty', :content_type => 'application/xml'

But my app raises:

ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):
/usr/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/request_forgery_protection.rb:86:in `verify_authenticity_token'

It seems like my app isn't getting the message that this is an XML request and that the AuthenticityToken should be ignored. Maybe I'm not using REST Client correctly. Any ideas on why I'm getting the exception?

Body:
Since your application is a Rails app, it might be easier to use ActiveResource for the client.

Something like:

require 'active_resource'

class Foo < ActiveResource::Base
  self.site = 'http://localhost:3000/'
end

foo = Foo.new(:name => 'somethingwitty')
foo.save

You can read up on how to do the authentication on the rdoc site.


问:
How do I get my CSS grid centered?
I am just trying to figure out how to position this grid on the page - I am getting this white space on the left and underneath, not sure where from. I am including a lot of the CSS and relevant grid code. There's also an external stylesheet that might have something on it that's making it do this, but I have gone over it and don't think so. Anyone know what might be causing this? Did I design the grid incorrectly and somehow skip to the second column, or is this margin space? Just trying to get grid somewhat centered, with an even margin around it. Sorry if I do something wrong format-wise or posted too much code - haven't posted in a while (also running on four hours of sleep). Thanks.

How it looks

```<code><style>

html {
  overflow: hidden;
  height: 100%;
}

p {
  text-indent: 50px;
  font-size: 200px;
  color: white;
  font-family:'y14.5m-20092009';
}

body {
  -webkit-font-smoothing: antialiased;
   background-color: white;
   overflow: auto;
   margin: 0px;
}

div#furtheroptions {
  font-size: 30px;
  color: white;
}

.hidden {
  display: none;
}

div#fixedfooter {
  position:fixed;
  bottom:0px;
  left:0px;
  width:100%;
  color: #ba2337;
  background:#333;
  padding:8px;
  font-family:'y14.5m-20092009';
  font-size: 20px;
  text-align: center;
}

input[type=text] {
    width: 400px;
    box-sizing: border-box;
    border: 2px solid #ccc;
    border-radius: 4px;
    font-size: 16px;
    background-color: white;
    background-image: url('searchicon.png');
    background-position: 10px 10px;
    background-repeat: no-repeat;
    padding: 12px 20px 12px 40px;
    -webkit-transition: width 0.4s ease-in-out;
    transition: width 0.4s ease-in-out;
    color: #ba2337;
}

button {
  text-align: center;
  border: 1px solid white !important;
  border-radius: 5px;
  outline: none; /*keeps blue selection border off*/
}

.navigationbuttons {
  display: grid;
  grid-gap: 10px;
  background-color: white;
  color: #ba2337;
  width: 100%;
  font-family:'y14.5m-20092009';
  margin-right: 100px;
}

    .box {
      background-color: #ba2337;
      color: #fff;
      border-radius: 5px;
      padding: 20px;
      font-size: 150%;
    }
    .a {
        grid-column: col / span 4;
        grid-row: row / span 3;
    }
    .b {
        grid-column: col / span 4;
        grid-row: row 4 / span 3;
    }
    .c {
        grid-column: col / span 1;
        grid-row: row 7;
    }
    .d {
        grid-column: col 2 / span 2;
        grid-row: row 7;
    }
    .e {
        grid-column: col 4;
        grid-row: row 7;
    }
    .f {
        grid-column: col / span 1;
        grid-row: row 8 / span 1;
    }
    .g {
        grid-column: col 2/ span 2;
        grid-row: row 8 / span 1;
    }
    .h {
        grid-column: col 4 /span 1;
        grid-row: row 8 / span 1;
    }
    .i {
        grid-column: col 1/ span 2;
        grid-row: row 9 / span 3;
    }
    .j {
        grid-column: col 3 /span 2;
        grid-row: row 9 / span 3;
    }

</style>

</head>

<body>
<form>
<div class="navigationbuttons">
<div class="box a">A</div>
<div class="box b"><font size=300px>B</font></div>
<div class="box c">C</div>
<div class="box d"><font size=5>D</font></div>
<div class="box e">E</div>
<div class="box f">F</div>
<div class="box g" style="text-align: center"><input type="text" name="search"  placeholder="Search.."></div>
<div class="box h"><button type="button" class="button" onclick="location.href = 'http://www.google.com';"</button>Button 1</div>
<div class="box i"><button type="button" class="button" onclick="location.href = 'http://www.google.com';"</button>Button 2</div>
<div class="box j"><button type="button" class="button" onclick="location.href = 'http://www.google.com';"</button>Button 3</div>
</form>
</div>
</code>```

答:
First of all, if that is your code, you have quite a lot of unclosed HTML tags.

Then if you want the grid centered in the page the easiest thing to do is to give a class to the container of the grid (the form tag in this case, but you can also create a new one just under the form) and give it these rules:

```<code>.centeredGrid {
    display: table;
    margin: auto;
}
</code>```

A working example is here

The size is depending on the input field width that in your case is 400px.

The complete code (fixed also with the closed HTML tags) is here

You can also use display: flex instead of table, but remember that flexbox is not supported in IE9 and lower and for IE10 and IE11 you have to use the vendor prefix.

Title: How do I get my CSS grid centered?

Body:
I am just trying to figure out how to position this grid on the page - I am getting this white space on the left and underneath, not sure where from. I am including a lot of the CSS and relevant grid code. There's also an external stylesheet that might have something on it that's making it do this, but I have gone over it and don't think so. Anyone know what might be causing this? Did I design the grid incorrectly and somehow skip to the second column, or is this margin space? Just trying to get grid somewhat centered, with an even margin around it. Sorry if I do something wrong format-wise or posted too much code - haven't posted in a while (also running on four hours of sleep). Thanks.

How it looks

<form>

A

B

C

D

E

F

<input type="text" name="search"  placeholder="Search..">

<button type="button" class="button" onclick="location.href = 'http://www.google.com';"</button>Button 1

<button type="button" class="button" onclick="location.href = 'http://www.google.com';"</button>Button 2

<button type="button" class="button" onclick="location.href = 'http://www.google.com';"</button>Button 3

</form>

Body:
First of all, if that is your code, you have quite a lot of unclosed HTML tags.

Then if you want the grid centered in the page the easiest thing to do is to give a class to the container of the grid (the form tag in this case, but you can also create a new one just under the form) and give it these rules:

.centeredGrid {
    display: table;
    margin: auto;
}

A working example is here

The size is depending on the input field width that in your case is 400px.

The complete code (fixed also with the closed HTML tags) is here

You can also use display: flex instead of table, but remember that flexbox is not supported in IE9 and lower and for IE10 and IE11 you have to use the vendor prefix.


问:
Xamarin Forms Layout create overlapping views
I am trying to create an Autocomplete control in Xamarin.Forms, so far I have created a ContentView with following Xaml.

```<code><ContentView.Content>
        <AbsoluteLayout BackgroundColor="Red" x:Name="absLayout" HeightRequest="30">
            <Entry BackgroundColor="Green" x:Name="entryView" AbsoluteLayout.LayoutBounds="1,1,1,1" AbsoluteLayout.LayoutFlags="All" Focused="Handle_Focused" Unfocused="Handle_Unfocused"/>
            <ListView BackgroundColor="Blue" Margin="0,30,0,0" IsVisible="false" x:Name="listView" HeightRequest="200">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <TextCell Text="{Binding .}" />
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </AbsoluteLayout>
    </ContentView.Content>
</code>```

This will be used on ContentPage, along with other Entry and Label controls.

When someone clicks on Entry then, corresponding ListView must be shown to user just below the Entry, by overlapping other controls, instead of pushing down other controls below it.

I have achieved overlapping of controls, but not correctly. ListView does shows list to user but other controls overlap it. ListView gets a lower Z-Index and other controls get higher Z-Index.

Need help to fix this.

Edit 1-

Screens for what I want to achieve. (This a Spinner control in Android)

I want to do something similar with my control.

PS - follow this SO answer for root cause this behaviour.

答:
I had the exact same problem and I fixed it using a custom renderer. This lets the user type to filter the list choices and then puts the selected choice in the entry when the user picks one. In your forms project you'll want a new subclass of entry:

```<code>public class AutofillTextView : Entry
{
    public static BindableProperty ChoicesSourceProperty = BindableProperty.Create(
            nameof(ChoicesSource), typeof(ObservableCollection<string>), typeof(CustomPicker),
            default(ObservableCollection<string>), propertyChanged: OnChoicesSourceChanged);

    public ObservableCollection<string> ChoicesSource
    {
        get { return (ObservableCollection<string>)GetValue(ChoicesSourceProperty); }
        set { SetValue(ChoicesSourceProperty, value); }
    }
    public AutofillTextView()
    {
        Items = new List<string>();
    }

    private void ChoicesChanged(object sender, NotifyCollectionChangedEventArgs args)
    {
        switch (args.Action)
        {
            case NotifyCollectionChangedAction.Add:
                Items.Add(args.NewItems[0]);
                break;

            default:
                var itemsList = ChoicesSource.ToList();
                Items = itemsList;
                break;
        }
        OnPropertyChanged(nameof(Items));
    }

    private static void OnChoicesSourceChanged(BindableObject bindable, object oldValue, object newValue)
    {
        var textView = (AutofillTextView) bindable;
        textView.ChoicesSource.CollectionChanged -= textView.ChoicesChanged;
        textView.ChoicesSource.CollectionChanged += textView.ChoicesChanged;
        textView.Items = newValue == null ? new List<string>() : ((ObservableCollection<string>)newValue).ToList();
    }
}
</code>```

You might need to expand on this, but I never remove items from the list so the switch was good enough for me. I needed to use observable collection as well, so you can simplify by switching to list. Anyway, next you need your custom renderer in droid:

```<code>[assembly: ExportRenderer(typeof(AutofillTextView), typeof(AutofillTextViewRenderer))]

namespace Default
{
    public class AutofillTextViewRenderer : ViewRenderer<AutofillTextView, InstantAutoCompleteTextView>
    {
        protected override void OnElementChanged(ElementChangedEventArgs<AutofillTextView> e)
        {
            base.OnElementChanged(e);

            if (Control == null)
            {
                var control = new InstantAutoCompleteTextView(Forms.Context);

                control.InputType = Android.Text.InputTypes.ClassText | Android.Text.InputTypes.TextFlagNoSuggestions;
                control.Text = Element.Text;
                SetNativeControl(control);
            }

            if (e.OldElement != null)
            {

            }

            if (e.NewElement != null)
            {
                var adapter = new ArrayAdapter<string>(Forms.Context as Android.App.Activity, Resource.Layout.AutofillTextViewItem, e.NewElement.Items.ToArray<string>());
                Control.Adapter = adapter;
                Control.Threshold = 0;
                Control.TextChanged += Control_TextChanged;
                adapter.NotifyDataSetChanged();
            }
        }

        void Control_TextChanged(object sender, Android.Text.TextChangedEventArgs e)
        {
            if (Element.Text != Control.Text)
            {
                Element.Text = Control.Text;
            }
        }

        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);
            if (e.PropertyName == AutofillTextView.ItemsProperty.PropertyName)
            {
                var adapter = new ArrayAdapter<string>(Forms.Context as Android.App.Activity, Resource.Layout.AutofillTextViewItem, Element.Items.ToArray<string>());
                Control.Adapter = adapter;
                adapter.NotifyDataSetChanged();
            }
            else if(e.PropertyName == AutofillTextView.TextProperty.PropertyName)
            {
                if(Control.Text != Element.Text)
                {
                    Control.Text = Element.Text;
                }
            } else if(e.PropertyName == AutofillTextView.IsFocusedProperty.PropertyName) {
                if(Element.IsFocused)
                    Control.PerformFiltering();
            }
        }

    }
}
</code>```

This will connect your custom class (AutofillTextView) to an android class (InstantAutoCompleteTextView) to replace the default entry renderer. The reason I don't use the built in AutoCompleteTextView is because it won't show the dropdown until you type at least one character. I'd prefer it shown on focus. If you don't care you can skip that. Here's that view:

```<code>public class InstantAutoCompleteTextView : AutoCompleteTextView
{

    public InstantAutoCompleteTextView(Context context) : base(context) {}

    public InstantAutoCompleteTextView(Context arg0, IAttributeSet arg1) : base(arg0, arg1){}

    public InstantAutoCompleteTextView(Context arg0, IAttributeSet arg1, int arg2) : base(arg0, arg1, arg2){}

    public override bool EnoughToFilter() {
        return true;
    }

    public void PerformFiltering()
    {
        PerformFiltering(Text, 0);
    }
}
</code>```

Body:
I am trying to create an Autocomplete control in Xamarin.Forms, so far I have created a ContentView with following Xaml.

<ContentView.Content>
        <AbsoluteLayout BackgroundColor="Red" x:Name="absLayout" HeightRequest="30">
            <Entry BackgroundColor="Green" x:Name="entryView" AbsoluteLayout.LayoutBounds="1,1,1,1" AbsoluteLayout.LayoutFlags="All" Focused="Handle_Focused" Unfocused="Handle_Unfocused"/>
            <ListView BackgroundColor="Blue" Margin="0,30,0,0" IsVisible="false" x:Name="listView" HeightRequest="200">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <TextCell Text="{Binding .}" />
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </AbsoluteLayout>
    </ContentView.Content>

This will be used on ContentPage, along with other Entry and Label controls.

When someone clicks on Entry then, corresponding ListView must be shown to user just below the Entry, by overlapping other controls, instead of pushing down other controls below it.

I have achieved overlapping of controls, but not correctly. ListView does shows list to user but other controls overlap it. ListView gets a lower Z-Index and other controls get higher Z-Index.

Need help to fix this.

Edit 1-

Screens for what I want to achieve. (This a Spinner control in Android)

I want to do something similar with my control.

PS - follow this SO answer for root cause this behaviour.

Body:
I had the exact same problem and I fixed it using a custom renderer. This lets the user type to filter the list choices and then puts the selected choice in the entry when the user picks one. In your forms project you'll want a new subclass of entry:

public class AutofillTextView : Entry
{
    public static BindableProperty ChoicesSourceProperty = BindableProperty.Create(
            nameof(ChoicesSource), typeof(ObservableCollection<string>), typeof(CustomPicker),
            default(ObservableCollection<string>), propertyChanged: OnChoicesSourceChanged);

    public ObservableCollection<string> ChoicesSource
    {
        get { return (ObservableCollection<string>)GetValue(ChoicesSourceProperty); }
        set { SetValue(ChoicesSourceProperty, value); }
    }
    public AutofillTextView()
    {
        Items = new List<string>();
    }

    private void ChoicesChanged(object sender, NotifyCollectionChangedEventArgs args)
    {
        switch (args.Action)
        {
            case NotifyCollectionChangedAction.Add:
                Items.Add(args.NewItems[0]);
                break;

            default:
                var itemsList = ChoicesSource.ToList();
                Items = itemsList;
                break;
        }
        OnPropertyChanged(nameof(Items));
    }

    private static void OnChoicesSourceChanged(BindableObject bindable, object oldValue, object newValue)
    {
        var textView = (AutofillTextView) bindable;
        textView.ChoicesSource.CollectionChanged -= textView.ChoicesChanged;
        textView.ChoicesSource.CollectionChanged += textView.ChoicesChanged;
        textView.Items = newValue == null ? new List<string>() : ((ObservableCollection<string>)newValue).ToList();
    }
}

You might need to expand on this, but I never remove items from the list so the switch was good enough for me. I needed to use observable collection as well, so you can simplify by switching to list. Anyway, next you need your custom renderer in droid:

[assembly: ExportRenderer(typeof(AutofillTextView), typeof(AutofillTextViewRenderer))]

namespace Default
{
    public class AutofillTextViewRenderer : ViewRenderer<AutofillTextView, InstantAutoCompleteTextView>
    {
        protected override void OnElementChanged(ElementChangedEventArgs<AutofillTextView> e)
        {
            base.OnElementChanged(e);

            if (Control == null)
            {
                var control = new InstantAutoCompleteTextView(Forms.Context);

                control.InputType = Android.Text.InputTypes.ClassText | Android.Text.InputTypes.TextFlagNoSuggestions;
                control.Text = Element.Text;
                SetNativeControl(control);
            }

            if (e.OldElement != null)
            {

            }

            if (e.NewElement != null)
            {
                var adapter = new ArrayAdapter<string>(Forms.Context as Android.App.Activity, Resource.Layout.AutofillTextViewItem, e.NewElement.Items.ToArray<string>());
                Control.Adapter = adapter;
                Control.Threshold = 0;
                Control.TextChanged += Control_TextChanged;
                adapter.NotifyDataSetChanged();
            }
        }

        void Control_TextChanged(object sender, Android.Text.TextChangedEventArgs e)
        {
            if (Element.Text != Control.Text)
            {
                Element.Text = Control.Text;
            }
        }

        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);
            if (e.PropertyName == AutofillTextView.ItemsProperty.PropertyName)
            {
                var adapter = new ArrayAdapter<string>(Forms.Context as Android.App.Activity, Resource.Layout.AutofillTextViewItem, Element.Items.ToArray<string>());
                Control.Adapter = adapter;
                adapter.NotifyDataSetChanged();
            }
            else if(e.PropertyName == AutofillTextView.TextProperty.PropertyName)
            {
                if(Control.Text != Element.Text)
                {
                    Control.Text = Element.Text;
                }
            } else if(e.PropertyName == AutofillTextView.IsFocusedProperty.PropertyName) {
                if(Element.IsFocused)
                    Control.PerformFiltering();
            }
        }

    }
}

This will connect your custom class (AutofillTextView) to an android class (InstantAutoCompleteTextView) to replace the default entry renderer. The reason I don't use the built in AutoCompleteTextView is because it won't show the dropdown until you type at least one character. I'd prefer it shown on focus. If you don't care you can skip that. Here's that view:

public class InstantAutoCompleteTextView : AutoCompleteTextView
{

    public InstantAutoCompleteTextView(Context context) : base(context) {}

    public InstantAutoCompleteTextView(Context arg0, IAttributeSet arg1) : base(arg0, arg1){}

    public InstantAutoCompleteTextView(Context arg0, IAttributeSet arg1, int arg2) : base(arg0, arg1, arg2){}

    public override bool EnoughToFilter() {
        return true;
    }

    public void PerformFiltering()
    {
        PerformFiltering(Text, 0);
    }
}


问:
Python Dataframe Single Row with Label
```<code>import pandas as pd
data = ["X", "Y", "Z", "A", "B"]
label = ['a','b','c','d','e']
df = pd.DataFrame(data, columns=label)
print(df)
</code>```

I want to get the dataframe to be:

```<code>a b c d e
X Y Z A B
</code>```

I am getting

```<code>ValueError: Shape of passed values is (1, 5), indices imply (5, 5)
</code>```

How to fix this to get the desired dataframe ?

答:
You can use a bit complicated, but very fast solution if large data - convert list to numpy array and then reshape:

```<code>df = pd.DataFrame(np.array(data).reshape(-1, len(data)), columns=label)
print(df)
   a  b  c  d  e
0  X  Y  Z  A  B
</code>```

Timings:

```<code>N = 100
data = ["X", "Y", "Z", "A", "B"] * N
label = ['a','b','c','d','e'] * N

In [30]: %timeit pd.DataFrame([data], columns=label)
10 loops, best of 3: 178 ms per loop

In [31]: %timeit pd.DataFrame(np.array(data).reshape(-1, len(data)), columns=label)
1000 loops, best of 3: 1.06 ms per loop

N = 1000

In [35]: %timeit pd.DataFrame([data], columns=label)
1 loop, best of 3: 1.7 s per loop

In [36]: %timeit pd.DataFrame(np.array(data).reshape(-1, len(data)), columns=label)
100 loops, best of 3: 3.83 ms per loop
</code>```

Title: Python Dataframe Single Row with Label

Body:
import pandas as pd
data = ["X", "Y", "Z", "A", "B"]
label = ['a','b','c','d','e']
df = pd.DataFrame(data, columns=label)
print(df)

I want to get the dataframe to be:

a b c d e
X Y Z A B

I am getting

ValueError: Shape of passed values is (1, 5), indices imply (5, 5)

How to fix this to get the desired dataframe ?

Body:
You can use a bit complicated, but very fast solution if large data - convert list to numpy array and then reshape:

df = pd.DataFrame(np.array(data).reshape(-1, len(data)), columns=label)
print(df)
   a  b  c  d  e
0  X  Y  Z  A  B

Timings:

N = 100
data = ["X", "Y", "Z", "A", "B"] * N
label = ['a','b','c','d','e'] * N

In [30]: %timeit pd.DataFrame([data], columns=label)
10 loops, best of 3: 178 ms per loop

In [31]: %timeit pd.DataFrame(np.array(data).reshape(-1, len(data)), columns=label)
1000 loops, best of 3: 1.06 ms per loop

N = 1000

In [35]: %timeit pd.DataFrame([data], columns=label)
1 loop, best of 3: 1.7 s per loop

In [36]: %timeit pd.DataFrame(np.array(data).reshape(-1, len(data)), columns=label)
100 loops, best of 3: 3.83 ms per loop


问:
About C# object scope
So I've created a class and instantiate an object in the main window. Then, when I'm trying to use that object in a button within the same window, I don't know how to indicate the context for this object. I know this is a very basic question, but I'm learning and haven't been able to figure it out just yet.

```<code>public MainWindow()
{
    InitializeComponent();
    DeltaMotor M2 = new DeltaMotor();
    M2.Card.Set8255();
    M2.Stop();
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    M2.Move(1); // this can't find M2 within the context
}
</code>```

I know this is basic, but help will be greatly appreciated.

答:
If you just want it to be accessible within this one class, then

```<code>private DeltaMotor M2;
public MainWindow()
{
    InitializeComponent();
    M2 = new DeltaMotor();
    M2.Card.Set8255();
    M2.Stop();
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    M2.Move(1); // this can't find M2 within the context
}
</code>```

Will work quite nicely. For further learning, here's a Microsoft reference on variable and method scope:
https://msdn.microsoft.com/en-us/library/ms973875.aspx

Which will be useful if you ever what to access M2 in another class. Hope that helps you get started!

Title: About C# object scope

Body:
So I've created a class and instantiate an object in the main window. Then, when I'm trying to use that object in a button within the same window, I don't know how to indicate the context for this object. I know this is a very basic question, but I'm learning and haven't been able to figure it out just yet.

public MainWindow()
{
    InitializeComponent();
    DeltaMotor M2 = new DeltaMotor();
    M2.Card.Set8255();
    M2.Stop();
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    M2.Move(1); // this can't find M2 within the context
}

I know this is basic, but help will be greatly appreciated.

Body:
If you just want it to be accessible within this one class, then

private DeltaMotor M2;
public MainWindow()
{
    InitializeComponent();
    M2 = new DeltaMotor();
    M2.Card.Set8255();
    M2.Stop();
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    M2.Move(1); // this can't find M2 within the context
}

Will work quite nicely. For further learning, here's a Microsoft reference on variable and method scope:
https://msdn.microsoft.com/en-us/library/ms973875.aspx

Which will be useful if you ever what to access M2 in another class. Hope that helps you get started!


问:
Firebase Analytics Setting User Property Multiple Times
In my app, I want to track the users based on business name. To track this, I'm setting value every time the user starts the app.

```<code>FirebaseAnalytics.getInstance(this).setUserProperty(Global.FIREBASE_ANALYTICS_BIZ, loginSP.getString(Global.BIZ_NM, ""));
</code>```

Is this is the correct way to do it? Or, can I do this only once when they logged in?

If I set this only once when they logged in, can I see the users in active users list if they are active.

Is the setting of user property is persisted across app restarts?

答:
User properties are designed for values that only change rarely, if at all, so they are well suited for your purpose.  The value of a user property persists and is reported with every bundle of events, across multiple runs of the app, reboots of the phone, etc.  Uninstalling the app will erase user property values.

1. You only need to set the value the first time the user starts the app, and whenever the value changes.

2. You do not need to set a user property or log a custom event for an active user to be counted.  If the user runs the app they will be counted.

3. Yes.

Body:
In my app, I want to track the users based on business name. To track this, I'm setting value every time the user starts the app.

FirebaseAnalytics.getInstance(this).setUserProperty(Global.FIREBASE_ANALYTICS_BIZ, loginSP.getString(Global.BIZ_NM, ""));

Is this is the correct way to do it? Or, can I do this only once when they logged in?

If I set this only once when they logged in, can I see the users in active users list if they are active.

Is the setting of user property is persisted across app restarts?


问:
Using Anaconda Python 3.4 with PyQt5
I have an existing PyQt5/Python3.4 application that works great, and would now like to add "real-time" data graphing to it.  Since matplotlib installation specifically looks for Python 3.2, and NumPhy / ipython each have there own Python version requirements, I thought I'd use a python distribution to avoid confusion.

But out of all the distros (pythonxy, winpython, canopy epd) Anaconda is the only one that supports Python 3.4, however it only has PyQt 4.10.4.   Is there a way I can install Anaconda, and use matplotlib from within my existing PyQt5 gui app?

Would I be better off just using another charting package (pyqtgraph, pyqwt, guiqwt, chaco, etc) that might work out of the box with PyQt5/Python3.4?

答:
I use Anaconda and with Python v2.7.X and qt5 doesn't work. The work-around I found was
Tools -> Preferences -> Python console -> External modules -> Library: PySlide</p>

Title: Using Anaconda Python 3.4 with PyQt5


问:
Get current user in Django admin
I have a posting object that can be either accessed in the website or the admin panel. In both, the user is automatically assigned to the post when the user posts it. In the website area, it works fine. However, it does not work in the admin area. First, I tried just having the form input there. When I try to save the object and leave the input blank, it tells me the form has no value. Then, trying to see if I just put in a random value and see if it was overwritten, I did that. However, that random value was not overwritten with the current user. If I excluded the field, when I try to save the model I get an Integrity error saying the field author 'may not be NULL', so I'm assuming my save_model() function is not firing right at all. Now the code I'm using for this I've seen all over the internet and people claim for it to work, I don't know if it's just broken now or what. Here's my code:</p>

```<code>from django.contrib import admin
from posting.models import Posting, Categories

class PostingAdmin(admin.ModelAdmin):
    list_display = ("title","author", "article","date")
    exclude = ('author',)
    fieldsets = (
        (None, {
            'fields': ('title',)
        }),
        ('Body', {
            'fields': ('article',)
            }),
    )

    def save_model(self,request,form,obj,change):
        print 'ENTERING SAVE_MODEL FUNCTION'
        if not change:
            obj.author = request.user
            print 'OBJ.AUTHOR:' + str(obj.author)
        obj.save()
        print "EXITING SAVE_MODEL FUNCTION"
admin.site.register(Posting, PostingAdmin)
</code>```

答:
I know i am a bit late for posting this solution, but like me if anyone else come across you may try:</p>

```<code>def save_model(self, request, obj, form, change):
    if getattr(obj, 'author', None) is None:
        obj.author = request.user
    obj.save()
</code>```

Title: Get current user in Django admin

Body:
I have a posting object that can be either accessed in the website or the admin panel. In both, the user is automatically assigned to the post when the user posts it. In the website area, it works fine. However, it does not work in the admin area. First, I tried just having the form input there. When I try to save the object and leave the input blank, it tells me the form has no value. Then, trying to see if I just put in a random value and see if it was overwritten, I did that. However, that random value was not overwritten with the current user. If I excluded the field, when I try to save the model I get an Integrity error saying the field author 'may not be NULL', so I'm assuming my save_model() function is not firing right at all. Now the code I'm using for this I've seen all over the internet and people claim for it to work, I don't know if it's just broken now or what. Here's my code:

from django.contrib import admin
from posting.models import Posting, Categories

class PostingAdmin(admin.ModelAdmin):
    list_display = ("title","author", "article","date")
    exclude = ('author',)
    fieldsets = (
        (None, {
            'fields': ('title',)
        }),
        ('Body', {
            'fields': ('article',)
            }),
    )

    def save_model(self,request,form,obj,change):
        print 'ENTERING SAVE_MODEL FUNCTION'
        if not change:
            obj.author = request.user
            print 'OBJ.AUTHOR:' + str(obj.author)
        obj.save()
        print "EXITING SAVE_MODEL FUNCTION"
admin.site.register(Posting, PostingAdmin)

Body:
I know i am a bit late for posting this solution, but like me if anyone else come across you may try:

def save_model(self, request, obj, form, change):
    if getattr(obj, 'author', None) is None:
        obj.author = request.user
    obj.save()


问:
ViewCell ForceUpdateSize not working sometimes
I am using a custom ViewCell in Xamarin Forms which looks like this:

```<code>public class NativeCell : ViewCell
{
    public double Height
    {
        get
        {
            return base.Height;
        }
        set
        {
            base.Height = value;
            ForceUpdateSize();
        }
    }
}
</code>```

I have also created a method to animate the colapse of the ViewCell which works as expected. However, with the overlay that comes with await, each loop iteration lasts up to 100ms instead of 1ms:

```<code>async public void Colapse()
{
    for (double i = Height; i >= 0; i--)
    {
        Height = i;
        await Task.Delay(1);
    }
}
</code>```

So I made another method that used the Stopwatch to do the waiting:

```<code>async public void Colapse()
{
    var Timer = new Stopwatch();

    for (double i = Height; i >= 0; i--)
    {
        Height = i;

        Timer.Start();
        while(Timer.Elapsed.TotalMilliseconds < 1)
        {
        }
        Debug.WriteLine("-->" + Timer.Elapsed.TotalMilliseconds);
        Timer.Reset();
    }
}
</code>```

This last method reports that the wait time is now usually 1.1ms - 1.3ms. Which is great. However, the Height asignment is not doing anything. Or at least ForceUpdateSize is not triggering.

答:
We need to solve few problems here.

You have to specify HasUnevenRows in list view

You cannot do "double i = Height" because Height will be "-1"

You last function setting Height using StopWatch is not really async, so you UI will not be updated till function exits.

Because Task.Delay is slow we can use Device timer with tick interval

Below is the solution that I tested on Android. The code is inside ViewCell in PCL

```<code>int currentHeight;
        public void Colapse()
        {
            currentHeight = (int)this.View.Height;
            Device.StartTimer(new TimeSpan(100), timerTick);
        }

        private bool timerTick()
        {
            if (currentHeight <= 0)
                return false;
            else
            {
                Height = currentHeight--;
                ForceUpdateSize();
                return true;
            }
        }
</code>```

Body:
I am using a custom ViewCell in Xamarin Forms which looks like this:

public class NativeCell : ViewCell
{
    public double Height
    {
        get
        {
            return base.Height;
        }
        set
        {
            base.Height = value;
            ForceUpdateSize();
        }
    }
}

I have also created a method to animate the colapse of the ViewCell which works as expected. However, with the overlay that comes with await, each loop iteration lasts up to 100ms instead of 1ms:

async public void Colapse()
{
    for (double i = Height; i >= 0; i--)
    {
        Height = i;
        await Task.Delay(1);
    }
}

So I made another method that used the Stopwatch to do the waiting:

async public void Colapse()
{
    var Timer = new Stopwatch();

    for (double i = Height; i >= 0; i--)
    {
        Height = i;

        Timer.Start();
        while(Timer.Elapsed.TotalMilliseconds < 1)
        {
        }
        Debug.WriteLine("-->" + Timer.Elapsed.TotalMilliseconds);
        Timer.Reset();
    }
}

This last method reports that the wait time is now usually 1.1ms - 1.3ms. Which is great. However, the Height asignment is not doing anything. Or at least ForceUpdateSize is not triggering.

Body:
We need to solve few problems here.

You have to specify HasUnevenRows in list view

You cannot do "double i = Height" because Height will be "-1"

You last function setting Height using StopWatch is not really async, so you UI will not be updated till function exits.

Because Task.Delay is slow we can use Device timer with tick interval

Below is the solution that I tested on Android. The code is inside ViewCell in PCL

int currentHeight;
        public void Colapse()
        {
            currentHeight = (int)this.View.Height;
            Device.StartTimer(new TimeSpan(100), timerTick);
        }

        private bool timerTick()
        {
            if (currentHeight <= 0)
                return false;
            else
            {
                Height = currentHeight--;
                ForceUpdateSize();
                return true;
            }
        }


问:
How to create a standalone RESTful Service in Java to consume JSON?
I am trying to create a standalone RESTful Service in Java without a Web Server.
This service will consume JSON that's sent part of the request from client applications.

I can create a SOAP web service using JAX-WS but I want to create REST service that will be run without a web server. Please suggest how can I create this? Appreciate your help.

Thanks

答: I prefer to choose spring boot to create Restful web services where it does not depend on web server. We can create and build the rest service as service. </p>


问:
Modifying data in a csv
I am trying to open and modify data in a csv file. I am trying to learn to utilize the csv module and I have little experience with it.

Basically what I am attempting to accomplish is have the program open a csv, it then opens a second csv to compare the data in column 0, from the first csv, with a matrix of sort in the second csv. If the data in a row of column 0 matches the second csv file's row/column 0 it will take the data from column 1, in the second csv, and replace it in the original csv file.

I was able to accomplish this without using the csv module with the code below.

```<code>file = open("needs_convertedTest.csv","r")

newFile = []

for line in file:
    data = line.split(",")
    file2 = open("options.csv","r")
    for choice in file2:
        dataOption = choice.split(",")
        if dataOption[0] in data[0]:
            docType = dataOption[1].strip("\n")
            newLine = "%s,%s,%s,%s,%s,%s,%s,%s,%s" %(docType,data[1],data[2],data[3],
                                                     data[4],data[5],data[7],data[6],data[8])
            newFile.append(newLine)

file = open("needs_convertedTest.csv","w")

for line in newFile:
    file.write(line)

file.close()
</code>```

The problem with using this code is that there are a couple of document types that are similar in name and for some reason the program creates a double of one of them, as demonstrated below.

```<code>MTG Closing | Margarett Jackson | 123-45-6789 | 1410000625 | 111814 | 18    | G:\Downloads\Exports\Images\Loan_1410000625\Good Faith Estimate.pdf | 16
MTG Closing | Margarett Jackson | 123-45-6789 | 1410000625 | 111814 | 18 | G:\Downloads\Exports\Images\Loan_1410000625\Acknowledgement of Receipt of Good Faith Estimate.pdf | 16
MTG Disclosures | Margarett Jackson | 123-45-6789 | 1410000625 | 111814 | 18 | G:\Downloads\Exports\Images\Loan_1410000625\Acknowledgement of Receipt of Good Faith Estimate.pdf | 16
</code>```

The first and third lines are correct. The second one is a duplicate of the third but has an incorrect Document Type, MTG Closing.

The options.csv file is formatted like this.

```<code>MTG Closings | Good Faith Estimate
MTG Disclosures | Acknowledgement of Receipt of Good Faith Estimate
</code>```

This is followed by several other rows containing similar data that the program uses to make comparisons and replacements of data in the needs_converted.csv file.

This program only deals with the information in data[0] which is the first column.

This is the program I wrote attempting to perform the same task, utilizing the csv module.

```<code>import csv

newFile=[]

with open('needs_converted.csv', 'w', newline='') as csvfile:
    data = csv.writer(csvfile, delimiter=' ',
                        quotechar='"', quoting=csv.QUOTE_ALL)
    with open('options.csv','r',) as csvfile2:
        dataOption = csv.reader(csvfile2, delimiter=' ',
                        quotechar='"', quoting=csv.QUOTE_ALL)
        next(reader,None)
        if dataOption[0] in data[0]:
            docType = dataOption[1].strip("\n")
            newLine = "%s,%s,%s,%s,%s,%s,%s,%s,%s" %(docType,data[1],data[2],data[3],
                                                     data[4],data[5],data[7],data[6],data[8])
            newFile.append(newLine)
</code>```

If someone could help me construct the code to accomplish this via the csv module, I would be really grateful!

Thanks,
Max

答:
It can be tricky to replace a line replace directly in an input file that you're looping over (though we do have a fileinput module that supports an inplace update option).

Instead, it is usually much simpler to build a new output file. The csv module writer objects will let you output CSV formatted lines effortlessly.  Once the new file is fully populated, just replace the original file with the new file using shutil.move().

Hope this gets you back on the right track :-)

Title: Modifying data in a csv

Body:
I am trying to open and modify data in a csv file. I am trying to learn to utilize the csv module and I have little experience with it.

Basically what I am attempting to accomplish is have the program open a csv, it then opens a second csv to compare the data in column 0, from the first csv, with a matrix of sort in the second csv. If the data in a row of column 0 matches the second csv file's row/column 0 it will take the data from column 1, in the second csv, and replace it in the original csv file.

I was able to accomplish this without using the csv module with the code below.

file = open("needs_convertedTest.csv","r")

newFile = []

for line in file:
    data = line.split(",")
    file2 = open("options.csv","r")
    for choice in file2:
        dataOption = choice.split(",")
        if dataOption[0] in data[0]:
            docType = dataOption[1].strip("\n")
            newLine = "%s,%s,%s,%s,%s,%s,%s,%s,%s" %(docType,data[1],data[2],data[3],
                                                     data[4],data[5],data[7],data[6],data[8])
            newFile.append(newLine)

file = open("needs_convertedTest.csv","w")

for line in newFile:
    file.write(line)

file.close()

The problem with using this code is that there are a couple of document types that are similar in name and for some reason the program creates a double of one of them, as demonstrated below.

MTG Closing | Margarett Jackson | 123-45-6789 | 1410000625 | 111814 | 18    | G:\Downloads\Exports\Images\Loan_1410000625\Good Faith Estimate.pdf | 16
MTG Closing | Margarett Jackson | 123-45-6789 | 1410000625 | 111814 | 18 | G:\Downloads\Exports\Images\Loan_1410000625\Acknowledgement of Receipt of Good Faith Estimate.pdf | 16
MTG Disclosures | Margarett Jackson | 123-45-6789 | 1410000625 | 111814 | 18 | G:\Downloads\Exports\Images\Loan_1410000625\Acknowledgement of Receipt of Good Faith Estimate.pdf | 16

The first and third lines are correct. The second one is a duplicate of the third but has an incorrect Document Type, MTG Closing.

The options.csv file is formatted like this.

MTG Closings | Good Faith Estimate
MTG Disclosures | Acknowledgement of Receipt of Good Faith Estimate

This is followed by several other rows containing similar data that the program uses to make comparisons and replacements of data in the needs_converted.csv file.

This program only deals with the information in data[0] which is the first column.

This is the program I wrote attempting to perform the same task, utilizing the csv module.

import csv

newFile=[]

with open('needs_converted.csv', 'w', newline='') as csvfile:
    data = csv.writer(csvfile, delimiter=' ',
                        quotechar='"', quoting=csv.QUOTE_ALL)
    with open('options.csv','r',) as csvfile2:
        dataOption = csv.reader(csvfile2, delimiter=' ',
                        quotechar='"', quoting=csv.QUOTE_ALL)
        next(reader,None)
        if dataOption[0] in data[0]:
            docType = dataOption[1].strip("\n")
            newLine = "%s,%s,%s,%s,%s,%s,%s,%s,%s" %(docType,data[1],data[2],data[3],
                                                     data[4],data[5],data[7],data[6],data[8])
            newFile.append(newLine)

If someone could help me construct the code to accomplish this via the csv module, I would be really grateful!

Thanks,
Max


问:
How to get row count and use in range
I am trying to get the number of rows in a spreadsheet and then use the number to select a range as such:

```<code>Dim lastrow As Long
lastrow = Cells(Rows.Count, "A").End(xlUp).Row
Range("C1").Select
ActiveCell.Copy
Range("C2:C & lastrow").Select
ActiveSheet.Paste
Range("A2:A & lastrow").Select
ActiveSheet.Paste
</code>```

So basically I am trying to copy content of C1 into every cell within columns A and C. However, using C:C and A:A in my Range statements causes extra rows to be added when I paste. So I really I need to be able to get the count of rows and then use that in the range. Can someone help me with this?

Thanks,

Jesse

答:
If I'm not mistaken, this code shouldnt compile. Your code is this:

```<code>Dim lastrow As Long
lastrow = Cells(Rows.Count, "A").End(xlUp).Row
Range("C1").Select
ActiveCell.Copy
Range("C2:C & lastrow").Select ' <----
ActiveSheet.Paste
Range("A2:A & lastrow").Select ' <----
ActiveSheet.Paste
</code>```

And it should be:

```<code>Dim lastrow As Long
lastrow = Cells(Rows.Count, "A").End(xlUp).Row
Range("C1").Select
ActiveCell.Copy
Range("C2:C" & lastrow).Select
ActiveSheet.Paste
Range("A2:A" & lastrow).Select
ActiveSheet.Paste
</code>```

This ignores the inefficiency of Select, Activate, Paste, etc, but it solves your problem (or at least should, unless I am really missing something).

Title: How to get row count and use in range

Body:
I am trying to get the number of rows in a spreadsheet and then use the number to select a range as such:

Dim lastrow As Long
lastrow = Cells(Rows.Count, "A").End(xlUp).Row
Range("C1").Select
ActiveCell.Copy
Range("C2:C & lastrow").Select
ActiveSheet.Paste
Range("A2:A & lastrow").Select
ActiveSheet.Paste

So basically I am trying to copy content of C1 into every cell within columns A and C. However, using C:C and A:A in my Range statements causes extra rows to be added when I paste. So I really I need to be able to get the count of rows and then use that in the range. Can someone help me with this?

Thanks,

Jesse

Body:
If I'm not mistaken, this code shouldnt compile. Your code is this:

Dim lastrow As Long
lastrow = Cells(Rows.Count, "A").End(xlUp).Row
Range("C1").Select
ActiveCell.Copy
Range("C2:C & lastrow").Select ' <----
ActiveSheet.Paste
Range("A2:A & lastrow").Select ' <----
ActiveSheet.Paste

And it should be:

Dim lastrow As Long
lastrow = Cells(Rows.Count, "A").End(xlUp).Row
Range("C1").Select
ActiveCell.Copy
Range("C2:C" & lastrow).Select
ActiveSheet.Paste
Range("A2:A" & lastrow).Select
ActiveSheet.Paste

This ignores the inefficiency of Select, Activate, Paste, etc, but it solves your problem (or at least should, unless I am really missing something).


问:
Retrofit2 return null Unit in kotlin for 204 No Content response
I'm using Retrofit 2.0.2 to post data to server using the interface below:

```<code>@POST("/path/to/post")
fun postData(/*args*/): Observable<Unit>
</code>```

And received success response from server.

```<code>05-09 21:20:21.770 23117 23224 D OkHttp  : --> POST https://myserver.com/api/notifications/123/markRead http/1.1
05-09 21:20:21.770 23117 23224 D OkHttp  : Content-Length: 0
05-09 21:20:21.770 23117 23224 D OkHttp  : User-Agent: MyUserAgent
05-09 21:20:21.770 23117 23224 D OkHttp  : Authorization: Bearer xxxxx
05-09 21:20:21.770 23117 23224 D OkHttp  : --> END POST (0-byte body)
05-09 21:20:22.473 23117 23224 D OkHttp  : <-- 204 No Content https://myserver.com/api/notifications/123/markRead (701ms)
</code>```

But i got exception below, seems retrofit pass null Unit to onNext.
Is this expected behaviour?

```<code>05-09 21:20:22.496 23117 23117 W System.err: java.lang.IllegalArgumentException: Parameter specified as non-null is null: method b.d.b.k.b, parameter result
05-09 21:20:22.496 23117 23117 W System.err:    at com.myandroid.notification.dialog.c$a.a(NotificationListPresenter.kt)
05-09 21:20:22.496 23117 23117 W System.err:    at com.myandroid.notification.dialog.c$a.onNext(NotificationListPresenter.kt:57)
05-09 21:20:22.496 23117 23117 W System.err:    at e.g.b.onNext(SafeSubscriber.java:139)
05-09 21:20:22.496 23117 23117 W System.err:    at e.d.a.g$2$1.onNext(OnSubscribeRedo.java:249)
05-09 21:20:22.496 23117 23117 W System.err:    at e.d.a.p$a.call(OperatorObserveOn.java:215)
05-09 21:20:22.496 23117 23117 W System.err:    at e.a.b.b$b.run(LooperScheduler.java:107)
05-09 21:20:22.496 23117 23117 W System.err:    at android.os.Handler.handleCallback(Handler.java:730)
05-09 21:20:22.504 23117 23117 W System.err:    at android.os.Handler.dispatchMessage(Handler.java:92)
05-09 21:20:22.504 23117 23117 W System.err:    at android.os.Looper.loop(Looper.java:137)
05-09 21:20:22.504 23117 23117 W System.err:    at android.app.ActivityThread.main(ActivityThread.java:5103)
05-09 21:20:22.504 23117 23117 W System.err:    at java.lang.reflect.Method.invokeNative(Native Method)
05-09 21:20:22.504 23117 23117 W System.err:    at java.lang.reflect.Method.invoke(Method.java:525)
05-09 21:20:22.504 23117 23117 W System.err:    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
05-09 21:20:22.504 23117 23117 W System.err:    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
05-09 21:20:22.504 23117 23117 W System.err:    at dalvik.system.NativeStart.main(Native Method)
</code>```

Thank you.

答:
The right way of solving this problem is to use Completable like this:

```<code>@POST("/path/to/post")
fun postData(/*args*/): Completable
</code>```

Then you can subscribe like this:

```<code>service.postData(/*args*/)
    .subscribe({ view.dataPostedSuccesfully() }, { handleError(it) })
</code>```

Work like a charm for me with Retrofit 2.2.0, RxJava 2.1.0.

Body:
I'm using Retrofit 2.0.2 to post data to server using the interface below:

@POST("/path/to/post")
fun postData(/*args*/): Observable<Unit>

And received success response from server.

05-09 21:20:21.770 23117 23224 D OkHttp  : --> POST https://myserver.com/api/notifications/123/markRead http/1.1
05-09 21:20:21.770 23117 23224 D OkHttp  : Content-Length: 0
05-09 21:20:21.770 23117 23224 D OkHttp  : User-Agent: MyUserAgent
05-09 21:20:21.770 23117 23224 D OkHttp  : Authorization: Bearer xxxxx
05-09 21:20:21.770 23117 23224 D OkHttp  : --> END POST (0-byte body)
05-09 21:20:22.473 23117 23224 D OkHttp  : <-- 204 No Content https://myserver.com/api/notifications/123/markRead (701ms)

But i got exception below, seems retrofit pass null Unit to onNext.
Is this expected behaviour?

05-09 21:20:22.496 23117 23117 W System.err: java.lang.IllegalArgumentException: Parameter specified as non-null is null: method b.d.b.k.b, parameter result
05-09 21:20:22.496 23117 23117 W System.err:    at com.myandroid.notification.dialog.c$a.a(NotificationListPresenter.kt)
05-09 21:20:22.496 23117 23117 W System.err:    at com.myandroid.notification.dialog.c$a.onNext(NotificationListPresenter.kt:57)
05-09 21:20:22.496 23117 23117 W System.err:    at e.g.b.onNext(SafeSubscriber.java:139)
05-09 21:20:22.496 23117 23117 W System.err:    at e.d.a.g$2$1.onNext(OnSubscribeRedo.java:249)
05-09 21:20:22.496 23117 23117 W System.err:    at e.d.a.p$a.call(OperatorObserveOn.java:215)
05-09 21:20:22.496 23117 23117 W System.err:    at e.a.b.b$b.run(LooperScheduler.java:107)
05-09 21:20:22.496 23117 23117 W System.err:    at android.os.Handler.handleCallback(Handler.java:730)
05-09 21:20:22.504 23117 23117 W System.err:    at android.os.Handler.dispatchMessage(Handler.java:92)
05-09 21:20:22.504 23117 23117 W System.err:    at android.os.Looper.loop(Looper.java:137)
05-09 21:20:22.504 23117 23117 W System.err:    at android.app.ActivityThread.main(ActivityThread.java:5103)
05-09 21:20:22.504 23117 23117 W System.err:    at java.lang.reflect.Method.invokeNative(Native Method)
05-09 21:20:22.504 23117 23117 W System.err:    at java.lang.reflect.Method.invoke(Method.java:525)
05-09 21:20:22.504 23117 23117 W System.err:    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
05-09 21:20:22.504 23117 23117 W System.err:    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
05-09 21:20:22.504 23117 23117 W System.err:    at dalvik.system.NativeStart.main(Native Method)

Thank you.

Body:
The right way of solving this problem is to use Completable like this:

@POST("/path/to/post")
fun postData(/*args*/): Completable

Then you can subscribe like this:

service.postData(/*args*/)
    .subscribe({ view.dataPostedSuccesfully() }, { handleError(it) })

Work like a charm for me with Retrofit 2.2.0, RxJava 2.1.0.


问:
Setup test data for Jmeter and Junit
Is there any way I can setup my test data for load tests that use Jmeter and Junit? I would like to be able to do something like get a  new user from a csv for each thread of a test. </p>

答:
Yes, I've used this a number of times.

See JMeter : Reading variables from a file.

Title: Setup test data for Jmeter and Junit


问:
cmdline argument parsing using tcl?
I am trying to pass the parameters to Spirent test center tool  using command line arguments, where I am passing slots, ports, frame size and load. I want to store the Slots and ports in array, where number of ports are dynamic.
I tried simple code with cmdline which can handle fixed ports

```<code>package require cmdline

set parameters {
    {s.arg ""   "Slot"}
    {p.arg ""   "Port"}
    {l.arg "100"   "Load"}
    {f.arg "256"   "Framesize"}
    {debug      "Turn on debugging, default=off"}
}
#set option(l) 100
set usage "- A simple script to demo cmdline parsing"

if {[catch {array set options [cmdline::getoptions ::argv $parameters $usage]}]} {
    puts [cmdline::usage $parameters $usage]
} else {
    parray options
}
#puts [array get options]
puts $options(l)
puts $options(f)
</code>```

script Output:

```<code>C:\Tcl\bin>tclsh opt.tcl -s 1 -f 128
options(debug) = 0
options(f)     = 128
options(l)     = 100
options(p)     =
options(s)     = 1
100
128
</code>```

Here I would like to pass all the ports for each slots onetime ,

```<code>tclsh opt.tcl -s 1 2 -p 11 12 13 14 -f 256 -l 100
</code>```

Where slots are 1 and 2 and ports in each slot are 11,12,13,14 and need to create array of slot and ports. Could you please suggest some method to achieve this.

答:
Try

```<code>tclsh opt.tcl -s "1 2" -p "11 12 13 14" -f 256 -l 100
</code>```

It works for me under Windows 10, at least. The thing is that the lists of slots and ports need to be one value each: the quotes ensure that.

Title: cmdline argument parsing using tcl?

Body:
I am trying to pass the parameters to Spirent test center tool  using command line arguments, where I am passing slots, ports, frame size and load. I want to store the Slots and ports in array, where number of ports are dynamic.
I tried simple code with cmdline which can handle fixed ports

package require cmdline

set parameters {
    {s.arg ""   "Slot"}
    {p.arg ""   "Port"}
    {l.arg "100"   "Load"}
    {f.arg "256"   "Framesize"}
    {debug      "Turn on debugging, default=off"}
}
#set option(l) 100
set usage "- A simple script to demo cmdline parsing"

if {[catch {array set options [cmdline::getoptions ::argv $parameters $usage]}]} {
    puts [cmdline::usage $parameters $usage]
} else {
    parray options
}
#puts [array get options]
puts $options(l)
puts $options(f)

script Output:

C:\Tcl\bin>tclsh opt.tcl -s 1 -f 128
options(debug) = 0
options(f)     = 128
options(l)     = 100
options(p)     =
options(s)     = 1
100
128

Here I would like to pass all the ports for each slots onetime ,

tclsh opt.tcl -s 1 2 -p 11 12 13 14 -f 256 -l 100

Where slots are 1 and 2 and ports in each slot are 11,12,13,14 and need to create array of slot and ports. Could you please suggest some method to achieve this.

Body:
Try

tclsh opt.tcl -s "1 2" -p "11 12 13 14" -f 256 -l 100

It works for me under Windows 10, at least. The thing is that the lists of slots and ports need to be one value each: the quotes ensure that.


问:
Switch shader program with less calls
Currently, I call this function (simplified) everytime I want to switch shaders:

```<code>void switchToShader(ShaderProgram* newProg, Mesh& mesh) {
    if(m_currentProg != nullptr) {
        m_currentProg->disableAttributeArray("aPos");
    }
    newProg->enableAttributeArray("aPos");
    mesh.vertexPosBuffer()->bind();
    glVertexAttribPointer(newProg->attributeLocation("aPos"), 2, GL_FLOAT, false, 0, 0);

    newProg->bind();

    mesh.indexBuffer()->bind();

    m_currentProg = newProg;
}
</code>```

It seems needlessly inefficient though.

Note that this function is only intended to support switching between programs that have an identical set of attribute arrays.

Ideally, my code would look more like this:

```<code>ShaderProgram::ShaderProgram() {
    // ...
    enableAttributeArray("aPos");
    glVertexAttribPointer(newProg->attributeLocation("aPos"), 2, GL_FLOAT, false, 0, 0);
}

void switchToShader(ShaderProgram* newProg, Mesh& mesh) {
    mesh.vertexPosBuffer()->bind();
    newProg->bind();
    mesh.indexBuffer()->bind();
}
</code>```

But for obvious reasons, this does not work.

Note that my class ShaderProgram derives from Qt's QOpenGLShaderProgram.

Any hints how to make my code more efficient?

I'm aware that I could use glBindAttribLocation to force the attrib array aPos, at shader program initialization time, to use e.g. location 1, for all my shader programs, and that would mean I can do enableAttributeArray just once per frame and can skip the disableAttributeArray. But that's a bit inelegant because it means writing a little extra code and passing my arbitrarily-chosen attrib locations around.

I'm currently looking into VAOs.

Edit: After making use of glBindAttribLocation and VAOs, my problem is solved. My code now looks like this:

```<code>void switchToShader(ShaderProgram* newProg, Mesh& mesh) {
    newProg->bind();
    mesh.vao()->bind();
    m_currentProg = newProg;
}
</code>```

And I can even bind the shader programs and the VAOs independently from each other, outside this function.

答:
But that's a bit inelegant because it means writing a little extra code

Then put it in your shader with layout(location = #). That's not "inelegant"; tha'ts "putting the information where it goes".

and passing my arbitrarily-chosen attrib locations around.

And yet, you don't have a problem "passing my arbitrarily-choose attribute names around". There is no difference between "aPos" and 1, from the perspective of your code. You have to get some kind of identifier for that attribute to the VAO. In both cases, you could just hard-code it to a specific value; whether it's a string literal or an integer literal means nothing.

It's just that if you use an integer, you won't have to constantly recreate your VAO when you change programs.

The QT's API of putting VAO commands in the shader object is wrongheaded, and now you see exactly why. Programs should not be responsible for which attributes are enabled or where they come from.

You know how to solve your problem. So solve it.

Title: Switch shader program with less calls

Body:
Currently, I call this function (simplified) everytime I want to switch shaders:

void switchToShader(ShaderProgram* newProg, Mesh& mesh) {
    if(m_currentProg != nullptr) {
        m_currentProg->disableAttributeArray("aPos");
    }
    newProg->enableAttributeArray("aPos");
    mesh.vertexPosBuffer()->bind();
    glVertexAttribPointer(newProg->attributeLocation("aPos"), 2, GL_FLOAT, false, 0, 0);

    newProg->bind();

    mesh.indexBuffer()->bind();

    m_currentProg = newProg;
}

It seems needlessly inefficient though.

Note that this function is only intended to support switching between programs that have an identical set of attribute arrays.

Ideally, my code would look more like this:

ShaderProgram::ShaderProgram() {
    // ...
    enableAttributeArray("aPos");
    glVertexAttribPointer(newProg->attributeLocation("aPos"), 2, GL_FLOAT, false, 0, 0);
}

void switchToShader(ShaderProgram* newProg, Mesh& mesh) {
    mesh.vertexPosBuffer()->bind();
    newProg->bind();
    mesh.indexBuffer()->bind();
}

But for obvious reasons, this does not work.

Note that my class ShaderProgram derives from Qt's QOpenGLShaderProgram.

Any hints how to make my code more efficient?

I'm aware that I could use glBindAttribLocation to force the attrib array aPos, at shader program initialization time, to use e.g. location 1, for all my shader programs, and that would mean I can do enableAttributeArray just once per frame and can skip the disableAttributeArray. But that's a bit inelegant because it means writing a little extra code and passing my arbitrarily-chosen attrib locations around.

I'm currently looking into VAOs.

Edit: After making use of glBindAttribLocation and VAOs, my problem is solved. My code now looks like this:

void switchToShader(ShaderProgram* newProg, Mesh& mesh) {
    newProg->bind();
    mesh.vao()->bind();
    m_currentProg = newProg;
}

And I can even bind the shader programs and the VAOs independently from each other, outside this function.


问:
Use data in angular directive link?
How i can use data , which passed from controller to directive from tag attribute ?? Its show undefined in console .

```<code>App.directive('applist', ['$rootScope', function($rootScope) {
'use strict';
    return {
       restrict: 'E',
       scope: {
           gamesList: '=',
       }.
       link: function(scope,attrs){
           console.log(scope.gamesList); //undefined
       }
    }
}])
</code>```

And html:

```<code><applist games-List="games">
    <div ng-repeat="(key, value) in gamesList | groupBy: 'game.id'"> ... </div>
</applist>
</code>```

答:
Use @ for getting String Values:
Modified Code:</p>

```<code><!DOCTYPE html>
<html ng-app="myApp">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>

<applist games-list="games"></applist>
<script>
var App=angular.module('myApp',[]);

App.directive('applist', ['$rootScope', function($rootScope) {
'use strict';
    return {
       restrict: 'E',
       transclude:true,
       scope: {
           gamesList: '@',
       },
       link: function(scope,attrs){
           console.log(scope.gamesList); //games
       }
    }
}])
</script>

</body>
</html>
</code>```

Title: Use data in angular directive link?

Body:
How i can use data , which passed from controller to directive from tag attribute ?? Its show undefined in console .

App.directive('applist', ['$rootScope', function($rootScope) {
'use strict';
    return {
       restrict: 'E',
       scope: {
           gamesList: '=',
       }.
       link: function(scope,attrs){
           console.log(scope.gamesList); //undefined
       }
    }
}])

And html:

<applist games-List="games">

 ...

</applist>

Body:
Use @ for getting String Values:
Modified Code:

<!DOCTYPE html>
<html ng-app="myApp">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>

<applist games-list="games"></applist>
<script>
var App=angular.module('myApp',[]);

App.directive('applist', ['$rootScope', function($rootScope) {
'use strict';
    return {
       restrict: 'E',
       transclude:true,
       scope: {
           gamesList: '@',
       },
       link: function(scope,attrs){
           console.log(scope.gamesList); //games
       }
    }
}])
</script>

</body>
</html>


问:
My Android Buttons look a bit weird (screenshot attached)?
Screenshot

I want my buttons to be round, but they are oblate/oval (please take a look at the screenshot). Can anyone help? My code (There are 2 buttons at the bottom):

```<code><LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:paddingTop="?attr/actionBarSize"
    android:background="#ffffff"
    >

    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="16dp"
        android:paddingRight="16dp"
        android:text="@string/package_size"
        tools:ignore="RtlSymmetry" />
    <View
        android:layout_width="fill_parent"
        android:layout_height="2dp"
        android:layout_marginLeft="32dp"
        android:layout_marginRight="32dp"
        android:background="#e9eaea"/>
    <RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/radio_group"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <RadioButton
            android:id="@+id/radio_small"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/small" />

        <RadioButton
            android:id="@+id/radio_medium"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/medium" />
        <RadioButton
            android:id="@+id/radio_large"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/large" />
    </RadioGroup>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:weightSum="4"
        android:background="#e6e7e8"
        >
        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            >
            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/ic_minus"/>

            <TextView android:id="@+id/text"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="0" />
            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/ic_plus"/>
        </LinearLayout>

    </LinearLayout>
</LinearLayout>
</code>```

Do I need to change Layout? Or why is it happening?

答:
You have set the background of button.

Buttons are not square by default so the background is stretched to default width of button.

So set the width and height manually to be same.

Body:
Screenshot

I want my buttons to be round, but they are oblate/oval (please take a look at the screenshot). Can anyone help? My code (There are 2 buttons at the bottom):

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:paddingTop="?attr/actionBarSize"
    android:background="#ffffff"
    >

    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="16dp"
        android:paddingRight="16dp"
        android:text="@string/package_size"
        tools:ignore="RtlSymmetry" />
    <View
        android:layout_width="fill_parent"
        android:layout_height="2dp"
        android:layout_marginLeft="32dp"
        android:layout_marginRight="32dp"
        android:background="#e9eaea"/>
    <RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/radio_group"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <RadioButton
            android:id="@+id/radio_small"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/small" />

        <RadioButton
            android:id="@+id/radio_medium"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/medium" />
        <RadioButton
            android:id="@+id/radio_large"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/large" />
    </RadioGroup>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:weightSum="4"
        android:background="#e6e7e8"
        >
        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            >
            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/ic_minus"/>

            <TextView android:id="@+id/text"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="0" />
            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/ic_plus"/>
        </LinearLayout>

    </LinearLayout>
</LinearLayout>

Do I need to change Layout? Or why is it happening?


问:
Getting a reference to the current KeyboardFocusManager
Is there a way to get a reference to the current KeyboardFocusManager in a Swing application?</p>

答:
Have you checked   KeyboardFocusManager.getCurrentKeyboardFocusManager()

Returns the current KeyboardFocusManager instance for the calling thread's context.


问:
External CSS - Best method for different color for content area on 1/2 the site
I'm learning External CSS.

I have a CSS file that is working.  The pages use a background image and a content color.

I want to use a different content color as the background for photos--- about 1/2 of the pages in the site.  I want it to be in Ext CSS (not a page style), in case I want to change the color in the future.

What is the best practice when everything else in the CSS will be the same for all pages, except for the content color?

Please give a 'grade school' answer telling me exactly what I'll need to do.  I'm still learning terminology, so your clarity will really help me.

Thank you.

答:
Keep it in this way:

```<code>.color1{
      color: #000000;}
.color2{
      color: #ffffff;}
</code>```

You can name color1 and color2 as anything you want and save these styles in your css file. Use these classes where you want like:

```<code><button class="color1">Good Button</button>
</code>```

You can change color values and will reflect everywhere.

Body:
Keep it in this way:

.color1{
      color: #000000;}
.color2{
      color: #ffffff;}

You can name color1 and color2 as anything you want and save these styles in your css file. Use these classes where you want like:

<button class="color1">Good Button</button>

You can change color values and will reflect everywhere.


问:
Adding Image Transition Animation in Swift
Below is the code that automatically transitions between different images, every 5 seconds. I want to add animations to the transitions i.e. fade, scroll from left, etc. How would I go about doing this in Swift? Thanks.</p>

```<code>class ViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()

    imageView.animationImages = [
        UIImage(named: "brooklyn-bridge.jpg")!,
        UIImage(named: "grand-central-terminal.jpg")!,
        UIImage(named: "new-york-city.jpg")!,
        UIImage(named: "one-world-trade-center.jpg")!,
        UIImage(named: "rain.jpg")!,
        UIImage(named: "wall-street.jpg")!]

    imageView.animationDuration = 25.0
    imageView.startAnimating()
}
</code>```

答:
animating code, based on this answer, in Swift 3

```<code>let animationDuration: TimeInterval = 0.25
let switchingInterval: TimeInterval = 3
func animateImageView()
{
    CATransaction.begin()

    CATransaction.setAnimationDuration(animationDuration)
    CATransaction.setCompletionBlock {
        DispatchQueue.main.asyncAfter(deadline: .now() + self.switchingInterval) {
            self.animateImageView()
        }
    }

    let transition = CATransition()
    transition.type = kCATransitionFade
    /*
     transition.type = kCATransitionPush
     transition.subtype = kCATransitionFromRight
     */
    imageView.layer.add(transition, forKey: kCATransition)
    imageView.image = images.object(at: index) as! UIImage

    CATransaction.commit()

    index = index < images.count - 1 ? index + 1 : 0
}
</code>```

Body:
Below is the code that automatically transitions between different images, every 5 seconds. I want to add animations to the transitions i.e. fade, scroll from left, etc. How would I go about doing this in Swift? Thanks.

class ViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()

    imageView.animationImages = [
        UIImage(named: "brooklyn-bridge.jpg")!,
        UIImage(named: "grand-central-terminal.jpg")!,
        UIImage(named: "new-york-city.jpg")!,
        UIImage(named: "one-world-trade-center.jpg")!,
        UIImage(named: "rain.jpg")!,
        UIImage(named: "wall-street.jpg")!]

    imageView.animationDuration = 25.0
    imageView.startAnimating()
}

Body:
animating code, based on this answer, in Swift 3

let animationDuration: TimeInterval = 0.25
let switchingInterval: TimeInterval = 3
func animateImageView()
{
    CATransaction.begin()

    CATransaction.setAnimationDuration(animationDuration)
    CATransaction.setCompletionBlock {
        DispatchQueue.main.asyncAfter(deadline: .now() + self.switchingInterval) {
            self.animateImageView()
        }
    }

    let transition = CATransition()
    transition.type = kCATransitionFade
    /*
     transition.type = kCATransitionPush
     transition.subtype = kCATransitionFromRight
     */
    imageView.layer.add(transition, forKey: kCATransition)
    imageView.image = images.object(at: index) as! UIImage

    CATransaction.commit()

    index = index < images.count - 1 ? index + 1 : 0
}


问:
Angular - get title list from json placeholder
I have created a simple service with Angular version 4 where I return an array with a few titles:

Here's the code:

```<code>//post.service.ts
import { Injectable } from '@angular/core';

@Injectable()
export class PopstService {

  constructor() {}

  showPosts() {
    return ['title1', 'title2', 'title3'];
  }

}
</code>```

Instead of having it hardcoded in the service page I'd like to gt the titles from some json data instead.

Here's the url:

https://jsonplaceholder.typicode.com/posts

Data looks like this:

```<code>0
userId  1
id  1
title   "sunt aut facere repellat provident occaecati excepturi optio reprehenderit"
body    "quia et suscipit\nsuscip… rem eveniet architecto"
1
userId  1
id  2
title   "qui est esse"
body    "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
</code>```

How can I modify this service to return the titles from the online json instead of my current hardcoded titles?

答:
Step 1. Create A service

```<code>import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import  'rxjs/add/operator/map';
import  'rxjs/add/operator/do';
import  'rxjs/add/operator/catch';

@Injectable()
export class ProductService{
  private _productUrl = 'api url';
  constructor (private _http:Http){}

  getProductsHttp():Observable<any> {
      return this._http.get(this._productUrl)
          .map((response: Response) => <any> response.json())
          .do(data => console.log('All: ' +  JSON.stringify(data)))
          .catch(this.handleError);
  }

  private handleError(error: Response) {
      console.error(error);
      return Observable.throw(error.json().error || 'Server error');
  }
</code>```

Step 2 Change the Component like below

```<code>constructor(private _producrService:ProductService)  {

  }
  ngOnInit() {
      //this.products=this._producrService.getProducts();
      this._producrService.getProductsHttp()
              .subscribe(products => this.products = products,
                         error => this.errorMessage = <any>error);

  }
</code>```

Body:
I have created a simple service with Angular version 4 where I return an array with a few titles:

Here's the code:

//post.service.ts
import { Injectable } from '@angular/core';

@Injectable()
export class PopstService {

  constructor() {}

  showPosts() {
    return ['title1', 'title2', 'title3'];
  }

}

Instead of having it hardcoded in the service page I'd like to gt the titles from some json data instead.

Here's the url:

https://jsonplaceholder.typicode.com/posts

Data looks like this:

0
userId  1
id  1
title   "sunt aut facere repellat provident occaecati excepturi optio reprehenderit"
body    "quia et suscipit\nsuscip… rem eveniet architecto"
1
userId  1
id  2
title   "qui est esse"
body    "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"

How can I modify this service to return the titles from the online json instead of my current hardcoded titles?

Body:
Step 1. Create A service

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import  'rxjs/add/operator/map';
import  'rxjs/add/operator/do';
import  'rxjs/add/operator/catch';

@Injectable()
export class ProductService{
  private _productUrl = 'api url';
  constructor (private _http:Http){}

  getProductsHttp():Observable<any> {
      return this._http.get(this._productUrl)
          .map((response: Response) => <any> response.json())
          .do(data => console.log('All: ' +  JSON.stringify(data)))
          .catch(this.handleError);
  }

  private handleError(error: Response) {
      console.error(error);
      return Observable.throw(error.json().error || 'Server error');
  }

Step 2 Change the Component like below

constructor(private _producrService:ProductService)  {

  }
  ngOnInit() {
      //this.products=this._producrService.getProducts();
      this._producrService.getProductsHttp()
              .subscribe(products => this.products = products,
                         error => this.errorMessage = <any>error);

  }


问:
Unix sort of version numbers
I have a list of version numbers, let's say for instance that they are in a file versions.txt

```<code>1.2.100.4
1.2.3.4
10.1.2.3
9.1.2.3
</code>```

I wish to sort them so that they are sorted by version.  i.e:

```<code>1.2.3.4
1.2.100.4
9.1.2.3
10.1.2.3
</code>```

I have tried using various sort commands using the "k" parameters, but do not really understand it well enough to pull it off.  Any help would be appreciated.

答:
```<code>sort -V versions.txt
</code>```

From man sort:

-V, --version-sort

natural sort of (version) numbers within text

See also Details about version sort.

Title: Unix sort of version numbers

Body:
I have a list of version numbers, let's say for instance that they are in a file versions.txt

1.2.100.4
1.2.3.4
10.1.2.3
9.1.2.3

I wish to sort them so that they are sorted by version.  i.e:

1.2.3.4
1.2.100.4
9.1.2.3
10.1.2.3

I have tried using various sort commands using the "k" parameters, but do not really understand it well enough to pull it off.  Any help would be appreciated.

Body:
sort -V versions.txt

From man sort:

-V, --version-sort

natural sort of (version) numbers within text

See also Details about version sort.

ContentLicense: CC BY-SA 4.0


问:
zgeev not giving correct eigenvalue
```<code>subroutine Ceigen(n,Uf,Ud,d)
implicit none
integer ::    n,info,i,j,lwork=-1
complex(8) ::    Ud(n,n),Uf(n,n),rwork(2*n),d(n)
complex(8),allocatable :: work(:)
complex(8),dimension(1,1) :: vr,vl
allocate(work(0:n-1))
Ud=Uf
call zgeev('N','N', n, Ud, n, d, vl, 1, vr, 1, work, lwork, rwork, info)
lwork=work(1)
deallocate(work)
allocate(work(n))
call zgeev('N','N', n, Ud, n, d, vl, 1, vr, 1, work, lwork, rwork, info)

end subroutine Ceigen
</code>```

I am using this subroutine to get the eigenvalues of a large complex matrix which is not symmetric.

However, every time I am getting the following error

** On entry to ZGEEV parameter number 12 had an illegal value Note: The following floating-point exceptions are signalling:
  IEEE_UNDERFLOW_FLAG IEEE_DENORMAL

lwork is the 12th parameter. However if I don't assign lwork =work(1) I am getting every eigenvalue zero.
Can anyone help?

答:
By assigning a value to lwork during its declaration, you implicitly give it the save attribute:

```<code>integer ::    n,info,i,j,lwork=-1
</code>```

That means, that it will keep its value between function calls. In case you call Ceigen a second time, it will not be -1 for the first call, but potentially an illegal value (lwork < 2*n, see the source code).

On the other hand, if you don't change lwork, it will stay -1, and you will always query the work array size and never do any calculation.

As a remedy, separate the declaration and the assignment:

```<code>integer ::    n,info,i,j,lwork
!...
lwork=-1
</code>```

Title: zgeev not giving correct eigenvalue

Body:
subroutine Ceigen(n,Uf,Ud,d)
implicit none
integer ::    n,info,i,j,lwork=-1
complex(8) ::    Ud(n,n),Uf(n,n),rwork(2*n),d(n)
complex(8),allocatable :: work(:)
complex(8),dimension(1,1) :: vr,vl
allocate(work(0:n-1))
Ud=Uf
call zgeev('N','N', n, Ud, n, d, vl, 1, vr, 1, work, lwork, rwork, info)
lwork=work(1)
deallocate(work)
allocate(work(n))
call zgeev('N','N', n, Ud, n, d, vl, 1, vr, 1, work, lwork, rwork, info)

end subroutine Ceigen

I am using this subroutine to get the eigenvalues of a large complex matrix which is not symmetric.

However, every time I am getting the following error

** On entry to ZGEEV parameter number 12 had an illegal value Note: The following floating-point exceptions are signalling:
  IEEE_UNDERFLOW_FLAG IEEE_DENORMAL

lwork is the 12th parameter. However if I don't assign lwork =work(1) I am getting every eigenvalue zero.
Can anyone help?

Body:
By assigning a value to lwork during its declaration, you implicitly give it the save attribute:

integer ::    n,info,i,j,lwork=-1

That means, that it will keep its value between function calls. In case you call Ceigen a second time, it will not be -1 for the first call, but potentially an illegal value (lwork < 2*n, see the source code).

On the other hand, if you don't change lwork, it will stay -1, and you will always query the work array size and never do any calculation.

As a remedy, separate the declaration and the assignment:

integer ::    n,info,i,j,lwork
!...
lwork=-1


问:
SQL conditional select with for/while loop
This is the table:

```<code>Order_ID|Priority|Status
A       |3       |Normal
A       |4       |Urgent
B       |6       |Urgent
B       |7       |Normal
C       |8       |Normal
C       |9       |Urgent
</code>```

How do I select the Order_ID and Status where a row's priority is higher for that ID? For example, in this case, the output of the query given the above data should be:

```<code>A - Urgent
B - Normal
C - Urgent
</code>```

答:
One way to do it is like this:</p>

```<code>select order_id || ' - ' || status
from (
    select order_id, priority, status,
           rank() over (partition by order_id order by priority desc) ranking
    from table
)
where ranking = 1;
</code>```

Body:
This is the table:

Order_ID|Priority|Status
A       |3       |Normal
A       |4       |Urgent
B       |6       |Urgent
B       |7       |Normal
C       |8       |Normal
C       |9       |Urgent

How do I select the Order_ID and Status where a row's priority is higher for that ID? For example, in this case, the output of the query given the above data should be:

A - Urgent
B - Normal
C - Urgent

Body:
One way to do it is like this:

select order_id || ' - ' || status
from (
    select order_id, priority, status,
           rank() over (partition by order_id order by priority desc) ranking
    from table
)
where ranking = 1;


问:
JSON literal in script with escaped quotes
Why will the following give a JSON parsing error in browsers.  It looks be valid JSON saved in a literal string and then passed into a parser.  Can we not put stringifed json into a javascript string and then parse?</p>

```<code><script>
  var text='{"value": "I said, \"hello\""}';
  var selectGroupsRows =JSON.parse(text);
</script>
</code>```

答:
You need to escape your quotes twice (once for javascript, and once for JSON).

```<code>var text='{"value": "I said, \"hello\""}';
</code>```

should be

```<code>var text='{"value": "I said, \\"hello\\""}';
</code>```

Body:
You need to escape your quotes twice (once for javascript, and once for JSON).

var text='{"value": "I said, \"hello\""}';

should be

var text='{"value": "I said, \\"hello\\""}';


问:
It is possible to filter the symbols by type?
When I use goToSymbol command (php file for instance) it shows all symbols of the file (classes, methods, functions, variables, callbacks etc). In 99% of the cases I just want to see methods. How can I get a list of methods only?

答:
I don't think it's possible to list only methods, but you can add a : to the filter textbox to group results by type:

If you want to have a keybinding for this, you can pass the text that should be pre-filled via the "args" of the "workbench.action.quickOpen" command (source):

{
    "key": "<keybinding>",
    "command": "workbench.action.quickOpen",
    "args": "@:"
}
```

Unfortunately the : seems to be preselected, which might be a bug considering other "special characters" like @ and > are not.

Body:
I don't think it's possible to list only methods, but you can add a : to the filter textbox to group results by type:

If you want to have a keybinding for this, you can pass the text that should be pre-filled via the "args" of the "workbench.action.quickOpen" command (source):

{
    "key": "<keybinding>",
    "command": "workbench.action.quickOpen",
    "args": "@:"
}

Unfortunately the : seems to be preselected, which might be a bug considering other "special characters" like @ and > are not.


问:
jquery .on not work
In my DOM this is generated dynamically:

```<code><li>333107 (<span id="pos_3488">1</span>)
<span><a id="del_3488" href="#" id_mod="3488"> - </a></span></li>
</code>```

My jQuery code:

```<code>$("a[id^='del_']").on("click", function(e){
    var id_modelo   = $(this).attr("id_mod");
    var id_bloque   = $(this).parent().attr("id");
});
</code>```

But when you click on the HTML element, there is no call to the "click event".

答:
On this cases I hardly recommend the pattern "event delegation"
https://learn.jquery.com/events/event-delegation/

This is the solution in your code:

```<code>$(document).on("click", "a[id^='del_']", function(e) {
  var id_modelo   = $(this).attr("id_mod");
  var id_bloque   = $(this).parent().attr("id");
});
</code>```

The event should be assigned to a constant DOM element, in this case I'm using document but you can change it for another one.

Event delegation is the root solution for this kind of problems, frameworks as angular, react, vuejs used this pattern as a performance solution because they change the DOM often.

Title: jquery .on not work

Body:
In my DOM this is generated dynamically:

333107 (1)
 -

My jQuery code:

$("a[id^='del_']").on("click", function(e){
    var id_modelo   = $(this).attr("id_mod");
    var id_bloque   = $(this).parent().attr("id");
});

But when you click on the HTML element, there is no call to the "click event".

Body:
On this cases I hardly recommend the pattern "event delegation"
https://learn.jquery.com/events/event-delegation/

This is the solution in your code:

$(document).on("click", "a[id^='del_']", function(e) {
  var id_modelo   = $(this).attr("id_mod");
  var id_bloque   = $(this).parent().attr("id");
});

The event should be assigned to a constant DOM element, in this case I'm using document but you can change it for another one.

Event delegation is the root solution for this kind of problems, frameworks as angular, react, vuejs used this pattern as a performance solution because they change the DOM often.