问:
How can I specify which TreeViewItem Style/Template for a TreeViewItem Generated from HierarchicalDataTemplate?

The Situation:

I have two classes that are represented in a TreeView.  DiskSpec and DiskSet.  DiskSpec can exist by itself, or it can be a child of DiskSet.  I am working on enabling DragDrop functionality so that the user can drag a DiskSpec from the DiskSpec node onto a DiskSet to add it to that DiskSet.  Now all is working except for one thing.  My DragDropHelper class needs to specify in an ItemsPresenter (or related class) that that control is a drag source or a drop target.

My TreeView is set up like so: .

The Problem:

So I really need to have two TreeViewItem Styles.  Once for DiskSets (which specifies that the ItemsPresenter that will present the DiskSpecs is a DropTarget) and one for everything else which specifies that it's ItemsPresenter is a DragSource.

Unfortunately I have not seen any way to set the TreeViewItem Style or Template from the HierarchicalDataTemplate object, and there does not appear to be a way to specify that this ItemTemplate is only for a particular DataType.

Any thoughts?  Or am I missing something?

Find below some samples from my XAML.

Default TreeViewItem

See the ItemsPresenter section for an example of the DragDropHelper properties settings.

```<code><Style TargetType="{x:Type TreeViewItem}">
    <Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}"/>
    <Setter Property="Background" Value="Transparent"/>
    <Setter Property="HorizontalContentAlignment" Value="{Binding HorizontalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"/>
    <Setter Property="VerticalContentAlignment" Value="{Binding VerticalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"/>
    <Setter Property="Padding" Value="1,0,0,0"/>
    <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
    <Setter Property="FocusVisualStyle" Value="{StaticResource TreeViewItemFocusVisual}"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type TreeViewItem}">
                <Grid Margin="0,4,0,0">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="Auto" MinWidth="10"/>
                        <ColumnDefinition Width="*"/>
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto" MinHeight="27.75"/>
                        <RowDefinition/>
                    </Grid.RowDefinitions>
                    <ToggleButton x:Name="Expander" ClickMode="Press" IsChecked="{Binding IsExpanded, RelativeSource={RelativeSource TemplatedParent}}" BorderBrush="#00376206" Foreground="#00000000" Style="{DynamicResource ToggleButtonStyle1}" Grid.Column="1">
                        <ToggleButton.Background>
                            <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                                <GradientStop Color="White" Offset="0"/>
                                <GradientStop Color="#00F3EEDB" Offset="0.9"/>
                            </LinearGradientBrush>
                        </ToggleButton.Background>
                    </ToggleButton>
                    <Border x:Name="Bd" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Grid.Column="0" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="true" Grid.ColumnSpan="2" CornerRadius="7" Height="26" VerticalAlignment="Top" Margin="0,0,8,0" Background="#59000000">
                        <ContentPresenter x:Name="PART_Header" ContentSource="Header" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" Margin="5,3,0,3" VerticalAlignment="Center"/>
                    </Border>
                    <ItemsPresenter x:Name="ItemsHost" Grid.ColumnSpan="2" Grid.Column="1" Grid.Row="1" drag:DragDropHelper.IsDropTarget="False" />
                </Grid>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsExpanded" Value="false">
                        <Setter Property="Visibility" TargetName="ItemsHost" Value="Collapsed"/>
                    </Trigger>
                    <Trigger Property="HasItems" Value="false">
                        <Setter Property="Visibility" TargetName="Expander" Value="Hidden"/>
                    </Trigger>
                    <Trigger Property="IsSelected" Value="true">
                        <Setter Property="BitmapEffect" TargetName="Bd">
                            <Setter.Value>
                                <DropShadowBitmapEffect />
                            </Setter.Value>
                        </Setter>
                        <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}"/>
                        <Setter Property="Background" TargetName="Bd">
                            <Setter.Value>
                                <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                                    <GradientStop Color="#FF5C5C5C" Offset="0.27"/>
                                    <GradientStop Color="#FF585858" Offset="1"/>
                                    <GradientStop Color="#FF747474" Offset="0"/>
                                </LinearGradientBrush>
                            </Setter.Value>
                        </Setter>
                    </Trigger>
                    <MultiTrigger>
                        <MultiTrigger.Conditions>
                            <Condition Property="IsSelected" Value="true"/>
                            <Condition Property="IsSelectionActive" Value="false"/>
                        </MultiTrigger.Conditions>
                        <Setter Property="Background" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"/>
                        <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
                    </MultiTrigger>
                    <Trigger Property="IsEnabled" Value="false">
                        <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Style.Triggers>
        <Trigger Property="VirtualizingStackPanel.IsVirtualizing" Value="true">
            <Setter Property="ItemsPanel">
                <Setter.Value>
                    <ItemsPanelTemplate>
                        <VirtualizingStackPanel/>
                    </ItemsPanelTemplate>
                </Setter.Value>
            </Setter>
        </Trigger>
    </Style.Triggers>
</Style>
</code>```

TreeView structure

```<code><TreeView x:Name="treeView" Margin="4,40,4,4" Style="{DynamicResource SnazzyTreeView}" >
    <TreeView.Resources>

    </TreeView.Resources>
    <TreeViewItem ItemsSource="{Binding Disks}" IsExpanded="True" drag:DragDropHelper.IsDragSource="True" drag:DragDropHelper.IsDropTarget="False" drag:DragDropHelper.DragDropTemplate="{StaticResource draggedDisk}">
        <TreeViewItem.Header>
            <TextBlock Text="Disks" Foreground="White" FontSize="16"/>
        </TreeViewItem.Header>
    </TreeViewItem>
    <TreeViewItem ItemsSource="{Binding DiskSets}" IsExpanded="True">
        <TreeViewItem.Header>
            <TextBlock Text="DiskSets" Foreground="White" FontSize="16"/>
        </TreeViewItem.Header>
    </TreeViewItem>
</TreeView>
</code>```

Bea Stolnitz's Blog Post: How can I drag and drop items between data bound ItemsControls?

答:
Why do you need a style for a TreeViewItem?
It can be done using DataTemplates only, and don't specify a key if you want them to apply automatically.

```<code><Window.Resources>
    <DataTemplate DataType = "{x:Type local:DiskSpec}">
        <TextBlock Text="{Binding Title}" drag:DragDropHelper.IsDragSource="True"
                   drag:DragDropHelper.IsDropTarget="False"/>
    </DataTemplate>

    <HierarchicalDataTemplate DataType = "{x:Type local:DiskSet}"
                            ItemsSource = "{Binding Path=Disks}">
        <TextBlock Text="{Binding Title}"/>
    </HierarchicalDataTemplate>

</Window.Resources>
</code>```

```<code>tree.ItemsSource = new object[]{
            new DiskSpec{Title = "Disc 1"},
            new DiskSpec{Title = "Disc 2"},
            new DiskSet{Title = "Set 1", Disks = new List<DiskSpec>{new DiskSpec{Title="Disc 1.1"}}},
            new DiskSet{Title = "Set 2", Disks = new List<DiskSpec>{new DiskSpec{Title="Disc 2.1"}, new DiskSpec{Title="Disc 2.2"}}}};
</code>```

After that you can enable drag in the Disk template and drop in the Set template.

Body:
The Situation:

I have two classes that are represented in a TreeView.  DiskSpec and DiskSet.  DiskSpec can exist by itself, or it can be a child of DiskSet.  I am working on enabling DragDrop functionality so that the user can drag a DiskSpec from the DiskSpec node onto a DiskSet to add it to that DiskSet.  Now all is working except for one thing.  My DragDropHelper class needs to specify in an ItemsPresenter (or related class) that that control is a drag source or a drop target.

My TreeView is set up like so: .

The Problem:

So I really need to have two TreeViewItem Styles.  Once for DiskSets (which specifies that the ItemsPresenter that will present the DiskSpecs is a DropTarget) and one for everything else which specifies that it's ItemsPresenter is a DragSource.

Unfortunately I have not seen any way to set the TreeViewItem Style or Template from the HierarchicalDataTemplate object, and there does not appear to be a way to specify that this ItemTemplate is only for a particular DataType.

Any thoughts?  Or am I missing something?

Find below some samples from my XAML.

Default TreeViewItem

See the ItemsPresenter section for an example of the DragDropHelper properties settings.

</Style>

TreeView structure

<TreeView x:Name="treeView" Margin="4,40,4,4" Style="{DynamicResource SnazzyTreeView}" >
    <TreeView.Resources>

    </TreeView.Resources>
    <TreeViewItem ItemsSource="{Binding Disks}" IsExpanded="True" drag:DragDropHelper.IsDragSource="True" drag:DragDropHelper.IsDropTarget="False" drag:DragDropHelper.DragDropTemplate="{StaticResource draggedDisk}">
        <TreeViewItem.Header>
            <TextBlock Text="Disks" Foreground="White" FontSize="16"/>
        </TreeViewItem.Header>
    </TreeViewItem>
    <TreeViewItem ItemsSource="{Binding DiskSets}" IsExpanded="True">
        <TreeViewItem.Header>
            <TextBlock Text="DiskSets" Foreground="White" FontSize="16"/>
        </TreeViewItem.Header>
    </TreeViewItem>
</TreeView>

Bea Stolnitz's Blog Post: How can I drag and drop items between data bound ItemsControls?

Body:
Why do you need a style for a TreeViewItem?
It can be done using DataTemplates only, and don't specify a key if you want them to apply automatically.

<Window.Resources>
    <DataTemplate DataType = "{x:Type local:DiskSpec}">
        <TextBlock Text="{Binding Title}" drag:DragDropHelper.IsDragSource="True"
                   drag:DragDropHelper.IsDropTarget="False"/>
    </DataTemplate>

    <HierarchicalDataTemplate DataType = "{x:Type local:DiskSet}"
                            ItemsSource = "{Binding Path=Disks}">
        <TextBlock Text="{Binding Title}"/>
    </HierarchicalDataTemplate>

</Window.Resources>

tree.ItemsSource = new object[]{
            new DiskSpec{Title = "Disc 1"},
            new DiskSpec{Title = "Disc 2"},
            new DiskSet{Title = "Set 1", Disks = new List<DiskSpec>{new DiskSpec{Title="Disc 1.1"}}},
            new DiskSet{Title = "Set 2", Disks = new List<DiskSpec>{new DiskSpec{Title="Disc 2.1"}, new DiskSpec{Title="Disc 2.2"}}}};

After that you can enable drag in the Disk template and drop in the Set template.


来源: stackexchange

问:
". was unexpected at this time" generated from batch script line 'if exist [file] (...
relevant code looks like this:

```<code>cd /d %~dp0

if exist filename.txt (
    echo %date% %time% *** text... >> filename2.txt
    echo ==============================
    echo ===  text.......           ===
    echo ===  text.......           ===
    echo ===  text....... (text...) ===
    echo ===  text (text...
    echo ===  text...).
    :loop
        set /p "varx= text: "
    if "%varx%" neq "xxxx" goto loop

 ... more script...

)
</code>```

Have searched high and low for solutions...

was pointed in direction of If statement groupings here:
https://www.petri.com/forums/forum/windows-scripting/general-scripting/57625-if-exists-file-was-unexpected-at-this-time  - NO GO

was pointed in direction of problems with loops in If blocks, here:
(Windows batch) Goto within if block behaves very strangely  - NO GO

Was pointed in direction of using @setlocal enabledelayedexpansion or @setlocal enableextensions (can't track down where) - NO GO

tried passing filename via set /p varfile="filename" and if exist %varfile% - NO GO

of course thought there were other parts of code causing error -- NO GO

The thing is that this WAS working for a long while...then I changed what I thought was some innocuous stuff and cannot figure out where the problem lies...

such an obscure problem to solve..ugh!

答:
The entire compound-statement from the if exist ... ( through to the closing parenthesis is a code block.

Within a code block, labels are not allowed, an un-escaped ) will terminate the block and any %var% is replaced by that variable's value when the block is encountered.

You need to call the :loop routine (easiest way)

```<code>if exist filename.txt (
    echo %date% %time% *** text... >> filename2.txt
    echo ==============================
    echo ===  text.......           ===
    echo ===  text.......           ===
    echo ===  text....... (text...^) ===
    echo ===  text (text...
    echo ===  text...^).
    call :loop

 ... more script...

)
</code>```

... etc

goto :eof

:loop
        set /p "varx= text: "
    if "%varx%" neq "xxxx" goto loop

goto :eof

Note the goto :eof is defined to be "go to end-of-file" (The colon is required)

Note the call has a colon before the label - this indicates it's an internal routine - it resides in this batchfile

Note that each ) is now escaped by a ^ which makes ) an ordinary character, not a statement-terminator.

You've probably removed a redirector - any echo within the called procedure will be gathered into the redirected output - that is if you have

```<code>(
whatever...
)>filename
</code>```

then any data echoed within the code block will be redirected to the file - including echoes within a called procedure. You can explicitly redirect an echo within such a block or procedure using echo to console>con for instance.

Encasing any sequence of lines in parentheses, making it a code block allows redirection of the echoed output from the block, so

```<code>(
 echo this
 echo that
)>filename
</code>```

creates a new filename containing the sum of the echoes rather than having to append >>filename to each line. Obviously, >> in place of > will append to any existing file in the usual manner.

ContentLicense: CC BY-SA 3.0

Body:
relevant code looks like this:

cd /d %~dp0

if exist filename.txt (
    echo %date% %time% *** text... >> filename2.txt
    echo ==============================
    echo ===  text.......           ===
    echo ===  text.......           ===
    echo ===  text....... (text...) ===
    echo ===  text (text...
    echo ===  text...).
    :loop
        set /p "varx= text: "
    if "%varx%" neq "xxxx" goto loop

 ... more script...

)

Have searched high and low for solutions...

was pointed in direction of If statement groupings here:
https://www.petri.com/forums/forum/windows-scripting/general-scripting/57625-if-exists-file-was-unexpected-at-this-time  - NO GO

was pointed in direction of problems with loops in If blocks, here:
(Windows batch) Goto within if block behaves very strangely  - NO GO

Was pointed in direction of using @setlocal enabledelayedexpansion or @setlocal enableextensions (can't track down where) - NO GO

tried passing filename via set /p varfile="filename" and if exist %varfile% - NO GO

of course thought there were other parts of code causing error -- NO GO

The thing is that this WAS working for a long while...then I changed what I thought was some innocuous stuff and cannot figure out where the problem lies...

such an obscure problem to solve..ugh!

Body:
The entire compound-statement from the if exist ... ( through to the closing parenthesis is a code block.

Within a code block, labels are not allowed, an un-escaped ) will terminate the block and any %var% is replaced by that variable's value when the block is encountered.

You need to call the :loop routine (easiest way)

if exist filename.txt (
    echo %date% %time% *** text... >> filename2.txt
    echo ==============================
    echo ===  text.......           ===
    echo ===  text.......           ===
    echo ===  text....... (text...^) ===
    echo ===  text (text...
    echo ===  text...^).
    call :loop

 ... more script...

)

... etc

goto :eof

:loop
        set /p "varx= text: "
    if "%varx%" neq "xxxx" goto loop

goto :eof

Note the goto :eof is defined to be "go to end-of-file" (The colon is required)

Note the call has a colon before the label - this indicates it's an internal routine - it resides in this batchfile

Note that each ) is now escaped by a ^ which makes ) an ordinary character, not a statement-terminator.

You've probably removed a redirector - any echo within the called procedure will be gathered into the redirected output - that is if you have

(
whatever...
)>filename

then any data echoed within the code block will be redirected to the file - including echoes within a called procedure. You can explicitly redirect an echo within such a block or procedure using echo to console>con for instance.

Encasing any sequence of lines in parentheses, making it a code block allows redirection of the echoed output from the block, so

(
 echo this
 echo that
)>filename

creates a new filename containing the sum of the echoes rather than having to append >>filename to each line. Obviously, >> in place of > will append to any existing file in the usual manner.


问:
How to set Recyclerview to show only 4 tiles
So, ive implemented a RecyclerView which has 15 items, now what I want to do is to restrict the RecyclerView to 4 items when I click a button and vice versa, i'm not sure how to do that, this is what I have done, any inputs would be helpful

```<code>floatingButton.Click += delegate {
            if (clicked)
            {
                Toast.MakeText(this, "Has been clicked before", ToastLength.Short).Show();
                recyclerview_layoutmanger = new GridLayoutManager(this,, 2);
                myRecyclerview.SetLayoutManager(recyclerview_layoutmanger);
                recyclerview_adapter.NotifyDataSetChanged();
                clicked = false;
            }
            else {
                recyclerview_layoutmanger = new LinearLayoutManager(this, LinearLayoutManager.Vertical, false);
                Toast.MakeText(this, "Has not been clicked before", ToastLength.Short).Show();
                myRecyclerview.SetLayoutManager(recyclerview_layoutmanger);
                recyclerview_adapter.NotifyDataSetChanged();
                clicked = true;
            }
        };
</code>```

Adapter Class

```<code>  public class RecyclerAdapter : RecyclerView.Adapter
    {
        public event EventHandler<int> ItemClick;

        private readonly List<MessageList> messages;

        public RecyclerAdapter(List<MessageList> messages)
        {
            this.messages = messages;
            NotifyDataSetChanged();
        }

        public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
        {
            var movieViewHolder = (MessageViewHolder)holder;
            movieViewHolder.messageView.Text = messages[position].Message;
            movieViewHolder.dateView.Text = messages[position].messageDate;
            // movieViewHolder.MovieImageView.SetImageResource(Resource.Drawable.starwarslogo);
        }

        public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
        {
            var layout = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.messages_list_layout, parent, false);

            return new MessageViewHolder(layout, OnItemClick);

        }

        public override int ItemCount
        {
            get { return messages.Count; }
        }

        void OnItemClick(int position)
        {
            if (ItemClick != null)
                ItemClick(this, position);
        }
    }

        /// <summary>
        /// Called after <c><see cref="M:Android.App.Activity.OnRestoreInstanceState(Android.OS.Bundle)" /></c>, <c><see cref="M:Android.App.Activity.OnRestart" /></c>, or
        /// <c><see cref="M:Android.App.Activity.OnPause" /></c>, for your activity to start interacting with the user.
        /// </summary>
        protected override void OnResume()
    {
        var toggle = new ActionBarDrawerToggle(this, this.DrawerLayout, this.AppToolbar, 0, 0);
        this.DrawerLayout.AddDrawerListener(toggle);
        toggle.SyncState();

        base.OnResume();
    }
</code>```

But this just changes the layout to a side by side kinda thing

答:
Your RecyclerView is powered by your adapter.

The no of items it displays is equal to the ItemCount you give in your adapter.

You can change it by adding a public method in the adapter to change your dataset:

```<code>public void SetMessages(List<MessageList> newDataset) {
    messages = newDataset;
}
</code>```

And you can use this method like this:

```<code>adapter.SetMessages(myMessages); // myMessages is a List<MessageList> containing 4 objects
recyclerView.NotifyDataSetChanged();
</code>```

Edit:

In your case to show only 4 items from a list of 15 items you can call SetMessages like this:

```<code>// oldList is your list containing 15 items
adapter.SetMessages(new List(oldList.GetRange(0, 4)));
recyclerView.NotifyDataSetChanged();
</code>```

Body:
So, ive implemented a RecyclerView which has 15 items, now what I want to do is to restrict the RecyclerView to 4 items when I click a button and vice versa, i'm not sure how to do that, this is what I have done, any inputs would be helpful

floatingButton.Click += delegate {
            if (clicked)
            {
                Toast.MakeText(this, "Has been clicked before", ToastLength.Short).Show();
                recyclerview_layoutmanger = new GridLayoutManager(this,, 2);
                myRecyclerview.SetLayoutManager(recyclerview_layoutmanger);
                recyclerview_adapter.NotifyDataSetChanged();
                clicked = false;
            }
            else {
                recyclerview_layoutmanger = new LinearLayoutManager(this, LinearLayoutManager.Vertical, false);
                Toast.MakeText(this, "Has not been clicked before", ToastLength.Short).Show();
                myRecyclerview.SetLayoutManager(recyclerview_layoutmanger);
                recyclerview_adapter.NotifyDataSetChanged();
                clicked = true;
            }
        };

Adapter Class

  public class RecyclerAdapter : RecyclerView.Adapter
    {
        public event EventHandler<int> ItemClick;

        private readonly List<MessageList> messages;

        public RecyclerAdapter(List<MessageList> messages)
        {
            this.messages = messages;
            NotifyDataSetChanged();
        }

        public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
        {
            var movieViewHolder = (MessageViewHolder)holder;
            movieViewHolder.messageView.Text = messages[position].Message;
            movieViewHolder.dateView.Text = messages[position].messageDate;
            // movieViewHolder.MovieImageView.SetImageResource(Resource.Drawable.starwarslogo);
        }

        public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
        {
            var layout = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.messages_list_layout, parent, false);

            return new MessageViewHolder(layout, OnItemClick);

        }

        public override int ItemCount
        {
            get { return messages.Count; }
        }

        void OnItemClick(int position)
        {
            if (ItemClick != null)
                ItemClick(this, position);
        }
    }

        ///
        /// Called after <c><see cref="M:Android.App.Activity.OnRestoreInstanceState(Android.OS.Bundle)" /></c>, <c><see cref="M:Android.App.Activity.OnRestart" /></c>, or
        /// <c><see cref="M:Android.App.Activity.OnPause" /></c>, for your activity to start interacting with the user.
        ///
        protected override void OnResume()
    {
        var toggle = new ActionBarDrawerToggle(this, this.DrawerLayout, this.AppToolbar, 0, 0);
        this.DrawerLayout.AddDrawerListener(toggle);
        toggle.SyncState();

        base.OnResume();
    }

But this just changes the layout to a side by side kinda thing

Body:
Your RecyclerView is powered by your adapter.

The no of items it displays is equal to the ItemCount you give in your adapter.

You can change it by adding a public method in the adapter to change your dataset:

public void SetMessages(List<MessageList> newDataset) {
    messages = newDataset;
}

And you can use this method like this:

adapter.SetMessages(myMessages); // myMessages is a List<MessageList> containing 4 objects
recyclerView.NotifyDataSetChanged();

Edit:

In your case to show only 4 items from a list of 15 items you can call SetMessages like this:

// oldList is your list containing 15 items
adapter.SetMessages(new List(oldList.GetRange(0, 4)));
recyclerView.NotifyDataSetChanged();


问:
Pure C OpenCL vs Python OpenCL performance
I am looking for performance measurement between Python wrapper to OpenCL and Pure C OpenCL. Performance measurements can varies with time, memory, etc..
- Are there any benchmarks available?
- What should be the expectation about the time performance differences?
- What kind of tasks (parallel of course...) should make a difference?</p>

答:
There is a benchmark here: https://github.com/bennylp/saxpy-benchmark, comparing PyOpenCL against OpenCL as well as other frameworks/methods such as CUDA, plain C++, Numpy, R, Octave, and even TensorFlow (disclaimer: I'm the author)

According to the benchmark results, the performance difference between OpenCL and PyOpenCL varies too wildly. The PyOpenCL GPU target is almost 7x slower than OpenCL, but for the CPU target PyOpenCL is actually more than 2x faster than OpenCL!


问:
textarea keyup event for submit
Here in my code I am having a textarea, where after user typed anything and press enter then some code need to be executed, but if the user press shift+enter then a new line should come in the textarea only. Below is my code so far --

```<code><textarea id="commentarea<?php echo $row[slno]; ?>" class="secondtextareay pull-left" rows="2" cols="50" placeholder="Post comments here..." onkeyup="enter_comment(<?php echo $row['slno']; ?>,<?php echo $CUID; ?>);"></textarea>

<script type="text/javascript">
function enter_comment(postid,userpostedid) {
       if (event.which == 13) {
           document.getElementById('commentarea'+postid).value='';
           //insert_comment(id); // Call any function here: Just pass your actual Parameters to enter_comment().
       }
       else
       {
           return;
       }
}
</script>
</code>```

Now, when I am pressing enter, it's working fine, but if I press shift+enter, then also it is doing the same. I want to prevent this, kindly help.

答:
It is better to use onkeydown

onkeydown is fired when the key is down

instead of onkeyup

onkeyup is fired when the key is released

You can check shiftkey is pressed by event.shiftKey(true/false)

```<code><script type="text/javascript">
function enter_comment(postid,userpostedid) {
       if (event.which == 13 && !event.shiftKey) {
           document.getElementById('commentarea'+postid).value='';
           event.preventDefault();
           //insert_comment(id); // Call any function here: Just pass your actual Parameters to enter_comment().
       }
}
</script>
</code>```

Title: textarea keyup event for submit

Body:
Here in my code I am having a textarea, where after user typed anything and press enter then some code need to be executed, but if the user press shift+enter then a new line should come in the textarea only. Below is my code so far --

<textarea id="commentarea<?php echo $row[slno]; ?>" class="secondtextareay pull-left" rows="2" cols="50" placeholder="Post comments here..." onkeyup="enter_comment(<?php echo $row['slno']; ?>,<?php echo $CUID; ?>);"></textarea>

Now, when I am pressing enter, it's working fine, but if I press shift+enter, then also it is doing the same. I want to prevent this, kindly help.

Body:
It is better to use onkeydown

onkeydown is fired when the key is down

instead of onkeyup

onkeyup is fired when the key is released

You can check shiftkey is pressed by event.shiftKey(true/false)

<script type="text/javascript">
function enter_comment(postid,userpostedid) {
       if (event.which == 13 && !event.shiftKey) {
           document.getElementById('commentarea'+postid).value='';
           event.preventDefault();
           //insert_comment(id); // Call any function here: Just pass your actual Parameters to enter_comment().
       }
}
</script>


问:
How do I get firebuglite to load opened?
here's the code I have so far:

```<code>    var scriptTag = document.createElement('script');
    scriptTag.type = "text/javascript";
    scriptTag.src = 'http://getfirebug.com/firebug-lite.js';
    document.getElementsByTagName('head')[0].appendChild(scriptTag);
    var ready = function() {console.log('test');};
    scriptTag.onreadystatechange = function () {
        if (scriptTag.readyState == 'complete') {
            ready();
        }
    }
    scriptTag.onload = ready;
</code>```

The problem is that when I use it, firebug just sits there in the lower right corner. I would like it to actually open up and show the log message.

It's the difference between here and this

What is that bookmarklet doing different?

答: Figured it out. Demo: here I just needed to add '#startOpened' to the end of the url</p>

ContentLicense: CC BY-SA 2.5

Body:
here's the code I have so far:

    var scriptTag = document.createElement('script');
    scriptTag.type = "text/javascript";
    scriptTag.src = 'http://getfirebug.com/firebug-lite.js';
    document.getElementsByTagName('head')[0].appendChild(scriptTag);
    var ready = function() {console.log('test');};
    scriptTag.onreadystatechange = function () {
        if (scriptTag.readyState == 'complete') {
            ready();
        }
    }
    scriptTag.onload = ready;

The problem is that when I use it, firebug just sits there in the lower right corner. I would like it to actually open up and show the log message.

It's the difference between here and this

What is that bookmarklet doing different?


问:
Error 403 Forbidden, When Logged in for almost 5 Minutes in Laravel App
I recently uploaded my laravel project to production server through git. Now Every time I browse my website, it works fine but when I logged in then after 4,5 minutes I start seeing error 403 Forbidden (You don't have permission to access / on this server.)

Then I clear the site's cookies from browser and it works fine again.

What could be the reason ? how can I fix this permanently ? I tried searching on internet and found something which is saying that it has something to do with login session. But I could not figured out what it is. Please help me to resolve this.

答: Thanks for helping. I figured out that the problem was with my user's permission. Which I fixed and its working good.Thanks </p>


问:
Unable to export generator functions
When attempting to export a generator function in order to use in a Redux-Saga, ES-Lint is telling me that I have an error in my code:

```<code>[eslint] Expected a function declaration. (func-style)
</code>```

It exports just fine the way that it is currently, and the rule is currently being ignored:

```<code>/*eslint-disable func-style*/
const myExampleSaga = function* () {
        yield takeEvery('DO_SOMETHING_REQUEST', andDoThisFunc);
};
export default myExampleSaga;
</code>```

I am more or less okay with the fact that ES-Lint does not support generators (or at least it would seem that way), however I would like to know why the following code does not work:

```<code>export default function* () {
    yield takeEvery('DO_SOMETHING_REQUEST', andDoThisFunc);
}
</code>```

With the following error message:

```<code>undefined is not an object (evaluating 'regeneratorRuntime.mark')
</code>```

The error message is being thrown from my rootSaga, which looks like this:

```<code>/*eslint-disable func-style*/
export const rootSaga = function* rootSaga() {
    yield all([
        spawn(myExampleSaga)
    ]);
};
</code>```

Can anyone tell me why the above code is invalid? I think it has something to do with hoisting, however I was not able to find any reason why that would be invalid.

答:
Can anyone tell me why the above code is invalid?

This is well-known issue of regenerator-transform babel plugin, which is commonly used for transpiling code with sagas. That issue also affects async functions, because they are implemented by regenerator-transform mechanism too.

```<code>export default function* () {
    yield takeEvery('DO_SOMETHING_REQUEST', andDoThisFunc);
}
</code>```

After transforming that code , there can be two issues. First is omitting inclusion of regenerator-runtime dependency, which is mandatory. Second is function hoisting, so if occurrence order matters, it should be specified implicitly.

Correct solution is:

```<code>import 'regenerator-runtime';
const mySaga = function* () {
    yield takeEvery('DO_SOMETHING_REQUEST', andDoThisFunc);
}
export default mySaga;
</code>```

Title: Unable to export generator functions

Body:
When attempting to export a generator function in order to use in a Redux-Saga, ES-Lint is telling me that I have an error in my code:

[eslint] Expected a function declaration. (func-style)

It exports just fine the way that it is currently, and the rule is currently being ignored:

/*eslint-disable func-style*/
const myExampleSaga = function* () {
        yield takeEvery('DO_SOMETHING_REQUEST', andDoThisFunc);
};
export default myExampleSaga;

I am more or less okay with the fact that ES-Lint does not support generators (or at least it would seem that way), however I would like to know why the following code does not work:

export default function* () {
    yield takeEvery('DO_SOMETHING_REQUEST', andDoThisFunc);
}

With the following error message:

undefined is not an object (evaluating 'regeneratorRuntime.mark')

The error message is being thrown from my rootSaga, which looks like this:

/*eslint-disable func-style*/
export const rootSaga = function* rootSaga() {
    yield all([
        spawn(myExampleSaga)
    ]);
};

Can anyone tell me why the above code is invalid? I think it has something to do with hoisting, however I was not able to find any reason why that would be invalid.

Body:
Can anyone tell me why the above code is invalid?

This is well-known issue of regenerator-transform babel plugin, which is commonly used for transpiling code with sagas. That issue also affects async functions, because they are implemented by regenerator-transform mechanism too.

export default function* () {
    yield takeEvery('DO_SOMETHING_REQUEST', andDoThisFunc);
}

After transforming that code , there can be two issues. First is omitting inclusion of regenerator-runtime dependency, which is mandatory. Second is function hoisting, so if occurrence order matters, it should be specified implicitly.

Correct solution is:

import 'regenerator-runtime';
const mySaga = function* () {
    yield takeEvery('DO_SOMETHING_REQUEST', andDoThisFunc);
}
export default mySaga;


问:
Can a reference to an element inside an std::map be invalidated?
I have a multi-threaded application and a shared resource std::map<KeyType, ElementType>. I use a mutex to protect inserts, gets and removes.

My get method returns a reference to the stored element (unlocks on return), and then I do some work with that element.

Question: Is it possible that while working with the stored element reference, another thread may change the std::map so the element will be moved to a different address and the reference will no longer be valid? (I know there are certain ADT implementations which do rearrangement of the ADT on resize).

答:
Another thread may erase the element, or destroy the map, which would of course also invalidate the element.

Erasing an element only invalidates iterators and refewrences to this element. Insertion does not invalidate iterators or references into the map.

(that's what the second-hand documentation says, at least - and it's an assumption I hold that never was invalidated, if anecdotal evidence counts.)

Another problem remains: Manipulation of the element through the returned reference is not thread safe. You need to sync e.g. per element - and make sure you don't violate lock hierarchy.


答:
The iterator invalidation rule for associative containers (which std::map is) says at [associative.reqmts]/9:

The insert and emplace members shall not affect the validity of
  iterators and references to the container, and the erase members shall
  invalidate only iterators and references to the erased elements.

So if one thread inserts an element, it won't affect any references to existing elements. But if it removes something, other threads may be borked. Some form of element-wise locking is in order, I'd say.

Title: Can a reference to an element inside an std::map be invalidated?

Body:
I have a multi-threaded application and a shared resource std::map<KeyType, ElementType>. I use a mutex to protect inserts, gets and removes.

My get method returns a reference to the stored element (unlocks on return), and then I do some work with that element.

Question: Is it possible that while working with the stored element reference, another thread may change the std::map so the element will be moved to a different address and the reference will no longer be valid? (I know there are certain ADT implementations which do rearrangement of the ADT on resize).


问:
Docker - "127.0.0.1" is not a valid port - Django
Hi I have a django app that I am currently moving to docker and ducker hub to start testing. I currently have the docker file and the project is building. There is an issue that is coming up when trying to run the

```<code>python manage.py runserver command.
</code>```

It is saying that there is the following issue:

```<code>omars-mbp:helloworld omarjandali$ docker run omaryap/helloworld
CommandError: "127.0.0.1" is not a valid port number or address:port pair.
</code>```

Here is my docker file for the django project I am currently running. If anyone can help me with this.

```<code>FROM python:3
WORKDIR hello
COPY requirements.txt ./
EXPOSE 8000
RUN pip install -r requirements.txt
COPY . .
CMD ["python", "manage.py", "runserver", "127.0.0.1"]
</code>```

答:
From the Dockerfile you provided I assume that the application is running on port 8000, so it should be:

```<code>FROM python:3
WORKDIR hello
COPY requirements.txt ./
EXPOSE 8000
RUN pip install -r requirements.txt
COPY . .
CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]
</code>```

What was clearly explained in the message:

CommandError: "127.0.0.1" is not a valid port number or address:port pair.

Body:
Hi I have a django app that I am currently moving to docker and ducker hub to start testing. I currently have the docker file and the project is building. There is an issue that is coming up when trying to run the

python manage.py runserver command.

It is saying that there is the following issue:

omars-mbp:helloworld omarjandali$ docker run omaryap/helloworld
CommandError: "127.0.0.1" is not a valid port number or address:port pair.

Here is my docker file for the django project I am currently running. If anyone can help me with this.

FROM python:3
WORKDIR hello
COPY requirements.txt ./
EXPOSE 8000
RUN pip install -r requirements.txt
COPY . .
CMD ["python", "manage.py", "runserver", "127.0.0.1"]

Body:
From the Dockerfile you provided I assume that the application is running on port 8000, so it should be:

FROM python:3
WORKDIR hello
COPY requirements.txt ./
EXPOSE 8000
RUN pip install -r requirements.txt
COPY . .
CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]

What was clearly explained in the message:

CommandError: "127.0.0.1" is not a valid port number or address:port pair.


问:
File upload in vuetify
I'm using Vuetify.js components for my front-end in Vue.js and want to create a user registration form with file upload. I'm able to create the form using v-text-field (a Vuetify component).

How can I upload the file that is selected (input)?

Which component should I use or is there any other alternative way?

答:
Vue JS do not have file-input feature till today, so you can tweak v-text-field to work like image input field. The concept is, create an file input field and then hide it using css, and add an event in v-text-field to trigger that specific file input field to upload image. I have attached snippet please do play with that, and I also do have a fiddle created using vue and vuetify, visit here. Thanks!

new Vue({
  el: '#app',
  data: () => ({
    title: "Image Upload",
    dialog: false,
    imageName: '',
    imageUrl: '',
    imageFile: ''
  }),

  methods: {
    pickFile() {
      this.$refs.image.click()
    },

    onFilePicked(e) {
      const files = e.target.files
      if (files[0] !== undefined) {
        this.imageName = files[0].name
        if (this.imageName.lastIndexOf('.') <= 0) {
          return
        }
        const fr = new FileReader()
        fr.readAsDataURL(files[0])
        fr.addEventListener('load', () => {
          this.imageUrl = fr.result
          this.imageFile = files[0] // this is an image file that can be sent to server...
        })
      } else {
        this.imageName = ''
        this.imageFile = ''
        this.imageUrl = ''
      }
    }
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href='https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons' rel="stylesheet">
<link href="https://unpkg.com/vuetify/dist/vuetify.min.css" rel="stylesheet">
<div id="app">
  <v-app>
    <v-toolbar dark color="primary">
      <v-toolbar-side-icon></v-toolbar-side-icon>
      <v-toolbar-title class="white--text">{{ title }}</v-toolbar-title>
      <v-spacer></v-spacer>
      <v-btn icon @click="dialog = !dialog">
        <v-icon>link</v-icon>
      </v-btn>
    </v-toolbar>
    <v-content>
      <v-container fluid>
        <v-flex xs12 class="text-xs-center text-sm-center text-md-center text-lg-center">
          <img :src="imageUrl" height="150" v-if="imageUrl"/>
          <v-text-field label="Select Image" @click='pickFile' v-model='imageName' prepend-icon='attach_file'></v-text-field>
          <input
            type="file"
            style="display: none"
            ref="image"
            accept="image/*"
            @change="onFilePicked"
          >
        </v-flex>
        <v-dialog v-model="dialog" max-width="290">
          <v-card>
            <v-card-title class="headline">Hello World!</v-card-title>
            <v-card-text>
              Image Upload Script in VUE JS
              <hr>
              Yubaraj Shrestha
              <br>http://yubarajshrestha.com.np/
            </v-card-text>
            <v-card-actions>
              <v-spacer></v-spacer>
              <v-btn color="green darken-1" flat="flat" @click.native="dialog = false">Close</v-btn>
            </v-card-actions>
          </v-card>
        </v-dialog>
      </v-container>
    </v-content>
  </v-app>
</div>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vuetify/dist/vuetify.js"></script></code>```

Latest version (V2.0.5) while editing this post dated Aug 11, 2019, there's a dedicated file input option. Please follow the link below for official documentation: https://vuetifyjs.com/en/components/file-inputs.

ContentLicense: CC BY-SA 4.0

Title: File upload in vuetify

Body:
Vue JS do not have file-input feature till today, so you can tweak v-text-field to work like image input field. The concept is, create an file input field and then hide it using css, and add an event in v-text-field to trigger that specific file input field to upload image. I have attached snippet please do play with that, and I also do have a fiddle created using vue and vuetify, visit here. Thanks!

new Vue({
  el: '#app',
  data: () => ({
    title: "Image Upload",
    dialog: false,
    imageName: '',
    imageUrl: '',
    imageFile: ''
  }),

  methods: {
    pickFile() {
      this.$refs.image.click()
    },

    onFilePicked(e) {
      const files = e.target.files
      if (files[0] !== undefined) {
        this.imageName = files[0].name
        if (this.imageName.lastIndexOf('.') <= 0) {
          return
        }
        const fr = new FileReader()
        fr.readAsDataURL(files[0])
        fr.addEventListener('load', () => {
          this.imageUrl = fr.result
          this.imageFile = files[0] // this is an image file that can be sent to server...
        })
      } else {
        this.imageName = ''
        this.imageFile = ''
        this.imageUrl = ''
      }
    }
  }
})

<link href='https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons' rel="stylesheet">
<link href="https://unpkg.com/vuetify/dist/vuetify.min.css" rel="stylesheet">
<div id="app">
  <v-app>
    <v-toolbar dark color="primary">
      <v-toolbar-side-icon></v-toolbar-side-icon>
      <v-toolbar-title class="white--text">{{ title }}</v-toolbar-title>
      <v-spacer></v-spacer>
      <v-btn icon @click="dialog = !dialog">
        <v-icon>link</v-icon>
      </v-btn>
    </v-toolbar>
    <v-content>
      <v-container fluid>
        <v-flex xs12 class="text-xs-center text-sm-center text-md-center text-lg-center">
          <img :src="imageUrl" height="150" v-if="imageUrl"/>
          <v-text-field label="Select Image" @click='pickFile' v-model='imageName' prepend-icon='attach_file'></v-text-field>
          <input
            type="file"
            style="display: none"
            ref="image"
            accept="image/*"
            @change="onFilePicked"
          >
        </v-flex>
        <v-dialog v-model="dialog" max-width="290">
          <v-card>
            <v-card-title class="headline">Hello World!</v-card-title>
            <v-card-text>
              Image Upload Script in VUE JS
              <hr>
              Yubaraj Shrestha
              <br>http://yubarajshrestha.com.np/
            </v-card-text>
            <v-card-actions>
              <v-spacer></v-spacer>
              <v-btn color="green darken-1" flat="flat" @click.native="dialog = false">Close</v-btn>
            </v-card-actions>
          </v-card>
        </v-dialog>
      </v-container>
    </v-content>
  </v-app>
</div>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vuetify/dist/vuetify.js"></script>

Latest version (V2.0.5) while editing this post dated Aug 11, 2019, there's a dedicated file input option. Please follow the link below for official documentation: https://vuetifyjs.com/en/components/file-inputs.


问:
ER_HOST_NOT_PRIVILEGED - docker container fails to connect to mariadb
I'm trying to get a docker container to work with mariadb and node.js images. The container will use an existing database in /home/mysql. However, when the container is launched, I'm getting this "failed to connect" error in node.js:

```<code>Error: ER_HOST_NOT_PRIVILEGED:
Host '172.18.0.5' is not allowed to connect to this MariaDB server
</code>```

Here's my docker-compose.yml:

```<code>version: '3'
services:
  mariadb:
    image: mariadb
    restart: always
    volumes:
     - /home/mysql:/var/lib/mysql
    user: "mysql"
    ports:
      - "3306:3306"
  watch:
    build: .
    restart: always
    links:
      - mariadb:mysql
    environment:
      - DOCKER_IP=172.18.0.2
    depends_on: ['mariadb']
    ports:
      - "3000:3000"
</code>```

After reading this thread, I found that mysql is actually running, but it fails to let other services connect:

These are some of the steps I have checked. As you can see, I can log in to the mysql instance:

```<code>    $ docker exec -it 552aae9ea09c bash

    mysql@552aae9ea09c:/$ mysql -u root -p
    Enter password: *******

    MariaDB [(none)]> SELECT host, user FROM mysql.user;
    +-------------+------------------+
    | host        | user             |
    +-------------+------------------+
    | 127.0.0.1   | root             |
    | ::1         | root             |
    | someusername|                  |
    | someusername| root             |
    | localhost   |                  |
    | localhost   | dbusername       |
    | localhost   | databasename     |
    | localhost   | root             |
    +-------------+------------------+
    8 rows in set (0.00 sec)

mysql@552aae9ea09c:/$ mysqld --verbose --help | grep bind-address

2017-11-13 17:35:40 139825857279872 [Note] Plugin 'FEEDBACK' is disabled.
  --bind-address=name IP address to bind to.

bind-address                                       (No default value)
</code>```

One thing to note is that even though I've explicitly set the user to mysql in the yml file, these three files in /home/mysql: ib_logfile0,ib_logfile1, ib_buffer_pool are still under the group of systemd-journal-remote, which I suspect has something to do with the connection failure.(reference)

答:
The error you are receiving is caused by the fact that MariaDB thinks you are not authorized to connect to the server. This means that you haven't created a database user for the Node.js app or the grants for that user are incorrect.

A fool-proof way to solve this is to create a separate user for the Node.js application. You can automate this by writing the following SQL into a file and mounting the volume into /docker-entrypoint-initdb.d.

```<code>CREATE USER 'my-app-user'@'%' IDENTIFIED BY 'my-app-password';
GRANT ALL ON *.* TO 'my-app-user'@'%';
</code>```

Change the username and password accordingly and reduce the given privileges from the ALL privilege. You can also change the wildcard hostname % to a specific IP address or hostname.

Body:
I'm trying to get a docker container to work with mariadb and node.js images. The container will use an existing database in /home/mysql. However, when the container is launched, I'm getting this "failed to connect" error in node.js:

Error: ER_HOST_NOT_PRIVILEGED:
Host '172.18.0.5' is not allowed to connect to this MariaDB server

Here's my docker-compose.yml:

version: '3'
services:
  mariadb:
    image: mariadb
    restart: always
    volumes:
     - /home/mysql:/var/lib/mysql
    user: "mysql"
    ports:
      - "3306:3306"
  watch:
    build: .
    restart: always
    links:
      - mariadb:mysql
    environment:
      - DOCKER_IP=172.18.0.2
    depends_on: ['mariadb']
    ports:
      - "3000:3000"

After reading this thread, I found that mysql is actually running, but it fails to let other services connect:

These are some of the steps I have checked. As you can see, I can log in to the mysql instance:

    $ docker exec -it 552aae9ea09c bash

    mysql@552aae9ea09c:/$ mysql -u root -p
    Enter password: *******

    MariaDB [(none)]> SELECT host, user FROM mysql.user;
    +-------------+------------------+
    | host        | user             |
    +-------------+------------------+
    | 127.0.0.1   | root             |
    | ::1         | root             |
    | someusername|                  |
    | someusername| root             |
    | localhost   |                  |
    | localhost   | dbusername       |
    | localhost   | databasename     |
    | localhost   | root             |
    +-------------+------------------+
    8 rows in set (0.00 sec)

mysql@552aae9ea09c:/$ mysqld --verbose --help | grep bind-address

2017-11-13 17:35:40 139825857279872 [Note] Plugin 'FEEDBACK' is disabled.
  --bind-address=name IP address to bind to.

bind-address                                       (No default value)

One thing to note is that even though I've explicitly set the user to mysql in the yml file, these three files in /home/mysql: ib_logfile0,ib_logfile1, ib_buffer_pool are still under the group of systemd-journal-remote, which I suspect has something to do with the connection failure.(reference)

Body:
The error you are receiving is caused by the fact that MariaDB thinks you are not authorized to connect to the server. This means that you haven't created a database user for the Node.js app or the grants for that user are incorrect.

A fool-proof way to solve this is to create a separate user for the Node.js application. You can automate this by writing the following SQL into a file and mounting the volume into /docker-entrypoint-initdb.d.

CREATE USER 'my-app-user'@'%' IDENTIFIED BY 'my-app-password';
GRANT ALL ON *.* TO 'my-app-user'@'%';

Change the username and password accordingly and reduce the given privileges from the ALL privilege. You can also change the wildcard hostname % to a specific IP address or hostname.


问:
PHPexcel how to get the current cell number
I am displaying a set of data using rangeToArray() on PHPexcel library
that works fine. each data is unique so i need to run another function per data, to do this i have to supply the current cell number to run my function.

```<code>$mySet = $objPHPExcel->getActiveSheet()->rangeToArray('A1:J31');

foreach ($mySet as $row) {
    echo "<tr>";
    foreach ($row as $data) {

        echo "<td>".$data."</td>";

    }
    echo "</tr>";
}
</code>```

My question is how can i get the current cell number of each data iteration?

答:
By default, rangeToArray() returns a simple enumerated array; but if you look at the arguments for the method

```<code>/**
 * Create array from a range of cells
 *
 * @param string $pRange Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1")
 * @param mixed $nullValue Value returned in the array entry if a cell doesn't exist
 * @param boolean $calculateFormulas Should formulas be calculated?
 * @param boolean $formatData Should formatting be applied to cell values?
 * @param boolean $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
 *                               True - Return rows and columns indexed by their actual row and column IDs
 * @return array
 */
</code>```

The last argument allow you to return that array indexed by row and column:

```<code>$mySet = $objPHPExcel->getActiveSheet()->rangeToArray('A1:J31', null, true, true, true);

foreach ($mySet as $rowNumber => $row) {
    echo "<tr>";
    foreach ($row as $columnAddress => $data) {

        echo "<td>".$columnAddress.$rowNumber.' = '.$data."</td>";

    }
    echo "</tr>";
}
</code>```

Body:
I am displaying a set of data using rangeToArray() on PHPexcel library
that works fine. each data is unique so i need to run another function per data, to do this i have to supply the current cell number to run my function.

$mySet = $objPHPExcel->getActiveSheet()->rangeToArray('A1:J31');

foreach ($mySet as $row) {
    echo "
";
    foreach ($row as $data) {

        echo "".$data."	";

    }
    echo "
";
}

My question is how can i get the current cell number of each data iteration?

Body:
By default, rangeToArray() returns a simple enumerated array; but if you look at the arguments for the method

/**
 * Create array from a range of cells
 *
 * @param string $pRange Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1")
 * @param mixed $nullValue Value returned in the array entry if a cell doesn't exist
 * @param boolean $calculateFormulas Should formulas be calculated?
 * @param boolean $formatData Should formatting be applied to cell values?
 * @param boolean $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
 *                               True - Return rows and columns indexed by their actual row and column IDs
 * @return array
 */

The last argument allow you to return that array indexed by row and column:

$mySet = $objPHPExcel->getActiveSheet()->rangeToArray('A1:J31', null, true, true, true);

foreach ($mySet as $rowNumber => $row) {
    echo "<tr>";
    foreach ($row as $columnAddress => $data) {

        echo "<td>".$columnAddress.$rowNumber.' = '.$data."</td>";

    }
    echo "</tr>";
}


问:
Zero all filesize in a large directory tree (delete file content, keep files)
How can I delete the content (zero the filesize) of a large directory tree (10 GB, 1K files) but keep the entire tree structure, filenames, extensions. (If I can keep the original last write time [last content modification time] that's a bonus).

I have seen several suggestions for individual files, but can not figure out the way to make this work for the entire CWD.

```<code>def deleteContent(fName):
    with open(fName, "w"):
        pass
</code>```

答:
os.walk() returns all directories as a list of following tuple:

```<code>(directory, list of folders in the directory, list of files in the directory)
</code>```

When we combine your code with os.walk():

```<code>import os

for tuple in os.walk("top_directory"):
    files = tuple[2]
    dir = tuple[0]
    for file in files:
        with open(os.path.join(dir, file), "w"):
            pass
</code>```

Body:
How can I delete the content (zero the filesize) of a large directory tree (10 GB, 1K files) but keep the entire tree structure, filenames, extensions. (If I can keep the original last write time [last content modification time] that's a bonus).

I have seen several suggestions for individual files, but can not figure out the way to make this work for the entire CWD.

def deleteContent(fName):
    with open(fName, "w"):
        pass

Body:
os.walk() returns all directories as a list of following tuple:

(directory, list of folders in the directory, list of files in the directory)

When we combine your code with os.walk():

import os

for tuple in os.walk("top_directory"):
    files = tuple[2]
    dir = tuple[0]
    for file in files:
        with open(os.path.join(dir, file), "w"):
            pass


问:
Removing list elements that have a specific name
I've got a nested list and I need to remove all the nodes/elements that have a specific name. For example, in the following defined R list(), I'd like to remove all nodes that have the name 'lol'. I note that it can appear at different levels of the hierarchy.

What's the best way to scan through the tree and remove those nodes?

```<code>tree <- list(
    A = list(
        A_1 = list(
            A_1_1 = list(), A_1_2 = list()
        ),
        lol = "haha"
    ),
    B = list(
        B_1 = list(
            B_1_1 = list(), B_1_2 = list(), lol = "rofl"
        )
    )
)
</code>```

I'd like to perform some action on the tree object so that result becomes:

```<code>$A
$A$A_1
$A$A_1$A_1_1
list()

$A$A_1$A_1_2
list()

$B
$B$B_1
$B$B_1$B_1_1
list()

$B$B_1$B_1_2
list()
</code>```

答:
You can create a simple recursive function function to remove those elements:</p>

```<code>foo <- function(x) {
  x <- x[names(x) != "lol"]
  if(is.list(x)) lapply(x, foo)
}

foo(tree)
# $A
# $A$A_1
# $A$A_1$A_1_1
# list()
#
# $A$A_1$A_1_2
# list()
#
#
#
# $B
# $B$B_1
# $B$B_1$B_1_1
# list()
#
# $B$B_1$B_1_2
# list()
</code>```

Body:
I've got a nested list and I need to remove all the nodes/elements that have a specific name. For example, in the following defined R list(), I'd like to remove all nodes that have the name 'lol'. I note that it can appear at different levels of the hierarchy.

What's the best way to scan through the tree and remove those nodes?

tree <- list(
    A = list(
        A_1 = list(
            A_1_1 = list(), A_1_2 = list()
        ),
        lol = "haha"
    ),
    B = list(
        B_1 = list(
            B_1_1 = list(), B_1_2 = list(), lol = "rofl"
        )
    )
)

I'd like to perform some action on the tree object so that result becomes:

$A
$A$A_1
$A$A_1$A_1_1
list()

$A$A_1$A_1_2
list()

$B
$B$B_1
$B$B_1$B_1_1
list()

$B$B_1$B_1_2
list()

Body:
You can create a simple recursive function function to remove those elements:

foo <- function(x) {
  x <- x[names(x) != "lol"]
  if(is.list(x)) lapply(x, foo)
}

foo(tree)
# $A
# $A$A_1
# $A$A_1$A_1_1
# list()
#
# $A$A_1$A_1_2
# list()
#
#
#
# $B
# $B$B_1
# $B$B_1$B_1_1
# list()
#
# $B$B_1$B_1_2
# list()


问:
Hitting directly a controller in codeigniter and getting json response
I am doing this in my codeigniter controller

```<code>public function getprice($origin,$destination){
    $this->load->model("flights");
    $query['data']=$this->flights->giveprice($origin,$destination);  //model gives fine result
     $this->output
    ->set_content_type('application/json')
    ->set_output(json_encode(array('foo' => $query['data'])));   //data is printed correctly

   }
</code>```

I have hitted this url with the exact this url :-

```<code>localhost/codeIgniter/index.php/booking/getprice?origin="Karachi"&destination="Lahore"
</code>```

and i am getting this as response:-

```<code> <div style="border:1px solid #990000;padding-left:20px;margin:0 0 10px 0;">
<h4>An uncaught Exception was encountered</h4>
<p>Type: ArgumentCountError</p>
<p>Message: Too few arguments to function Booking::getprice(), 0 passed in /opt/lampp/htdocs/codeIgniter/system/core/CodeIgniter.php on line 532 and exactly 2 expected</p>
<p>Filename: /opt/lampp/htdocs/codeIgniter/application/controllers/Booking.php</p>
<p>Line Number: 22</p>
<p>Backtrace:</p>
<p style="margin-left:10px">
        File: /opt/lampp/htdocs/codeIgniter/index.php
    <br />
        Line: 315
    <br />
        Function: require_once
</p>
</code>```

Another function of mine without parameters runs fine, but when parameters ("GET") are involved it says "too few arguements given", I am providing 2 arguments. Please correct me where I am doing wrong.

答:
You have call function using get parameters.
But calling in codeigniter is different than ordinary function calling.
Example: http://localhost/project/main/getproduct/24/45

See this
Passing multiple variables in URL using codeigniter

Body:
I am doing this in my codeigniter controller

public function getprice($origin,$destination){
    $this->load->model("flights");
    $query['data']=$this->flights->giveprice($origin,$destination);  //model gives fine result
     $this->output
    ->set_content_type('application/json')
    ->set_output(json_encode(array('foo' => $query['data'])));   //data is printed correctly

   }

I have hitted this url with the exact this url :-

localhost/codeIgniter/index.php/booking/getprice?origin="Karachi"&destination="Lahore"

and i am getting this as response:-

An uncaught Exception was encountered

Type: ArgumentCountError

Message: Too few arguments to function Booking::getprice(), 0 passed in /opt/lampp/htdocs/codeIgniter/system/core/CodeIgniter.php on line 532 and exactly 2 expected

Filename: /opt/lampp/htdocs/codeIgniter/application/controllers/Booking.php

Line Number: 22

Backtrace:

        File: /opt/lampp/htdocs/codeIgniter/index.php

        Line: 315

        Function: require_once

Another function of mine without parameters runs fine, but when parameters ("GET") are involved it says "too few arguements given", I am providing 2 arguments. Please correct me where I am doing wrong.


问:
passing html element using to_html in flask
I have a dataframe that contains a column containing <canvas> something </canvas> element. In a flask application, I passed this data to a template using df.to_html(), but it never is working and always shows the <canvas> within displayed html table.

<img src="https://i.stack.imgur.com/Kt6Br.png" alt="I intend to let the canvas element be captured by a chartjs function">

答: I realized that I had to utilize the option to_html(escape=False) to solve this problem


问:
Are services also destroyed when the component providing them gets destroyed?
Suppose we have the following code:

```<code>@Component(
    // ..
    providers: [SomeService]
)
export class SomeComponent {
    constructor(someService: SomeService) {}
}
</code>```

Will the someService instance be destroyed whenever SomeComponent is destroyed? Or should one manually destroy it through onDestroy() hook?

答:
As explained in this answer, providers follow the lifecycle and can have OnDestroy hook. They are destroyed when their injectors are destroyed.

If a provider belongs to component injector, it's destroyed with a component.

If a provider belongs to root injector, it's destroyed with an application.

Body:
Suppose we have the following code:

@Component(
    // ..
    providers: [SomeService]
)
export class SomeComponent {
    constructor(someService: SomeService) {}
}

Will the someService instance be destroyed whenever SomeComponent is destroyed? Or should one manually destroy it through onDestroy() hook?


问:
TableView and the home indicator on iPhone X
I am using both UITableViewController and UITableView in one project.

An UITableView in an UITableViewController overlays the home indicator on iPhone X.
But an UITableView in an UIViewController doesn't overlay the home indicator on iPhone X.
Should I fit one?
And which one is correct when I consider about safe area?

e.x.

答:
You can continue to use a UITableView on a standard UIViewController. Just set auto layout so the bottom of the tableview is flush with the bottom of the superview (and not the margin). Then set the insetsContentViewsToSafeArea property of the tableview to true

Swift:

```<code>if #available(iOS 11.0, *) {
    tableView.insetsContentViewsToSafeArea = true;
}
</code>```

Objective-C:

```<code>if (@available(iOS 11.0, *)) {
    [tableView setInsetsContentViewsToSafeArea:YES];
}
</code>```

Body:
You can continue to use a UITableView on a standard UIViewController. Just set auto layout so the bottom of the tableview is flush with the bottom of the superview (and not the margin). Then set the insetsContentViewsToSafeArea property of the tableview to true

Swift:

if #available(iOS 11.0, *) {
    tableView.insetsContentViewsToSafeArea = true;
}

Objective-C:

if (@available(iOS 11.0, *)) {
    [tableView setInsetsContentViewsToSafeArea:YES];
}


问:
XSLT: Sort by multiple items
I have XML data such as:

```<code><feed>
  <entry>
    <id>4</id>
    <updated>2011-01-18T16:55:54Z</updated>
    <title>title2</title>
  </entry>
  <entry>
    <id>3</id>
    <updated>2011-01-18T16:55:54Z</updated>
    <title>title1</title>
  </entry>
  <entry>
    <id>2</id>
    <updated>2011-01-18T16:55:54Z</updated>
    <title>title1</title>
  </entry>
  <entry>
    <id>1</id>
    <updated>2011-01-18T16:55:54Z</updated>
    <title>title</title>
  </entry>
</feed>
</code>```

And I need the outcome to result like:

```<code><feed>
  <entry>
    <id>1</id>
    <updated>2011-01-18T16:55:54Z</updated>
    <title>title</title>
  </entry>
  <entry>
    <id>2</id>
    <updated>2011-01-18T16:55:54Z</updated>
    <title>title1</title>
  </entry>
  <entry>
    <id>3</id>
    <updated>2011-01-18T16:55:54Z</updated>
    <title>title1</title>
  </entry>
  <entry>
    <id>4</id>
    <updated>2011-01-18T16:55:54Z</updated>
    <title>title2</title>
  </entry>
</feed>
</code>```

Basically I need the XSLT to sort on the title, then the ID. I have made an XSLT but the shorter times come out last (using Xerces):

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:atom="http://www.w3.org/2005/Atom"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" encoding="UTF-8" indent="yes" />

 <xsl:template match="@* | node()">
  <xsl:copy>
   <xsl:apply-templates select="@* | node()" />
  </xsl:copy>
 </xsl:template>

 <xsl:template match="atom:feed">
  <xsl:copy>
   <xsl:apply-templates select="*" />
   <xsl:for-each select="atom:entry">
    <xsl:sort select="string-length(atom:title)" order="descending" />
    <xsl:sort select="atom:title" data-type="text" order="ascending" />
    <xsl:copy-of select="."/>
   </xsl:for-each>
  </xsl:copy>
 </xsl:template>

 <xsl:template match="atom:feed/atom:entry"/>

</xsl:stylesheet>
</code>```

答:
For your input sample (not actually an Atom feed), this stylesheet:

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" />
        </xsl:copy>
    </xsl:template>
    <xsl:template match="feed">
        <xsl:copy>
            <xsl:apply-templates>
                <xsl:sort select="update" order="descending"/>
                <xsl:sort select="title"/>
                <xsl:sort select="id" data-type="number"/>
            </xsl:apply-templates>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>
</code>```

Output:

```<code><feed>
    <entry>
        <id>1</id>
        <updated>2011-01-18T16:55:54Z</updated>
        <title>title</title>
    </entry>
    <entry>
        <id>2</id>
        <updated>2011-01-18T16:55:54Z</updated>
        <title>title1</title>
    </entry>
    <entry>
        <id>3</id>
        <updated>2011-01-18T16:55:54Z</updated>
        <title>title1</title>
    </entry>
    <entry>
        <id>4</id>
        <updated>2011-01-18T16:55:54Z</updated>
        <title>title2</title>
    </entry>
</feed>
</code>```

Note: This date time format can be ordered like string (default) as long as there is no different time zone.

Title: XSLT: Sort by multiple items

Body:
I have XML data such as:

<feed>
  <entry>
    <id>4</id>
    <updated>2011-01-18T16:55:54Z</updated>
    <title>title2</title>
  </entry>
  <entry>
    <id>3</id>
    <updated>2011-01-18T16:55:54Z</updated>
    <title>title1</title>
  </entry>
  <entry>
    <id>2</id>
    <updated>2011-01-18T16:55:54Z</updated>
    <title>title1</title>
  </entry>
  <entry>
    <id>1</id>
    <updated>2011-01-18T16:55:54Z</updated>
    <title>title</title>
  </entry>
</feed>

And I need the outcome to result like:

<feed>
  <entry>
    <id>1</id>
    <updated>2011-01-18T16:55:54Z</updated>
    <title>title</title>
  </entry>
  <entry>
    <id>2</id>
    <updated>2011-01-18T16:55:54Z</updated>
    <title>title1</title>
  </entry>
  <entry>
    <id>3</id>
    <updated>2011-01-18T16:55:54Z</updated>
    <title>title1</title>
  </entry>
  <entry>
    <id>4</id>
    <updated>2011-01-18T16:55:54Z</updated>
    <title>title2</title>
  </entry>
</feed>

Basically I need the XSLT to sort on the title, then the ID. I have made an XSLT but the shorter times come out last (using Xerces):

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:atom="http://www.w3.org/2005/Atom"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" encoding="UTF-8" indent="yes" />

 <xsl:template match="@* | node()">
  <xsl:copy>
   <xsl:apply-templates select="@* | node()" />
  </xsl:copy>
 </xsl:template>

 <xsl:template match="atom:feed">
  <xsl:copy>
   <xsl:apply-templates select="*" />
   <xsl:for-each select="atom:entry">
    <xsl:sort select="string-length(atom:title)" order="descending" />
    <xsl:sort select="atom:title" data-type="text" order="ascending" />
    <xsl:copy-of select="."/>
   </xsl:for-each>
  </xsl:copy>
 </xsl:template>

 <xsl:template match="atom:feed/atom:entry"/>

</xsl:stylesheet>

Body:
For your input sample (not actually an Atom feed), this stylesheet:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" />
        </xsl:copy>
    </xsl:template>
    <xsl:template match="feed">
        <xsl:copy>
            <xsl:apply-templates>
                <xsl:sort select="update" order="descending"/>
                <xsl:sort select="title"/>
                <xsl:sort select="id" data-type="number"/>
            </xsl:apply-templates>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

Output:

<feed>
    <entry>
        <id>1</id>
        <updated>2011-01-18T16:55:54Z</updated>
        <title>title</title>
    </entry>
    <entry>
        <id>2</id>
        <updated>2011-01-18T16:55:54Z</updated>
        <title>title1</title>
    </entry>
    <entry>
        <id>3</id>
        <updated>2011-01-18T16:55:54Z</updated>
        <title>title1</title>
    </entry>
    <entry>
        <id>4</id>
        <updated>2011-01-18T16:55:54Z</updated>
        <title>title2</title>
    </entry>
</feed>

Note: This date time format can be ordered like string (default) as long as there is no different time zone.


问:
How to increase the counter value when clicking the button in java script
I am new to java script i am doing one event that is when i clicking the plus button the css style was printed but value not increase. and same as clicking menus button the last child is not removed...

i want to print the css style and incremented value and same decrease value and delete the last child........

below is my html

    var counter = 0;
    var numBoxes = 10;
    function myFun(showDiv) {
           var ele = document.getElementById(showDiv + counter);
           if(counter>numBoxes) {
                  document.getElementById("incBtn").addEventListener("click", function(){
        document.getElementById("demo").innerHTML = "Limit Is Over";
       });
           }
           else {
                  ele.style.display = "block";
           }
           if(counter>0) {
                 ele.style.display = "block";
           }
           else {
                  document.getElementById("decBtn").addEventListener("click", function(){
        document.getElementById("demo").innerHTML = "Limit Is Over";
       });
           }
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="divInfo">
      <span id="box1" style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;"></span>
      <span id="box2" style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;margin-left:10px;"></span>
      <span id="box3" style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;margin-left:10px;"></span>
      <span id="box4" style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;margin-left:10px;"></span>
      <span id="box5" style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;margin-left:10px;"></span>
      <span id="box6" style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;margin-left:10px;"></span>
      <span id="box7" style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;margin-left:10px;"></span>
      <span id="box8" style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;margin-left:10px;"></span>
      <span id="box9" style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;margin-left:10px;"></span>
      <span id="box10"style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;margin-left:10px;"></span>
     </div>
     <div class="divInfo2">
      <input type="text" id="value" value="0">
     </div>
     <div class="IncDrc">
      <input id="incBtn" type="button" value="+" onclick="counter++; myFun('box');">
      <input id="decBtn" type="button" value="-" onclick="counter--; myFun('box');">
     </div>
     <div>
      <p id="demo"></p>
     </div></code>```

答:
You can try something like this: </p>

```<code>var counter = 0;
var numBoxes = 10;
function myFun(action, showDiv) {
    if (action == 'add') {
        counter++;
    }else{
        counter--;
    }
    if (counter > 0 && counter > numBoxes) {

         document.getElementById("demo").innerHTML = "Limit Is Over";

    }
    else {
        if (counter > 0) {

            if (action == 'sub' && ((counter + 1) > 0)) {
                var lastEle = document.getElementById(showDiv +
                   (counter + 1));
                lastEle.style.display = "none";
            } else {
                var ele = document.getElementById(showDiv + counter);
                ele.style.display = "block";
            }
            var inputValue =
                 document.getElementById("value").setAttribute('value', counter);

        }
        else {

            document.getElementById("demo").innerHTML = "Limit Is Over";

        }
    }

}
</code>```

<p>And in HTML </p>

```<code><input id="incBtn" type="button" value="+" onclick="myFun('add','box');">
<input id="decBtn" type="button" value="-" onclick="myFun('sub','box');">
</code>```

Body:
I am new to java script i am doing one event that is when i clicking the plus button the css style was printed but value not increase. and same as clicking menus button the last child is not removed...

i want to print the css style and incremented value and same decrease value and delete the last child........

below is my html

    var counter = 0;
    var numBoxes = 10;
    function myFun(showDiv) {
           var ele = document.getElementById(showDiv + counter);
           if(counter>numBoxes) {
                  document.getElementById("incBtn").addEventListener("click", function(){
        document.getElementById("demo").innerHTML = "Limit Is Over";
       });
           }
           else {
                  ele.style.display = "block";
           }
           if(counter>0) {
                 ele.style.display = "block";
           }
           else {
                  document.getElementById("decBtn").addEventListener("click", function(){
        document.getElementById("demo").innerHTML = "Limit Is Over";
       });
           }
    }

      <input type="text" id="value" value="0">

      <input id="incBtn" type="button" value="+" onclick="counter++; myFun('box');">
      <input id="decBtn" type="button" value="-" onclick="counter--; myFun('box');">

Body:
You can try something like this:

var counter = 0;
var numBoxes = 10;
function myFun(action, showDiv) {
    if (action == 'add') {
        counter++;
    }else{
        counter--;
    }
    if (counter > 0 && counter > numBoxes) {

         document.getElementById("demo").innerHTML = "Limit Is Over";

    }
    else {
        if (counter > 0) {

            if (action == 'sub' && ((counter + 1) > 0)) {
                var lastEle = document.getElementById(showDiv +
                   (counter + 1));
                lastEle.style.display = "none";
            } else {
                var ele = document.getElementById(showDiv + counter);
                ele.style.display = "block";
            }
            var inputValue =
                 document.getElementById("value").setAttribute('value', counter);

        }
        else {

            document.getElementById("demo").innerHTML = "Limit Is Over";

        }
    }

}

And in HTML

<input id="incBtn" type="button" value="+" onclick="myFun('add','box');">
<input id="decBtn" type="button" value="-" onclick="myFun('sub','box');">


问:
Cardflip with Angular
I'm starting to learn AngularJS and am having trouble achieving the card flip.  When I try it with normal JQuery and using the toggleclass function on the div with the card class, it works.  When I try to use the code below, however it doesn't.  My initial card also shows the backface initially and doesn't rotate when I click rotate.  Here's my code.

Thanks in advance.

HTML/Angular

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="ISO-8859-1">
    <title>Insert title here</title>
    <link href='main.css' rel='stylesheet '/>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
</head>
<body ng-app='myApp' ng-controller='MyController'>
    <div class="main-container">
        <div class="card" ng-class="{'rotateFace': !front}">
            <div class="front">
                1
            </div>
            <div class="back">
                2
            </div>
        </div>
    </div>
    <button ng-click=rotate()>Click</button>
    <script>
     var app = angular.module('myApp', []);
     app.controller('MyController', function($scope) {
         var front = true;

         $scope.rotate = function() {
             front = !front;
         }
     });
    </script>
</body>
</html>
</code>```

CSS

```<code>@CHARSET "ISO-8859-1";

.main-container {
     width: 200px;
    height: 260px;
    position: relative;
    border: 1px solid #ccc;
    -webkit-perspective: 800px;
    -moz-perspective: 800px;
    -o-perspective: 800px;
    perspective: 800px;
}

.card {
     width: 100%;
    height: 100%;
    position: absolute;
    -webkit-transition: -webkit-transform 1s;
    -moz-transition: -moz-transform 1s;
    -o-transition: -o-transform 1s;
    transition: transform 1s;
    -webkit-transform-style: preserve-3d;
    -moz-transform-style: preserve-3d;
    -o-transform-style: preserve-3d;
    transform-style: preserve-3d;
    -webkit-transform-origin: 50% 50%;

}

.card div {
    display: block;
    height: 100%;
    width: 100%;
    line-height: 260px;
    color: white;
    text-align: center;
    font-weight: bold;
    font-size: 140px;
    position: absolute;
    -webkit-backface-visibility: hidden;
    -moz-backface-visibility: hidden;
    -o-backface-visibility: hidden;
    backface-visibility: hidden;
}
</code>```

答:
Try this?

```<code>$scope.front = true;

$scope.rotate = function() {
     $scope.front = !$scope.front;
}
</code>```

(assuming that you have a rotateFace class somewhere - like in  your main.css file?)

Title: Cardflip with Angular

Body:
I'm starting to learn AngularJS and am having trouble achieving the card flip.  When I try it with normal JQuery and using the toggleclass function on the div with the card class, it works.  When I try to use the code below, however it doesn't.  My initial card also shows the backface initially and doesn't rotate when I click rotate.  Here's my code.

Thanks in advance.

HTML/Angular

<!DOCTYPE html>

    <meta charset="ISO-8859-1">
    <title>Insert title here</title>
    <link href='main.css' rel='stylesheet '/>

                1

                2

    <button ng-click=rotate()>Click</button>

CSS

@CHARSET "ISO-8859-1";

.main-container {
     width: 200px;
    height: 260px;
    position: relative;
    border: 1px solid #ccc;
    -webkit-perspective: 800px;
    -moz-perspective: 800px;
    -o-perspective: 800px;
    perspective: 800px;
}

.card {
     width: 100%;
    height: 100%;
    position: absolute;
    -webkit-transition: -webkit-transform 1s;
    -moz-transition: -moz-transform 1s;
    -o-transition: -o-transform 1s;
    transition: transform 1s;
    -webkit-transform-style: preserve-3d;
    -moz-transform-style: preserve-3d;
    -o-transform-style: preserve-3d;
    transform-style: preserve-3d;
    -webkit-transform-origin: 50% 50%;

}

.card div {
    display: block;
    height: 100%;
    width: 100%;
    line-height: 260px;
    color: white;
    text-align: center;
    font-weight: bold;
    font-size: 140px;
    position: absolute;
    -webkit-backface-visibility: hidden;
    -moz-backface-visibility: hidden;
    -o-backface-visibility: hidden;
    backface-visibility: hidden;
}

Body:
Try this?

$scope.front = true;

$scope.rotate = function() {
     $scope.front = !$scope.front;
}

(assuming that you have a rotateFace class somewhere - like in  your main.css file?)


问:
Flexbox item is shrunk down on iOS 9 when the parent container is set as a specific height
I have encountered this bug on iOS version 9 when using with latest Boostrap 4 Beta. Basically I have a parent div and an ul element that contains multiple list items. The parent div is a flexbox with the dimensions are set to some numbers and turn on overflow for the children element. The list item is supposed to take 100% of the height of the parent. Here is the link to the demo code: https://codepen.io/nguyenthai/pen/jawzRo.

Most browsers display that fine. However, only on any version of iOS 9, the list is shrunk down since Safari does not calculate the proper height for the container. I believe there are several variants of this bug existed and most of them have been fixed from iOS 10 and above. But I do need the support for iOS 9 and so far none of the workarounds that I have found is working properly. Setting flex-shrink: 0; or using flex: 1 0 auto; did not yield success result. The only thing that would somehow mitigate this is to switch the list to use display: block rather than flex. However, that could have effect on other browsers as well and I only want the fix to apply specifically for any iOS version 9.

So any ideas on how to fix this without radically changing the syntax and affecting other browsers?

答:
A flex item by default is allowed to shrink, flex-shrink: 1, and it appears this is also what iOS9 allow them to.

By giving the li flex-shrink: 0 should prevent that.

Updated codepen

Stack snippet

.test {
  width: 400px;
  height: 500px;
  overflow: auto;
}
.list-group-item {
  flex-shrink: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>

<div class="test d-flex flex-column">
  <ul class="list-group h-100">
    <li class="list-group-item">Cras justo odio</li>
    <li class="list-group-item">Dapibus ac facilisis in</li>
    <li class="list-group-item">Morbi leo risus</li>
    <li class="list-group-item">Porta ac consectetur ac</li>
    <li class="list-group-item">Vestibulum at eros</li>
    <li class="list-group-item">Cras justo odio</li>
    <li class="list-group-item">Dapibus ac facilisis in</li>
    <li class="list-group-item">Morbi leo risus</li>
    <li class="list-group-item">Porta ac consectetur ac</li>
    <li class="list-group-item">Vestibulum at eros</li>
    <li class="list-group-item">Cras justo odio</li>
    <li class="list-group-item">Dapibus ac facilisis in</li>
    <li class="list-group-item">Morbi leo risus</li>
    <li class="list-group-item">Porta ac consectetur ac</li>
    <li class="list-group-item">Vestibulum at eros</li>
    <li class="list-group-item">Cras justo odio</li>
    <li class="list-group-item">Dapibus ac facilisis in</li>
    <li class="list-group-item">Morbi leo risus</li>
    <li class="list-group-item">Porta ac consectetur ac</li>
    <li class="list-group-item">Vestibulum at eros</li>
  </ul>
<div></code>```

Body:
A flex item by default is allowed to shrink, flex-shrink: 1, and it appears this is also what iOS9 allow them to.

By giving the li flex-shrink: 0 should prevent that.

Updated codepen

Stack snippet

.test {
  width: 400px;
  height: 500px;
  overflow: auto;
}
.list-group-item {
  flex-shrink: 0;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>

<div class="test d-flex flex-column">
  <ul class="list-group h-100">
    <li class="list-group-item">Cras justo odio</li>
    <li class="list-group-item">Dapibus ac facilisis in</li>
    <li class="list-group-item">Morbi leo risus</li>
    <li class="list-group-item">Porta ac consectetur ac</li>
    <li class="list-group-item">Vestibulum at eros</li>
    <li class="list-group-item">Cras justo odio</li>
    <li class="list-group-item">Dapibus ac facilisis in</li>
    <li class="list-group-item">Morbi leo risus</li>
    <li class="list-group-item">Porta ac consectetur ac</li>
    <li class="list-group-item">Vestibulum at eros</li>
    <li class="list-group-item">Cras justo odio</li>
    <li class="list-group-item">Dapibus ac facilisis in</li>
    <li class="list-group-item">Morbi leo risus</li>
    <li class="list-group-item">Porta ac consectetur ac</li>
    <li class="list-group-item">Vestibulum at eros</li>
    <li class="list-group-item">Cras justo odio</li>
    <li class="list-group-item">Dapibus ac facilisis in</li>
    <li class="list-group-item">Morbi leo risus</li>
    <li class="list-group-item">Porta ac consectetur ac</li>
    <li class="list-group-item">Vestibulum at eros</li>
  </ul>
<div>


问:
Find the content and increment value from Ruby
I have json file which contains following peace of lines.
I need to find and increment the last number "1.39.25.1" like 1.39.25.2, 1.39.25.3 so on by a ruby code.

```<code>    "appVersion": {
    "buildFlavour": "varation",
    "customisation": "MY.VER.NUM",
    "version": "1.39.25.1"
},
</code>```

Please help on this

Body:
I have json file which contains following peace of lines.
I need to find and increment the last number "1.39.25.1" like 1.39.25.2, 1.39.25.3 so on by a ruby code.

    "appVersion": {
    "buildFlavour": "varation",
    "customisation": "MY.VER.NUM",
    "version": "1.39.25.1"
},

Please help on this

Body:
String#succ is a quick and easy way:

"1.39.25.1".succ  #=> "1.39.25.2"


问:
How to turn off .NET 4.5 features on CSharpCodeProvider?
I'm using CSharpCodeProvider to compile assembly. I want to get errors when user using features and classes from .NET Framework versions above 4.0.

For example, if run this code on machine with installed 4.5 version .NET framework, CSharpCodeProvider compiles successfully with .NET 4.5 APIs(e.g. System.Reflection.ReflectionContext)

```<code>var options = new Dictionary<string, string> { { "CompilerVersion", "v4.0" } };
var cs = new CSharpCodeProvider(options);
var compilerParams = new CompilerParameters();
var r = cs.CompileAssemblyFromSource(
    compilerParams,
    "namespace Sample {public class SampleClass{private System.Reflection.ReflectionContext a;}}");
</code>```

Anyone any idea how I can specify to use the only 4.0 version for compile?

答:
The way to specifically target the .NET 4.0 Framework shape is to do what MSBuild does when resolving assembly references in .NET 4.0 projects by default, target the reference assemblies deployed by the Windows SDK (which is installed by VS). The reference assemblies installed to C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.0 represent the public surface area of the Framework binaries for .NET 4.0 - referencing these binaries will let your app target the subset of .NET 4.5 available on systems with only .NET 4.0 installed.

https://connect.microsoft.com/VisualStudio/feedback/details/783278/compilerversion-is-not-being-taken-into-account-v4-0-in-a-machine-with-net-4-5-installed

Body:
I'm using CSharpCodeProvider to compile assembly. I want to get errors when user using features and classes from .NET Framework versions above 4.0.

For example, if run this code on machine with installed 4.5 version .NET framework, CSharpCodeProvider compiles successfully with .NET 4.5 APIs(e.g. System.Reflection.ReflectionContext)

var options = new Dictionary<string, string> { { "CompilerVersion", "v4.0" } };
var cs = new CSharpCodeProvider(options);
var compilerParams = new CompilerParameters();
var r = cs.CompileAssemblyFromSource(
    compilerParams,
    "namespace Sample {public class SampleClass{private System.Reflection.ReflectionContext a;}}");

Anyone any idea how I can specify to use the only 4.0 version for compile?


问:
Function not executing on Angular2
When a button click triggers createPlaylist() the function fails to execute asd(). I tried doing it all on the same function but I get the same. console.log(resp) never logs. Why is that?</p>

```<code>    createPlaylist(token:string = localStorage.getItem('myToken')) {

      const url = `https://api.spotify.com/v1/users/${this.currentUser}/playlists`;
      const headers = new Headers();
      headers.append('Authorization', 'Bearer ' + token);
      headers.append('Content-Type', 'application/json');
      const body = {
        'name': 'searchDDD playlist'
      };
      this.http.post(url, body, { headers } )
      .subscribe(res => {
        console.log(res.json().name);
        console.log(res.status);
        this.playlistID = res.json().id;
        this.asd();
      });

    }

    asd(token:string = localStorage.getItem('myToken')){
      const url = `https://api.spotify.com/v1/users/${this.currentUser}/playlists/${this.playlistID}/tracks?`;
      const body = {'uris': ['spotify:track:4iV5W9uYEdYUVa79Axb7Rh',
      'spotify:track:1301WleyT98MSxVHPZCA6M']};
      const headers = new Headers();
      headers.append('Authorization', 'Bearer ' + token);
      headers.append('Content-type', 'application/json');
      this.http.post(url, body, { headers } ).map(resp => {
        console.log(resp);
    });
}
</code>```

答:
Without subscribe() (or forEach() or some others that actually execute the observable) observables won't do anything, because they are lazy

```<code>this.http.post(url, body, { headers } ).subscribe(resp => {
    console.log(resp);
});
</code>```

Title: Function not executing on Angular2

Body:
When a button click triggers createPlaylist() the function fails to execute asd(). I tried doing it all on the same function but I get the same. console.log(resp) never logs. Why is that?

    createPlaylist(token:string = localStorage.getItem('myToken')) {

      const url = `https://api.spotify.com/v1/users/${this.currentUser}/playlists`;
      const headers = new Headers();
      headers.append('Authorization', 'Bearer ' + token);
      headers.append('Content-Type', 'application/json');
      const body = {
        'name': 'searchDDD playlist'
      };
      this.http.post(url, body, { headers } )
      .subscribe(res => {
        console.log(res.json().name);
        console.log(res.status);
        this.playlistID = res.json().id;
        this.asd();
      });

    }

    asd(token:string = localStorage.getItem('myToken')){
      const url = `https://api.spotify.com/v1/users/${this.currentUser}/playlists/${this.playlistID}/tracks?`;
      const body = {'uris': ['spotify:track:4iV5W9uYEdYUVa79Axb7Rh',
      'spotify:track:1301WleyT98MSxVHPZCA6M']};
      const headers = new Headers();
      headers.append('Authorization', 'Bearer ' + token);
      headers.append('Content-type', 'application/json');
      this.http.post(url, body, { headers } ).map(resp => {
        console.log(resp);
    });
}

Body:
Without subscribe() (or forEach() or some others that actually execute the observable) observables won't do anything, because they are lazy

this.http.post(url, body, { headers } ).subscribe(resp => {
    console.log(resp);
});


问:
ExecuteScalar throws NullReferenceException when calling a stored proc that returns 1
I've done some research before posting this question and I'm aware of the fact that when there's no data returned, ExecuteScalar will throw  a System.NullReferenceException. That is why I modified my stored proc to "return 1" so there's guaranteed a return value. However, I'm still getting the NULL reference exception.

So I tried to use the SqlCommand to query a table that has data:

```<code>        SqlCommand sqlCommand = new SqlCommand("SELECT * FROM ATableThatHasValues", conn)
</code>```

When I ran execute scalar I was able to pick up a value so I know I have permission to query the database. I'm suspecting that this is some specific storeed proc permission setting that I missed?

I'd really appreciate any comment/suggestions as I've been stuck on this for a day now. :(

My code looks like this:

```<code>        using (SqlConnection sqlConnection = new SqlConnection(connectionString))
        {
            sqlConnection.Open();
            using (SqlCommand sqlCommand = new SqlCommand("GetSomeValue", sqlConnection))
            {
                sqlCommand.CommandType = CommandType.StoredProcedure;
                //sqlCommand.Parameters.Add(new SqlParameter("@Id", this.ID));
                //sqlCommand.Parameters.Add(new SqlParameter("@State", 1 /* active */));

                byte retValue = (byte)sqlCommand.ExecuteScalar();
                return retValue;
            }
        }
</code>```

THANKS!

答: I'm just going to elaborate on what @gbn said. When you execute SQL code you can return information in three different ways, OUTPUT parameters, tabular data and/or a single RETURN value. Like @gbn said, RETURN values are essentially specialized OUTPUT parameters. ExecuteScalar only sees information from tabular data, namely the first column of the first row. If no tabular data is received when you call ExecuteScalar a null value is returned instead. If you try to do something with this null value then obviously you'll get a NRE.

Body:
I've done some research before posting this question and I'm aware of the fact that when there's no data returned, ExecuteScalar will throw  a System.NullReferenceException. That is why I modified my stored proc to "return 1" so there's guaranteed a return value. However, I'm still getting the NULL reference exception.

So I tried to use the SqlCommand to query a table that has data:

        SqlCommand sqlCommand = new SqlCommand("SELECT * FROM ATableThatHasValues", conn)

When I ran execute scalar I was able to pick up a value so I know I have permission to query the database. I'm suspecting that this is some specific storeed proc permission setting that I missed?

I'd really appreciate any comment/suggestions as I've been stuck on this for a day now. :(

My code looks like this:

        using (SqlConnection sqlConnection = new SqlConnection(connectionString))
        {
            sqlConnection.Open();
            using (SqlCommand sqlCommand = new SqlCommand("GetSomeValue", sqlConnection))
            {
                sqlCommand.CommandType = CommandType.StoredProcedure;
                //sqlCommand.Parameters.Add(new SqlParameter("@Id", this.ID));
                //sqlCommand.Parameters.Add(new SqlParameter("@State", 1 /* active */));

                byte retValue = (byte)sqlCommand.ExecuteScalar();
                return retValue;
            }
        }

THANKS!