问:
Images not showing up for django-simple-captcha
I am using django-simple-captcha to make a captcha for different contact buttons on a webpage. I think I have it all working except for the fact that the images for the captcha won't show up.

urls.py:

```<code>from django.conf.urls import url
from django.conf.urls import include
from . import views

urlpatterns = [
    url(r'^$', views.product_landing, name='product_landing'),
    url(r'(?P<product_slug>.*)/?$', views.product_detail,
    name='product_detail'),url(r'^captcha/', include('captcha.urls'))
]
</code>```

html for page:

</form>
{% else %} {% if is_valid %}

Thank you!

Your resume has been received and we will be in touch with a decision soon. Please contact us if you have any questions.

{% else %}
<form action="" method="POST" id="apply-form" enctype="multipart/form-data" class="application-form">
  {% csrf_token %}

FIRST NAME

    {{ form.first_name }}

LAST NAME

    {{ form.last_name }}

EMAIL

    {{ form.email }}

PHONE

    {{ form.phone }}

ATTACH PDF RESUME

    <input class="readonly" type="text" READONLY>

      {{ form.resume }}

        BROWSE

MESSAGE

    {{ form.message }}

  {{ form.captcha }}
  <button class="submit-button" type="submit">
                                            APPLY
                                        </button>
</form>```

I've updated my forms and settings according to the documentation so I don't think that's the issue. From what I know so far I figure that it has to have something to do with the imaging libraries but I'm not quite sure. I have Pillow 4.1.1 installed and I'm on a Mac if that helps.

答: For anyone who stumbles across this, I figured it out. I had to list the captcha url above the product url because it was looking for the image in the wrong place. </p>

Body:
I am using django-simple-captcha to make a captcha for different contact buttons on a webpage. I think I have it all working except for the fact that the images for the captcha won't show up.

urls.py:

from django.conf.urls import url
from django.conf.urls import include
from . import views

urlpatterns = [
    url(r'^$', views.product_landing, name='product_landing'),
    url(r'(?P<product_slug>.*)/?$', views.product_detail,
    name='product_detail'),url(r'^captcha/', include('captcha.urls'))
]

html for page:

</form>
{% else %} {% if is_valid %}

Thank you!

Your resume has been received and we will be in touch with a decision soon. Please contact us if you have any questions.

{% else %}
<form action="" method="POST" id="apply-form" enctype="multipart/form-data" class="application-form">
  {% csrf_token %}

FIRST NAME

    {{ form.first_name }}

LAST NAME

    {{ form.last_name }}

EMAIL

    {{ form.email }}

PHONE

    {{ form.phone }}

ATTACH PDF RESUME

    <input class="readonly" type="text" READONLY>

      {{ form.resume }}

        BROWSE

MESSAGE

    {{ form.message }}

  {{ form.captcha }}
  <button class="submit-button" type="submit">
                                            APPLY
                                        </button>
</form>

I've updated my forms and settings according to the documentation so I don't think that's the issue. From what I know so far I figure that it has to have something to do with the imaging libraries but I'm not quite sure. I have Pillow 4.1.1 installed and I'm on a Mac if that helps.


来源: stackexchange

问:
Check if an array of strings contains a substring
I have an array like this:

```<code>array = ["123", "456", "#123"]
</code>```

I want to find the element which contains the substring "#". I tried array.includes("#") and array.indexOf("#") but it didn't work.

How can I check if any of the strings in this array contain the substring "#"?

答:
You can use filter ().

```<code>    var array = ["123", "456", "#123"];

    console.log(array.filter(function(item){
        var finder = '#';
        return eval('/'+finder+'/').test(item);
    }));
</code>```

By passing a function you can filter and return the elements that match what you are looking for.

In this example, I made use of eval (), just because to fetch the string use RegExp, but could fetch with the == operator.

ContentLicense: CC BY-SA 4.0

Body:
I have an array like this:

array = ["123", "456", "#123"]

I want to find the element which contains the substring "#". I tried array.includes("#") and array.indexOf("#") but it didn't work.

How can I check if any of the strings in this array contain the substring "#"?

Body:
You can use filter ().

    var array = ["123", "456", "#123"];

    console.log(array.filter(function(item){
        var finder = '#';
        return eval('/'+finder+'/').test(item);
    }));

By passing a function you can filter and return the elements that match what you are looking for.

In this example, I made use of eval (), just because to fetch the string use RegExp, but could fetch with the == operator.

ContentLicense: CC BY-SA 3.0


问:
wpf Rectangle acts weird when changing properties
Situation:

i have a custom WPF UserControl which should be like the toggle Buttons from most mobile OS.

It should change from one state to another when clicking on it once.

My Problem
Sometimes the just don't work the way I want. Either the rectangles disappear or the red/gray background rectangles won't be colored.

or they will be drawn twice or so.

My Code
I have a Grid:
In there is one Grid for the Background rectangels
and the 3 "SelectRectangles" are in there in different columns.

```<code><UserControl x:Class="test.StatusControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:local="clr-namespace:test"
         mc:Ignorable="d"
         d:DesignHeight="20" d:DesignWidth="80">

    <UserControl.Resources>
        <!-- my dummy values -->

    <SolidColorBrush x:Key="BackgroundBrush" Color="DarkGray" />
    <SolidColorBrush x:Key="TSBackgroundBrush" Color="Gray" />
    <SolidColorBrush x:Key="TSBarBrush" Color="LightGreen" />
    <SolidColorBrush x:Key="AccentColorBrush1" Color="Khaki" />

        <Style TargetType="Rectangle" x:Key="SliderRectangleStyle">
            <Setter Property="Stroke" Value="{DynamicResource BackgroundBrush}" />
            <Setter Property="Fill" Value="{DynamicResource TSBarBrush}" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding Status, RelativeSource={RelativeSource AncestorType=UserControl}}" Value="0">
                    <Setter Property="Grid.Column" Value="0" />
                </DataTrigger>
                <DataTrigger Binding="{Binding Status, RelativeSource={RelativeSource AncestorType=UserControl}}" Value="1">
                    <Setter Property="Grid.Column" Value="2" />
                </DataTrigger>
                <DataTrigger Binding="{Binding Status, RelativeSource={RelativeSource AncestorType=UserControl}}" Value="2">
                    <Setter Property="Grid.Column" Value="4" />
                </DataTrigger>
            </Style.Triggers>
        </Style>

        <Style TargetType="Rectangle" x:Key="LeftFillRectangleStyle">
            <Setter Property="Stroke" Value="{DynamicResource BackgroundBrush}" />
            <Setter Property="Fill" Value="{DynamicResource AccentColorBrush1}" />
            <Setter Property="Margin" Value="2,2,0,2" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding Status, RelativeSource={RelativeSource AncestorType=UserControl}}" Value="0">
                    <Setter Property="Visibility" Value="Collapsed" />
                </DataTrigger>
                <DataTrigger Binding="{Binding Status, RelativeSource={RelativeSource AncestorType=UserControl}}" Value="1">
                    <Setter Property="Grid.ColumnSpan" Value="2" />
                </DataTrigger>
                <DataTrigger Binding="{Binding Status, RelativeSource={RelativeSource AncestorType=UserControl}}" Value="2">
                    <Setter Property="Grid.ColumnSpan" Value="4" />
                </DataTrigger>
            </Style.Triggers>
        </Style>

        <Style x:Key="TextLabelStyle" TargetType="TextBlock">
            <Style.Triggers>
                <DataTrigger Binding="{Binding Status, RelativeSource={RelativeSource AncestorType=UserControl}}" Value="0">
                    <Setter Property="Text" Value="Aus" />
                </DataTrigger>
                <DataTrigger Binding="{Binding Status, RelativeSource={RelativeSource AncestorType=UserControl}}" Value="1">
                    <Setter Property="Text" Value="Client" />
                </DataTrigger>
                <DataTrigger Binding="{Binding Status, RelativeSource={RelativeSource AncestorType=UserControl}}" Value="2">
                    <Setter Property="Text" Value="Finance Dept." />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </UserControl.Resources>

    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="10"/>
            <ColumnDefinition Width="10"/>
            <ColumnDefinition Width="10"/>
            <ColumnDefinition Width="10"/>
            <ColumnDefinition Width="10"/>
            <ColumnDefinition Width="auto"/>
        </Grid.ColumnDefinitions>

        <Rectangle
        Margin="5,2,5,2"
        Grid.Row="0"
        Grid.Column="0"
        Grid.ColumnSpan="5"
        Fill="{DynamicResource BackgroundBrush}"
        Stroke="{DynamicResource TSBackgroundBrush}"
        />

        <TextBlock
        Grid.Row="0"
        Grid.Column="5"
        Style="{StaticResource TextLabelStyle}"
        Margin="4,0,4,0"
        />

        <Rectangle Style="{StaticResource LeftFillRectangleStyle}" />
        <Rectangle Style="{StaticResource SliderRectangleStyle}" />

        <!-- Overlay the slider area with three equal click areas -->
        <Grid Grid.Column="0" Grid.ColumnSpan="5">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>

            <Grid.Resources>
                <!--
            Because this style has no x:Key, it will apply to all Rectangles in this Grid
            -->
                <Style TargetType="Rectangle" >
                    <!--
                Uncomment these setters to make sure the clickable areas are where
                they should be.
                -->
                    <!--
                <Setter Property="Stroke" Value="Red" />
                <Setter Property="StrokeThickness" Value="1" />
               -->
                    <Setter Property="Fill" Value="Transparent" />
                    <EventSetter Event="PreviewMouseDown" Handler="StatusSelect_PreviewMouseDown" />
                </Style>
            </Grid.Resources>

            <Rectangle Grid.Column="0" />
            <Rectangle Grid.Column="1" />
            <Rectangle Grid.Column="2" />
        </Grid>
    </Grid>
</UserControl>
</code>```

I am setting the visibility to hidden/visible accordingly, since moving one Rectangle, happened to come up with the same problem.

```<code>  using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace test
{
    /// <summary>
    /// Interaktionslogik für StatusControl.xaml
    /// </summary>
    public partial class StatusControl : UserControl
    {
        public StatusControl()
        {
            InitializeComponent();
        }

        #region Status Property
        public int Status {
            get { return (int)GetValue(StatusProperty); }
            set { SetValue(StatusProperty, value); }
        }

        public static readonly DependencyProperty StatusProperty =
            DependencyProperty.Register(nameof(Status), typeof(int), typeof(StatusControl),new PropertyMetadata(0));
        #endregion Status Property

        private void StatusSelect_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            Status = Grid.GetColumn(sender as UIElement);
        }
    }
}
</code>```

Main Window xaml:

```<code><Window x:Class="test.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:test"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <StackPanel>
        <local:StatusControl Status="1"/>
        <local:StatusControl Status="2"/>
        <local:StatusControl Status="3"/>
        <Slider x:Name="TestSlider" Minimum="0" Maximum="2" Width="200"/>
        <local:StatusControl Status="{Binding Value, ElementName=TestSlider}"/>
    </StackPanel>
</Grid>
</code>```

My tried solutions
It seems that they just don't update. I tried calling this.UpdateLayout() but it did not help. Sometimes the also redraw themselves after a few seconds an then its okey. Sometimes not...

Thank you for reading/helping!

答:
First, let's give your status control a Status dependency property. I don't know what your control is called or what the status variable you have is all about, so I'll just call my control StatusControl. I think you might be better off with an enum for Status instead of an int (Good, Indifferent, Bad, or Error, Warning, Success or something like that). But I'll stick with your int for now.

```<code>public partial class StatusControl : UserControl
{
    public StatusControl()
    {
        InitializeComponent();
    }

    #region Status Property
    public int Status
    {
        get { return (int)GetValue(StatusProperty); }
        set { SetValue(StatusProperty, value); }
    }

    public static readonly DependencyProperty StatusProperty =
        DependencyProperty.Register(nameof(Status), typeof(int), typeof(StatusControl),
            new PropertyMetadata(0));
    #endregion Status Property

    private void StatusSelect_PreviewMouseDown(object sender, MouseButtonEventArgs e)
    {
        Status = Grid.GetColumn(sender as UIElement);
    }
}
</code>```

And that Status property drives the changes in the user control via the Triggers in the two rectangle styles.

SliderRectangleStyle dynamically repositions a single rectangle representing the slider.

LeftFillRectangleStyle dynamically shows/hides and resizes a rectangle that fills in the accent-color area of the slider.

You may have to fine-tune the margins a bit to get the exact proportions you had originally; I was pretty casual when I ripped apart your original XAML.

```<code><UserControl.Resources>
    <!-- my dummy values -->
    <!--
    <SolidColorBrush x:Key="BackgroundBrush" Color="DarkGray" />
    <SolidColorBrush x:Key="TSBackgroundBrush" Color="Gray" />
    <SolidColorBrush x:Key="TSBarBrush" Color="LightGreen" />
    <SolidColorBrush x:Key="AccentColorBrush1" Color="Khaki" />
    -->

    <Style TargetType="Rectangle" x:Key="SliderRectangleStyle">
        <Setter Property="Stroke" Value="{DynamicResource BackgroundBrush}" />
        <Setter Property="Fill" Value="{DynamicResource TSBarBrush}" />
        <Style.Triggers>
            <DataTrigger Binding="{Binding Status, RelativeSource={RelativeSource AncestorType=UserControl}}" Value="0">
                <Setter Property="Grid.Column" Value="0" />
            </DataTrigger>
            <DataTrigger Binding="{Binding Status, RelativeSource={RelativeSource AncestorType=UserControl}}" Value="1">
                <Setter Property="Grid.Column" Value="2" />
            </DataTrigger>
            <DataTrigger Binding="{Binding Status, RelativeSource={RelativeSource AncestorType=UserControl}}" Value="2">
                <Setter Property="Grid.Column" Value="4" />
            </DataTrigger>
        </Style.Triggers>
    </Style>

    <Style TargetType="Rectangle" x:Key="LeftFillRectangleStyle">
        <Setter Property="Stroke" Value="{DynamicResource BackgroundBrush}" />
        <Setter Property="Fill" Value="{DynamicResource AccentColorBrush1}" />
        <Setter Property="Margin" Value="2,2,0,2" />
        <Style.Triggers>
            <DataTrigger Binding="{Binding Status, RelativeSource={RelativeSource AncestorType=UserControl}}" Value="0">
                <Setter Property="Visibility" Value="Collapsed" />
            </DataTrigger>
            <DataTrigger Binding="{Binding Status, RelativeSource={RelativeSource AncestorType=UserControl}}" Value="1">
                <Setter Property="Grid.ColumnSpan" Value="2" />
            </DataTrigger>
            <DataTrigger Binding="{Binding Status, RelativeSource={RelativeSource AncestorType=UserControl}}" Value="2">
                <Setter Property="Grid.ColumnSpan" Value="4" />
            </DataTrigger>
        </Style.Triggers>
    </Style>

    <Style x:Key="TextLabelStyle" TargetType="TextBlock">
        <Style.Triggers>
            <DataTrigger Binding="{Binding Status, RelativeSource={RelativeSource AncestorType=UserControl}}" Value="0">
                <Setter Property="Text" Value="Aus" />
            </DataTrigger>
            <DataTrigger Binding="{Binding Status, RelativeSource={RelativeSource AncestorType=UserControl}}" Value="1">
                <Setter Property="Text" Value="Client" />
            </DataTrigger>
            <DataTrigger Binding="{Binding Status, RelativeSource={RelativeSource AncestorType=UserControl}}" Value="2">
                <Setter Property="Text" Value="Finance Dept." />
            </DataTrigger>
        </Style.Triggers>
    </Style>
</UserControl.Resources>

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="10"/>
        <ColumnDefinition Width="10"/>
        <ColumnDefinition Width="10"/>
        <ColumnDefinition Width="10"/>
        <ColumnDefinition Width="10"/>
        <ColumnDefinition Width="auto"/>
    </Grid.ColumnDefinitions>

    <Rectangle
        Margin="5,2,5,2"
        Grid.Row="0"
        Grid.Column="0"
        Grid.ColumnSpan="5"
        Fill="{DynamicResource BackgroundBrush}"
        Stroke="{DynamicResource TSBackgroundBrush}"
        />

    <TextBlock
        Grid.Row="0"
        Grid.Column="5"
        Style="{StaticResource TextLabelStyle}"
        Margin="4,0,4,0"
        />

    <Rectangle Style="{StaticResource LeftFillRectangleStyle}" />
    <Rectangle Style="{StaticResource SliderRectangleStyle}" />

    <!-- Overlay the slider area with three equal click areas -->
    <Grid Grid.Column="0" Grid.ColumnSpan="5">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>

        <Grid.Resources>
            <!--
            Because this style has no x:Key, it will apply to all Rectangles in this Grid
            -->
            <Style TargetType="Rectangle" >
                <!--
                Uncomment these setters to make sure the clickable areas are where
                they should be.
                -->
                <!--
                <Setter Property="Stroke" Value="Red" />
                <Setter Property="StrokeThickness" Value="1" />
                -->
                <Setter Property="Fill" Value="Transparent" />
                <EventSetter Event="PreviewMouseDown" Handler="StatusSelect_PreviewMouseDown" />
            </Style>
        </Grid.Resources>

        <Rectangle Grid.Column="0" />
        <Rectangle Grid.Column="1" />
        <Rectangle Grid.Column="2" />
    </Grid>
</Grid>
</code>```

Body:
Situation:

i have a custom WPF UserControl which should be like the toggle Buttons from most mobile OS.

It should change from one state to another when clicking on it once.

My Problem
Sometimes the just don't work the way I want. Either the rectangles disappear or the red/gray background rectangles won't be colored.

or they will be drawn twice or so.

My Code
I have a Grid:
In there is one Grid for the Background rectangels
and the 3 "SelectRectangles" are in there in different columns.

<UserControl x:Class="test.StatusControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:local="clr-namespace:test"
         mc:Ignorable="d"
         d:DesignHeight="20" d:DesignWidth="80">

    <UserControl.Resources>

    <SolidColorBrush x:Key="BackgroundBrush" Color="DarkGray" />
    <SolidColorBrush x:Key="TSBackgroundBrush" Color="Gray" />
    <SolidColorBrush x:Key="TSBarBrush" Color="LightGreen" />
    <SolidColorBrush x:Key="AccentColorBrush1" Color="Khaki" />

        </Style>

        </Style>

        </Style>
    </UserControl.Resources>

    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="10"/>
            <ColumnDefinition Width="10"/>
            <ColumnDefinition Width="10"/>
            <ColumnDefinition Width="10"/>
            <ColumnDefinition Width="10"/>
            <ColumnDefinition Width="auto"/>
        </Grid.ColumnDefinitions>

        <Rectangle
        Margin="5,2,5,2"
        Grid.Row="0"
        Grid.Column="0"
        Grid.ColumnSpan="5"
        Fill="{DynamicResource BackgroundBrush}"
        Stroke="{DynamicResource TSBackgroundBrush}"
        />

        <TextBlock
        Grid.Row="0"
        Grid.Column="5"
        Style="{StaticResource TextLabelStyle}"
        Margin="4,0,4,0"
        />

        <Rectangle Style="{StaticResource LeftFillRectangleStyle}" />
        <Rectangle Style="{StaticResource SliderRectangleStyle}" />

        <Grid Grid.Column="0" Grid.ColumnSpan="5">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>

            <Grid.Resources>

            </Grid.Resources>

            <Rectangle Grid.Column="0" />
            <Rectangle Grid.Column="1" />
            <Rectangle Grid.Column="2" />
        </Grid>
    </Grid>
</UserControl>

I am setting the visibility to hidden/visible accordingly, since moving one Rectangle, happened to come up with the same problem.

  using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace test
{
    ///
    /// Interaktionslogik für StatusControl.xaml
    ///
    public partial class StatusControl : UserControl
    {
        public StatusControl()
        {
            InitializeComponent();
        }

        #region Status Property
        public int Status {
            get { return (int)GetValue(StatusProperty); }
            set { SetValue(StatusProperty, value); }
        }

        public static readonly DependencyProperty StatusProperty =
            DependencyProperty.Register(nameof(Status), typeof(int), typeof(StatusControl),new PropertyMetadata(0));
        #endregion Status Property

        private void StatusSelect_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            Status = Grid.GetColumn(sender as UIElement);
        }
    }
}

Main Window xaml:

<Window x:Class="test.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:test"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <StackPanel>
        <local:StatusControl Status="1"/>
        <local:StatusControl Status="2"/>
        <local:StatusControl Status="3"/>
        <Slider x:Name="TestSlider" Minimum="0" Maximum="2" Width="200"/>
        <local:StatusControl Status="{Binding Value, ElementName=TestSlider}"/>
    </StackPanel>
</Grid>

My tried solutions
It seems that they just don't update. I tried calling this.UpdateLayout() but it did not help. Sometimes the also redraw themselves after a few seconds an then its okey. Sometimes not...

Thank you for reading/helping!

Body:
First, let's give your status control a Status dependency property. I don't know what your control is called or what the status variable you have is all about, so I'll just call my control StatusControl. I think you might be better off with an enum for Status instead of an int (Good, Indifferent, Bad, or Error, Warning, Success or something like that). But I'll stick with your int for now.

public partial class StatusControl : UserControl
{
    public StatusControl()
    {
        InitializeComponent();
    }

    #region Status Property
    public int Status
    {
        get { return (int)GetValue(StatusProperty); }
        set { SetValue(StatusProperty, value); }
    }

    public static readonly DependencyProperty StatusProperty =
        DependencyProperty.Register(nameof(Status), typeof(int), typeof(StatusControl),
            new PropertyMetadata(0));
    #endregion Status Property

    private void StatusSelect_PreviewMouseDown(object sender, MouseButtonEventArgs e)
    {
        Status = Grid.GetColumn(sender as UIElement);
    }
}

And that Status property drives the changes in the user control via the Triggers in the two rectangle styles.

SliderRectangleStyle dynamically repositions a single rectangle representing the slider.

LeftFillRectangleStyle dynamically shows/hides and resizes a rectangle that fills in the accent-color area of the slider.

You may have to fine-tune the margins a bit to get the exact proportions you had originally; I was pretty casual when I ripped apart your original XAML.

<UserControl.Resources>
    <!-- my dummy values -->
    <!--
    <SolidColorBrush x:Key="BackgroundBrush" Color="DarkGray" />
    <SolidColorBrush x:Key="TSBackgroundBrush" Color="Gray" />
    <SolidColorBrush x:Key="TSBarBrush" Color="LightGreen" />
    <SolidColorBrush x:Key="AccentColorBrush1" Color="Khaki" />
    -->

    <Style TargetType="Rectangle" x:Key="SliderRectangleStyle">
        <Setter Property="Stroke" Value="{DynamicResource BackgroundBrush}" />
        <Setter Property="Fill" Value="{DynamicResource TSBarBrush}" />
        <Style.Triggers>
            <DataTrigger Binding="{Binding Status, RelativeSource={RelativeSource AncestorType=UserControl}}" Value="0">
                <Setter Property="Grid.Column" Value="0" />
            </DataTrigger>
            <DataTrigger Binding="{Binding Status, RelativeSource={RelativeSource AncestorType=UserControl}}" Value="1">
                <Setter Property="Grid.Column" Value="2" />
            </DataTrigger>
            <DataTrigger Binding="{Binding Status, RelativeSource={RelativeSource AncestorType=UserControl}}" Value="2">
                <Setter Property="Grid.Column" Value="4" />
            </DataTrigger>
        </Style.Triggers>
    </Style>

    <Style TargetType="Rectangle" x:Key="LeftFillRectangleStyle">
        <Setter Property="Stroke" Value="{DynamicResource BackgroundBrush}" />
        <Setter Property="Fill" Value="{DynamicResource AccentColorBrush1}" />
        <Setter Property="Margin" Value="2,2,0,2" />
        <Style.Triggers>
            <DataTrigger Binding="{Binding Status, RelativeSource={RelativeSource AncestorType=UserControl}}" Value="0">
                <Setter Property="Visibility" Value="Collapsed" />
            </DataTrigger>
            <DataTrigger Binding="{Binding Status, RelativeSource={RelativeSource AncestorType=UserControl}}" Value="1">
                <Setter Property="Grid.ColumnSpan" Value="2" />
            </DataTrigger>
            <DataTrigger Binding="{Binding Status, RelativeSource={RelativeSource AncestorType=UserControl}}" Value="2">
                <Setter Property="Grid.ColumnSpan" Value="4" />
            </DataTrigger>
        </Style.Triggers>
    </Style>

    <Style x:Key="TextLabelStyle" TargetType="TextBlock">
        <Style.Triggers>
            <DataTrigger Binding="{Binding Status, RelativeSource={RelativeSource AncestorType=UserControl}}" Value="0">
                <Setter Property="Text" Value="Aus" />
            </DataTrigger>
            <DataTrigger Binding="{Binding Status, RelativeSource={RelativeSource AncestorType=UserControl}}" Value="1">
                <Setter Property="Text" Value="Client" />
            </DataTrigger>
            <DataTrigger Binding="{Binding Status, RelativeSource={RelativeSource AncestorType=UserControl}}" Value="2">
                <Setter Property="Text" Value="Finance Dept." />
            </DataTrigger>
        </Style.Triggers>
    </Style>
</UserControl.Resources>

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="10"/>
        <ColumnDefinition Width="10"/>
        <ColumnDefinition Width="10"/>
        <ColumnDefinition Width="10"/>
        <ColumnDefinition Width="10"/>
        <ColumnDefinition Width="auto"/>
    </Grid.ColumnDefinitions>

    <Rectangle
        Margin="5,2,5,2"
        Grid.Row="0"
        Grid.Column="0"
        Grid.ColumnSpan="5"
        Fill="{DynamicResource BackgroundBrush}"
        Stroke="{DynamicResource TSBackgroundBrush}"
        />

    <TextBlock
        Grid.Row="0"
        Grid.Column="5"
        Style="{StaticResource TextLabelStyle}"
        Margin="4,0,4,0"
        />

    <Rectangle Style="{StaticResource LeftFillRectangleStyle}" />
    <Rectangle Style="{StaticResource SliderRectangleStyle}" />

    <!-- Overlay the slider area with three equal click areas -->
    <Grid Grid.Column="0" Grid.ColumnSpan="5">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>

        <Grid.Resources>
            <!--
            Because this style has no x:Key, it will apply to all Rectangles in this Grid
            -->
            <Style TargetType="Rectangle" >
                <!--
                Uncomment these setters to make sure the clickable areas are where
                they should be.
                -->
                <!--
                <Setter Property="Stroke" Value="Red" />
                <Setter Property="StrokeThickness" Value="1" />
                -->
                <Setter Property="Fill" Value="Transparent" />
                <EventSetter Event="PreviewMouseDown" Handler="StatusSelect_PreviewMouseDown" />
            </Style>
        </Grid.Resources>

        <Rectangle Grid.Column="0" />
        <Rectangle Grid.Column="1" />
        <Rectangle Grid.Column="2" />
    </Grid>
</Grid>


问:
SWFAddress: adding "/" char at the end of an URL via JavaScript
how can I add the / char at the end of the URL without force the user to write it?
I'm starting to work with SWFAddress using JavaScript and jQuery directly (without Flash) like this wonderful site.

So something like this:

```<code>http://mysite.com/section

// and after click to a specific <a ="#">button</a> get
http://mysite.com/section/#/sub-content

// instead of
http://mysite.com/section#/sub-content
</code>```

I've started with this code to do it:

```<code>$(".time_dot, .time_year").click (function () {
    onClickEvent (this);
});

function onClickEvent (dom) {
    var timer = setTimeout (function () {
        SWFAddress.setValue($(dom).parent().attr("id"));
    }, 200);
    // do something else
}
</code>```

The setTimeout method is used to avoid the  button overwrite the SWFAddress.setValue method, but I don't know a way to change the URL address to url.com/content#/... to url.com/content/#/....

How can I do that?

答:
```<code>function fixUrl(url) {
    return url.replace(/\/?$/,'/');
}

//or

function fixUrl(url) {
    return url.match(/\/$/)
       ? url
       : url + '/';
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
how can I add the / char at the end of the URL without force the user to write it?
I'm starting to work with SWFAddress using JavaScript and jQuery directly (without Flash) like this wonderful site.

So something like this:

http://mysite.com/section

// and after click to a specific button get
http://mysite.com/section/#/sub-content

// instead of
http://mysite.com/section#/sub-content

I've started with this code to do it:

$(".time_dot, .time_year").click (function () {
    onClickEvent (this);
});

function onClickEvent (dom) {
    var timer = setTimeout (function () {
        SWFAddress.setValue($(dom).parent().attr("id"));
    }, 200);
    // do something else
}

The setTimeout method is used to avoid the  button overwrite the SWFAddress.setValue method, but I don't know a way to change the URL address to url.com/content#/... to url.com/content/#/....

How can I do that?


问:
How after building the dist folder in Webpack, move the bundle.js and css file into the statics folder?
When I run my npm run build or npm run build-dev

It creates the index.html and manage2.bundle.js and manage2.css files in the root. I need to move those files into the static directory.

So the generated index.html below will actually work, with the correct paths:

```<code><!doctype html>
<html lang="en">
<head>
    <title>Manage2</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="description" content="The TickerTags backend manage app">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="style.css">
    <link href="https://fonts.googleapis.com/css?family=Roboto+Condensed:300|Source+Sans+Pro:200,600" rel="stylesheet">
    <link rel="icon" type="image/x-icon" href="static/favicon.ico">
<link href="/static/manage2.css" rel="stylesheet"></head>
<body>
    <div id="manage2"></div>
<script type="text/javascript" src="/static/manage2.bundle.js"></script></body>
</html>
</code>```

How is this acomplished? webpack.config below

```<code>const fs = require('fs');
const webpack = require('webpack')
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const path = require("path");
const dist = path.resolve(__dirname, "dist");
const src = path.resolve(__dirname, "src");
const environment = process.env.NODE_ENV;

const stream = fs.createWriteStream("src/services/environment.js");
stream.once('open', function(fd) {
  stream.write('const env = "'+environment+'"\n');
  stream.write('export default env');
  stream.end();
});

module.exports = {
  context: src,
  entry: [
    "./index.js"
  ],
  output: {
    path: dist,
    filename: "manage2.bundle.js",
    publicPath: '/static/',
  },
  devtool: 'source-map',
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: ["babel-loader"]
      },
      {
        test: /\.scss$/,
        use: ExtractTextPlugin.extract({
          fallbackLoader: "style-loader",
          loader: ["css-loader", "sass-loader"],
          publicPath: dist
        })
      }
    ]
  },
  devServer: {
    hot: false,
    quiet: true,
    publicPath: "",
    contentBase: path.join(__dirname, "dist"),
    compress: true,
    stats: "errors-only",
    open: true
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: "index.html"
    }),
    new ExtractTextPlugin({
      filename: "manage2.css",
      disable: false,
      allChunks: true
    }),
    new CopyWebpackPlugin([{ from: "static", to: "static" }])
  ]
};
// new webpack.DefinePlugin({ env: JSON.stringify(environment) })
</code>```

My npm scripts

```<code>"scripts": {
    "dev": "NODE_ENV=development webpack-dev-server --history-api-fallback",
    "prod": "NODE_ENV=production webpack-dev-server -p",
    "build": "NODE_ENV=production webpack -p",
    "build-dev": "NODE_ENV=production webpack -d",
</code>```

答:
Your output.path is incorrect. It should be path.resolve(__dirname, 'dist', 'static').

And since now your output.path points to dist/static, set publicPath back to /.

Body:
When I run my npm run build or npm run build-dev

It creates the index.html and manage2.bundle.js and manage2.css files in the root. I need to move those files into the static directory.

So the generated index.html below will actually work, with the correct paths:

<!doctype html>

    <title>Manage2</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="description" content="The TickerTags backend manage app">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="style.css">
    <link href="https://fonts.googleapis.com/css?family=Roboto+Condensed:300|Source+Sans+Pro:200,600" rel="stylesheet">
    <link rel="icon" type="image/x-icon" href="static/favicon.ico">
<link href="/static/manage2.css" rel="stylesheet">

How is this acomplished? webpack.config below

const fs = require('fs');
const webpack = require('webpack')
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const path = require("path");
const dist = path.resolve(__dirname, "dist");
const src = path.resolve(__dirname, "src");
const environment = process.env.NODE_ENV;

const stream = fs.createWriteStream("src/services/environment.js");
stream.once('open', function(fd) {
  stream.write('const env = "'+environment+'"\n');
  stream.write('export default env');
  stream.end();
});

module.exports = {
  context: src,
  entry: [
    "./index.js"
  ],
  output: {
    path: dist,
    filename: "manage2.bundle.js",
    publicPath: '/static/',
  },
  devtool: 'source-map',
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: ["babel-loader"]
      },
      {
        test: /\.scss$/,
        use: ExtractTextPlugin.extract({
          fallbackLoader: "style-loader",
          loader: ["css-loader", "sass-loader"],
          publicPath: dist
        })
      }
    ]
  },
  devServer: {
    hot: false,
    quiet: true,
    publicPath: "",
    contentBase: path.join(__dirname, "dist"),
    compress: true,
    stats: "errors-only",
    open: true
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: "index.html"
    }),
    new ExtractTextPlugin({
      filename: "manage2.css",
      disable: false,
      allChunks: true
    }),
    new CopyWebpackPlugin([{ from: "static", to: "static" }])
  ]
};
// new webpack.DefinePlugin({ env: JSON.stringify(environment) })

My npm scripts

"scripts": {
    "dev": "NODE_ENV=development webpack-dev-server --history-api-fallback",
    "prod": "NODE_ENV=production webpack-dev-server -p",
    "build": "NODE_ENV=production webpack -p",
    "build-dev": "NODE_ENV=production webpack -d",


问:
Parse multiple xml files in Python
I am stuck with a problem here. So I want to parse multiple xml files with the same structure within it. I was already able to get all the locations for each file and save them into three different lists, since there are three different types of xml structures. Now I want to create three  functions (for each list), which is looping through the lists and parse the information I need. Somehow I am not able to do it. Anybody here who could give me a hint how to do it?

```<code>import os
import glob
import xml.etree.ElementTree as ET
import fnmatch
import re
import sys

#### Get the location of each XML file and save them into a list ####

all_xml_list =[]

def locate(pattern,root=os.curdir):
    for path, dirs, files in os.walk(os.path.abspath(root)):
        for filename in fnmatch.filter(files,pattern):
            yield os.path.join(path,filename)

for files in locate('*.xml',r'C:\Users\Lars\Documents\XML-Files'):
    all_xml_list.append(files)

#### Create lists by GameDay Events ####

xml_GameDay_Player   = [x for x in all_xml_list if 'Player' in x]
xml_GameDay_Team     = [x for x in all_xml_list if 'Team' in x]
xml_GameDay_Match    = [x for x in all_xml_list if 'Match' in x]
</code>```

The XML file looks like this:

<sports-content xmlns:imp="url">
  <sports-metadata date-time="20160912T000000+0200" doc-id="sports_event_" publisher="somepublisher" language="en_EN" document-class="player-statistics">
    <sports-title>player-statistics-165483</sports-title>
  </sports-metadata>
  <sports-event>
    <event-metadata id="E_165483" event-key="165483" event-status="post-event" start-date-time="20160827T183000+0200" start-weekday="saturday" heat-number="1" site-attendance="52183" />
    <team>
      <team-metadata id="O_17" team-key="17">
        <name full="TeamName" nickname="NicknameoftheTeam" imp:dfl-3-letter-code="NOT" official-3-letter-code="" />
      </team-metadata>
      <player>
        <player-metadata player-key="33201" uniform-number="1">
          <name first="Max" last="Mustermann" full="Max Mustermann" nickname="Mäxchen" imp:extensive="Name" />
        </player-metadata>
        <player-stats stats-coverage="standard" date-coverage-type="event" minutes-played="90" score="0">
          <rating rating-type="standard" imp:rating-value-goalie="7.6" imp:rating-value-defenseman="5.6" imp:rating-value-mid-fielder="5.8" imp:rating-value-forward="5.0" />
          <rating rating-type="grade" rating-value="2.2" />
          <rating rating-type="index" imp:rating-value-goalie="7.6" imp:rating-value-defenseman="3.7" imp:rating-value-mid-fielder="2.5" imp:rating-value-forward="1.2" />
          <rating rating-type="bemeister" rating-value="16.04086" />
          <player-stats-soccer imp:duels-won="1" imp:duels-won-ground="0" imp:duels-won-header="1" imp:duels-lost-ground="0" imp:duels-lost-header="0" imp:duels-lost="0" imp:duels-won-percentage="100" imp:passes-completed="28" imp:passes-failed="4" imp:passes-completions-percentage="87.5" imp:passes-failed-percentage="12.5" imp:passes="32" imp:passes-short-total="22" imp:balls-touched="50" imp:tracking-distance="5579.80" imp:tracking-average-speed="3.41" imp:tracking-max-speed="23.49" imp:tracking-sprints="0" imp:tracking-sprints-distance="0.00" imp:tracking-fast-runs="3" imp:tracking-fast-runs-distance="37.08" imp:tracking-offensive-runs="0" imp:tracking-offensive-runs-distance="0.00" dfl-distance="5579.80" dfl-average-speed="3.41" dfl-max-speed="23.49">
            <stats-soccer-defensive saves="5" imp:catches-punches-crosses="3" imp:catches-punches-corners="0" goals-against-total="1" imp:penalty-saves="0" imp:clear-cut-chance="0" />
            <stats-soccer-offensive shots-total="0" shots-on-goal-total="0" imp:shots-off-post="0" offsides="0" corner-kicks="0" imp:crosses="0" assists-total="0" imp:shot-assists="0" imp:freekicks="3" imp:miss-chance="0" imp:throw-in="0" imp:punt="2" shots-penalty-shot-scored="0" shots-penalty-shot-missed="0" dfl-assists-total="0" imp:shots-total-outside-box="0" imp:shots-total-inside-box="0" imp:shots-foot-inside-box="0" imp:shots-foot-outside-box="0" imp:shots-total-header="0" />
            <stats-soccer-foul fouls-commited="0" fouls-suffered="0" imp:yellow-red-cards="0" imp:red-cards="0" imp:yellow-cards="0" penalty-caused="0" />
          </player-stats-soccer>
        </player-stats>
      </player>
    </team>
  </sports-event>
</sports-content>
```

I want to extract everything which is within the "player meta tag" and "player-stats coverage" and "player stats soccer" tag.

答:
This won't be a complete solution for your particular case, because this is a bit of task to do and also I don't have keyboard, working from tablet.

In general, you can do it several ways, depending on whether you really need all data or extract specific subset, and whether you know all the possible structures in advance.

For example, one way:

```<code>from lxml import etree
Playerdata=[]
for F in xml_Gameday_Player:
                tree=etree.XML(file_get_contents(F))
                for player in tree.xpath('.//player'):
                        row=[]
                        row['player']=player.xpath('./player-metadata/name/@Last/text()')
                        for plrdata in player.xpath('.//player-stats'):
                               #do stuff with player data
                         Playerdata+=row
</code>```

This is adapted from my existing script, however, it is more tailored to extracting only a specific subset of xml. If you need all data, it would probably be better to use some xml tree walker.

file_get_contents is a small helper function :

```<code>def file_get_contents(filename):
    with open(filename) as f:
        return f.read()
</code>```

Xpath is a powerful language for finding nodes within xml.
Note that depending on Xpath you use, the result may be either an xml node as in "for player in..." statement, or a string, as in "row['player']=" statement.

Title: Parse multiple xml files in Python

Body:
I am stuck with a problem here. So I want to parse multiple xml files with the same structure within it. I was already able to get all the locations for each file and save them into three different lists, since there are three different types of xml structures. Now I want to create three  functions (for each list), which is looping through the lists and parse the information I need. Somehow I am not able to do it. Anybody here who could give me a hint how to do it?

import os
import glob
import xml.etree.ElementTree as ET
import fnmatch
import re
import sys

#### Get the location of each XML file and save them into a list ####

all_xml_list =[]

def locate(pattern,root=os.curdir):
    for path, dirs, files in os.walk(os.path.abspath(root)):
        for filename in fnmatch.filter(files,pattern):
            yield os.path.join(path,filename)

for files in locate('*.xml',r'C:\Users\Lars\Documents\XML-Files'):
    all_xml_list.append(files)

#### Create lists by GameDay Events ####

xml_GameDay_Player   = [x for x in all_xml_list if 'Player' in x]
xml_GameDay_Team     = [x for x in all_xml_list if 'Team' in x]
xml_GameDay_Match    = [x for x in all_xml_list if 'Match' in x]

The XML file looks like this:

<sports-content xmlns:imp="url">
  <sports-metadata date-time="20160912T000000+0200" doc-id="sports_event_" publisher="somepublisher" language="en_EN" document-class="player-statistics">
    <sports-title>player-statistics-165483</sports-title>
  </sports-metadata>
  <sports-event>
    <event-metadata id="E_165483" event-key="165483" event-status="post-event" start-date-time="20160827T183000+0200" start-weekday="saturday" heat-number="1" site-attendance="52183" />
    <team>
      <team-metadata id="O_17" team-key="17">
        <name full="TeamName" nickname="NicknameoftheTeam" imp:dfl-3-letter-code="NOT" official-3-letter-code="" />
      </team-metadata>
      <player>
        <player-metadata player-key="33201" uniform-number="1">
          <name first="Max" last="Mustermann" full="Max Mustermann" nickname="Mäxchen" imp:extensive="Name" />
        </player-metadata>
        <player-stats stats-coverage="standard" date-coverage-type="event" minutes-played="90" score="0">
          <rating rating-type="standard" imp:rating-value-goalie="7.6" imp:rating-value-defenseman="5.6" imp:rating-value-mid-fielder="5.8" imp:rating-value-forward="5.0" />
          <rating rating-type="grade" rating-value="2.2" />
          <rating rating-type="index" imp:rating-value-goalie="7.6" imp:rating-value-defenseman="3.7" imp:rating-value-mid-fielder="2.5" imp:rating-value-forward="1.2" />
          <rating rating-type="bemeister" rating-value="16.04086" />
          <player-stats-soccer imp:duels-won="1" imp:duels-won-ground="0" imp:duels-won-header="1" imp:duels-lost-ground="0" imp:duels-lost-header="0" imp:duels-lost="0" imp:duels-won-percentage="100" imp:passes-completed="28" imp:passes-failed="4" imp:passes-completions-percentage="87.5" imp:passes-failed-percentage="12.5" imp:passes="32" imp:passes-short-total="22" imp:balls-touched="50" imp:tracking-distance="5579.80" imp:tracking-average-speed="3.41" imp:tracking-max-speed="23.49" imp:tracking-sprints="0" imp:tracking-sprints-distance="0.00" imp:tracking-fast-runs="3" imp:tracking-fast-runs-distance="37.08" imp:tracking-offensive-runs="0" imp:tracking-offensive-runs-distance="0.00" dfl-distance="5579.80" dfl-average-speed="3.41" dfl-max-speed="23.49">
            <stats-soccer-defensive saves="5" imp:catches-punches-crosses="3" imp:catches-punches-corners="0" goals-against-total="1" imp:penalty-saves="0" imp:clear-cut-chance="0" />
            <stats-soccer-offensive shots-total="0" shots-on-goal-total="0" imp:shots-off-post="0" offsides="0" corner-kicks="0" imp:crosses="0" assists-total="0" imp:shot-assists="0" imp:freekicks="3" imp:miss-chance="0" imp:throw-in="0" imp:punt="2" shots-penalty-shot-scored="0" shots-penalty-shot-missed="0" dfl-assists-total="0" imp:shots-total-outside-box="0" imp:shots-total-inside-box="0" imp:shots-foot-inside-box="0" imp:shots-foot-outside-box="0" imp:shots-total-header="0" />
            <stats-soccer-foul fouls-commited="0" fouls-suffered="0" imp:yellow-red-cards="0" imp:red-cards="0" imp:yellow-cards="0" penalty-caused="0" />
          </player-stats-soccer>
        </player-stats>
      </player>
    </team>
  </sports-event>
</sports-content>

I want to extract everything which is within the "player meta tag" and "player-stats coverage" and "player stats soccer" tag.

Body:
This won't be a complete solution for your particular case, because this is a bit of task to do and also I don't have keyboard, working from tablet.

In general, you can do it several ways, depending on whether you really need all data or extract specific subset, and whether you know all the possible structures in advance.

For example, one way:

from lxml import etree
Playerdata=[]
for F in xml_Gameday_Player:
                tree=etree.XML(file_get_contents(F))
                for player in tree.xpath('.//player'):
                        row=[]
                        row['player']=player.xpath('./player-metadata/name/@Last/text()')
                        for plrdata in player.xpath('.//player-stats'):
                               #do stuff with player data
                         Playerdata+=row

This is adapted from my existing script, however, it is more tailored to extracting only a specific subset of xml. If you need all data, it would probably be better to use some xml tree walker.

file_get_contents is a small helper function :

def file_get_contents(filename):
    with open(filename) as f:
        return f.read()

Xpath is a powerful language for finding nodes within xml.
Note that depending on Xpath you use, the result may be either an xml node as in "for player in..." statement, or a string, as in "row['player']=" statement.


问:
Css overflow hidden outside
I hace this structure for create 2 cols and inside content :

```<code>        <style>
    #articulos_content
        {
        position:relative;
        width:100%;
        min-height:400px;
        height:auto;
        margin-left:auto;
        margin-right:auto;
        margin-bottom:30px;
        overflow:hidden;
        }

        #articulos_load_col_left
        {
        float:left;
        position:relative;
        width:72%;
        mini-height:400px;
        height:auto;
        margin-bottom:-50000px;
        padding-bottom:50000px;
        }

        #articulos_load_col_right
        {
        float:right;
        position:relative;
        width:28%;
        mini-height:400px;
        height:auto;
        background-color:#cccccc;
        margin-bottom:-50000px;
        padding-bottom:50000px;
        }
</style>

<div id="articulos_content">
<div id="articulos_load_col_left">Load the articles in bucle</div>
<div id="articulos_load_col_right"></div>
</div>
</code>```

How you can see the style called articulos_content have 2 divs working as cols , and in the col left i load bucle in php for show articles

I have problem with overflow hidden in the style called articulos_content , because the articles have popup for show article´s comments , and the overflow hidden cut this css-window and no let me see all , but overflow:hidden it´s necessary for grow the cols and in this point i don´t know what can i do for fix this problem

Thank´s

答:
As mention by @Venu immadi add "clearfix" as a class in your container,  and add the style in your css.

See below:

```<code><style>
    #articulos_content
    {
        position:relative;
        width:100%;
        min-height:400px;
        height:auto;
        margin-left:auto;
        margin-right:auto;
        margin-bottom:30px;
        overflow:hidden;
    }

    #articulos_load_col_left
    {
        float:left;
        position:relative;
        width:72%;
        mini-height:400px;
        height:auto;
        margin-bottom:-50000px;
        padding-bottom:50000px;
    }

    #articulos_load_col_right
    {
        float:right;
        position:relative;
        width:28%;
        mini-height:400px;
        height:auto;
        background-color:#cccccc;
        margin-bottom:-50000px;
        padding-bottom:50000px;
    }

    .clearfix:after
    {
         content: " "; /* Older browser do not support empty content */
         visibility: hidden;
         display: block;
         height: 0;
         clear: both;
    }

</style>

<div id="articulos_content" class="clearfix">
    <div id="articulos_load_col_left">Load the articles in bucle</div>
    <div id="articulos_load_col_right"></div>
</div>
</code>```

Title: Css overflow hidden outside

Body:
I hace this structure for create 2 cols and inside content :

Load the articles in bucle

How you can see the style called articulos_content have 2 divs working as cols , and in the col left i load bucle in php for show articles

I have problem with overflow hidden in the style called articulos_content , because the articles have popup for show article´s comments , and the overflow hidden cut this css-window and no let me see all , but overflow:hidden it´s necessary for grow the cols and in this point i don´t know what can i do for fix this problem

Thank´s

Body:
As mention by @Venu immadi add "clearfix" as a class in your container,  and add the style in your css.

See below:

<style>
    #articulos_content
    {
        position:relative;
        width:100%;
        min-height:400px;
        height:auto;
        margin-left:auto;
        margin-right:auto;
        margin-bottom:30px;
        overflow:hidden;
    }

    #articulos_load_col_left
    {
        float:left;
        position:relative;
        width:72%;
        mini-height:400px;
        height:auto;
        margin-bottom:-50000px;
        padding-bottom:50000px;
    }

    #articulos_load_col_right
    {
        float:right;
        position:relative;
        width:28%;
        mini-height:400px;
        height:auto;
        background-color:#cccccc;
        margin-bottom:-50000px;
        padding-bottom:50000px;
    }

    .clearfix:after
    {
         content: " "; /* Older browser do not support empty content */
         visibility: hidden;
         display: block;
         height: 0;
         clear: both;
    }

</style>

<div id="articulos_content" class="clearfix">
    <div id="articulos_load_col_left">Load the articles in bucle</div>
    <div id="articulos_load_col_right"></div>
</div>


问:
MySQL - multiple groups and multiple count
I have a table like such named urlTraffic:

```<code>+------------+--------------+------+-----+---------+----------------+
| Field      | Type         | Null | Key | Default | Extra          |
+------------+--------------+------+-----+---------+----------------+
| id         | bigint       | NO   | MUL | NULL    |                |
| location   | char(17)     | NO   |     | NULL    |                |
| domain     | varchar(128) | NO   |     | NULL    |                |
+------------+--------------+------+-----+---------+----------------+
</code>```

I need to get the count of the top 250 domains visited, and then find a count of the total number of locations that it was visited at.

This gives me the top 250 most commonly visited domains:

```<code> select count(1) as domain_visits, domain
 from urlTraffic
 group by domain
 order by domain_visits DESC
 LIMIT 250;
</code>```

with results like:

```<code>+---------------+-----------------+
| domain_visits |     domain      |
+---------------+-----------------+
|    183002     | google.com      |
|    150181     | facebook.com    |
</code>```

and I know that this gives me the a list of the locations:

```<code> select distinct(location)
 from urlTraffic
 where domain = 'google.com';
</code>```

However, I need the result set to be like this:

```<code>+---------------+-------------------------------------+
| domain_visits |     domain      |  number_of_sites  |
+---------------+-------------------------------------+
|    183002     | google.com      |          15       |
|    150181     | facebook.com    |          17       |
|    100002     | t.lkqd.net      |          4        |
</code>```

I know there is a way to perform this query, but can't figure it out.

答:
Something like this will return the specified result

```<code>  SELECT COUNT(1) AS domain_visits
       , ut.domain
       , COUNT(DISTINCT ut.location) AS number_of_sites
    FROM urlTraffic ut
   GROUP BY ut.domain
   ORDER BY domain_visits DESC
   LIMIT 250
</code>```

(if I understood the specification. It's a bit confusing in that the result of this first query is shown with column named "site", when the first query is returning a column named "domain". This answer is based on the assumption that references to "site" were actually intended to be references to "domain".)

Body:
I have a table like such named urlTraffic:

+------------+--------------+------+-----+---------+----------------+
| Field      | Type         | Null | Key | Default | Extra          |
+------------+--------------+------+-----+---------+----------------+
| id         | bigint       | NO   | MUL | NULL    |                |
| location   | char(17)     | NO   |     | NULL    |                |
| domain     | varchar(128) | NO   |     | NULL    |                |
+------------+--------------+------+-----+---------+----------------+

I need to get the count of the top 250 domains visited, and then find a count of the total number of locations that it was visited at.

This gives me the top 250 most commonly visited domains:

 select count(1) as domain_visits, domain
 from urlTraffic
 group by domain
 order by domain_visits DESC
 LIMIT 250;

with results like:

+---------------+-----------------+
| domain_visits |     domain      |
+---------------+-----------------+
|    183002     | google.com      |
|    150181     | facebook.com    |

and I know that this gives me the a list of the locations:

 select distinct(location)
 from urlTraffic
 where domain = 'google.com';

However, I need the result set to be like this:

+---------------+-------------------------------------+
| domain_visits |     domain      |  number_of_sites  |
+---------------+-------------------------------------+
|    183002     | google.com      |          15       |
|    150181     | facebook.com    |          17       |
|    100002     | t.lkqd.net      |          4        |

I know there is a way to perform this query, but can't figure it out.

Body:
Something like this will return the specified result

  SELECT COUNT(1) AS domain_visits
       , ut.domain
       , COUNT(DISTINCT ut.location) AS number_of_sites
    FROM urlTraffic ut
   GROUP BY ut.domain
   ORDER BY domain_visits DESC
   LIMIT 250

(if I understood the specification. It's a bit confusing in that the result of this first query is shown with column named "site", when the first query is returning a column named "domain". This answer is based on the assumption that references to "site" were actually intended to be references to "domain".)


问:
How to resolve UnsatisfiedLinkError when using JNI with packages?
Firstly, my example has the following directory structure:

```<code>Sample.c
lib/
mypackage/
--Sample.java
</code>```

Sample.java in mypackage looks like this:

```<code>package mypackage;

public class Sample {
    public static native int sampleMethod(int x);

    public static void main(String[] args) {
        System.loadLibrary("Sample");
        System.out.println("sampleMethod result: " + sampleMethod(5));
    }
}
</code>```

I run javac mypackage/Sample.java to compile the java file and javah mypackage.Sample to generate the JNI headers. Then I compile the library using the following command:

```<code>clang -I"${JAVA_HOME}/include" -I"${JAVA_HOME}/include/darwin" -o lib/libSample.so -shared Sample.c
</code>```

At this point the directory structure looks like this:

```<code>Sample.c
mypackage_Sample.h
lib/
--libSample.so
mypackage/
--Sample.java
--Sample.class
</code>```

Now when I try to run the example using java -Djava.library.path=./lib/ mypackage.Sample I get the following error:

```<code>Exception in thread "main" java.lang.UnsatisfiedLinkError: no Sample in java.library.path
    at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1867)
    at java.lang.Runtime.loadLibrary0(Runtime.java:870)
    at java.lang.System.loadLibrary(System.java:1122)
    at mypackage.Sample.main(Sample.java:7)
</code>```

I tried specifying the full path to lib/, but I get the same error.

I am not sure if the code for the header and the implementation matter, but I will post them anyway.

mypackage_Sample.h:

```<code>/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class mypackage_Sample */

#ifndef _Included_mypackage_Sample
#define _Included_mypackage_Sample
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     mypackage_Sample
 * Method:    sampleMethod
 * Signature: (I)I
 */
JNIEXPORT jint JNICALL Java_mypackage_Sample_sampleMethod
  (JNIEnv *, jclass, jint);

#ifdef __cplusplus
}
#endif
#endif
</code>```

Sample.c:

```<code>#include "mypackage_Sample.h"
#include <stdio.h>

JNIEXPORT jint JNICALL Java_mypackage_Sample_sampleMethod
  (JNIEnv * env, jclass obj, jint num) {
      return num * num;
  }
</code>```

I run this on OS X Yosemite 10.10.5 using clang 7.0.2 and java 1.8.0_101.

答:
It looks like you have the wrong name from your library file (libSample.so).

If you use:

```<code>System.loadLibrary("Sample");
</code>```

The JVM will map this name to a platform specific file name to try and load. On Linux that is libSample.so, on Windows that is Sample.dll, but on OS X it's something else.

You can find out which name your library file should have by looking at the output of:

```<code>System.mapLibraryName("Sample");
</code>```

Called on the target platform.

After that, you can use that as the name of your library file.

Body:
Firstly, my example has the following directory structure:

Sample.c
lib/
mypackage/
--Sample.java

Sample.java in mypackage looks like this:

package mypackage;

public class Sample {
    public static native int sampleMethod(int x);

    public static void main(String[] args) {
        System.loadLibrary("Sample");
        System.out.println("sampleMethod result: " + sampleMethod(5));
    }
}

I run javac mypackage/Sample.java to compile the java file and javah mypackage.Sample to generate the JNI headers. Then I compile the library using the following command:

clang -I"${JAVA_HOME}/include" -I"${JAVA_HOME}/include/darwin" -o lib/libSample.so -shared Sample.c

At this point the directory structure looks like this:

Sample.c
mypackage_Sample.h
lib/
--libSample.so
mypackage/
--Sample.java
--Sample.class

Now when I try to run the example using java -Djava.library.path=./lib/ mypackage.Sample I get the following error:

Exception in thread "main" java.lang.UnsatisfiedLinkError: no Sample in java.library.path
    at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1867)
    at java.lang.Runtime.loadLibrary0(Runtime.java:870)
    at java.lang.System.loadLibrary(System.java:1122)
    at mypackage.Sample.main(Sample.java:7)

I tried specifying the full path to lib/, but I get the same error.

I am not sure if the code for the header and the implementation matter, but I will post them anyway.

mypackage_Sample.h:

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class mypackage_Sample */

#ifndef _Included_mypackage_Sample
#define _Included_mypackage_Sample
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     mypackage_Sample
 * Method:    sampleMethod
 * Signature: (I)I
 */
JNIEXPORT jint JNICALL Java_mypackage_Sample_sampleMethod
  (JNIEnv *, jclass, jint);

#ifdef __cplusplus
}
#endif
#endif

Sample.c:

#include "mypackage_Sample.h"
#include <stdio.h>

JNIEXPORT jint JNICALL Java_mypackage_Sample_sampleMethod
  (JNIEnv * env, jclass obj, jint num) {
      return num * num;
  }

I run this on OS X Yosemite 10.10.5 using clang 7.0.2 and java 1.8.0_101.

Body:
It looks like you have the wrong name from your library file (libSample.so).

If you use:

System.loadLibrary("Sample");

The JVM will map this name to a platform specific file name to try and load. On Linux that is libSample.so, on Windows that is Sample.dll, but on OS X it's something else.

You can find out which name your library file should have by looking at the output of:

System.mapLibraryName("Sample");

Called on the target platform.

After that, you can use that as the name of your library file.


问:
netbeans form loading issues
```<code>Error in loading component: [jDialog]->mainPanel->titleBar
cannot create instance of <qualified classname>
The component cannot be loaded.

Error in loading layout: [JDialog]->mainPanel->[layout]
Failed to initialize layout of this container

Errors occured in loading the form data. It is not recommended to use this form now in editable mode - data that could not be loaded would be lost after saving the form. Please go through the reported errors, try to fix them if possible, and open the form again. If you choose to open the form as View Only you may see which beans are missing.
</code>```

recently moved a class that was being used in several forms but all the paths in both form and java files were updated to point to the new location. Anyone know what could cause an error like this?

Things I have tried: clean + build, removeing and re-adding all library jar files, making sure the title bar and the old version in SVN were identical except for the package changes. Doing the same comparison with their respective form files.

答:
In the View menu there is an IDE log option that allowed me to see what was happening behind the scenes to cause this error.

custom code for the text of one of the labels was throwing an exception.

Title: netbeans form loading issues

Body:
Error in loading component: [jDialog]->mainPanel->titleBar
cannot create instance of <qualified classname>
The component cannot be loaded.

Error in loading layout: [JDialog]->mainPanel->[layout]
Failed to initialize layout of this container

Errors occured in loading the form data. It is not recommended to use this form now in editable mode - data that could not be loaded would be lost after saving the form. Please go through the reported errors, try to fix them if possible, and open the form again. If you choose to open the form as View Only you may see which beans are missing.

recently moved a class that was being used in several forms but all the paths in both form and java files were updated to point to the new location. Anyone know what could cause an error like this?

Things I have tried: clean + build, removeing and re-adding all library jar files, making sure the title bar and the old version in SVN were identical except for the package changes. Doing the same comparison with their respective form files.


问:
Get a HTML list to dynamically alternate between two columns
I have an html list that I need to get split into two columns. I'm curious if I can do this purely in CSS without changing the HTML code.

For example:

I have a list like this:

Item 1

Item Longer 2

Item really long 3

Item this 4

Item five 5

Item 6

But I want to display the list as two columns with equal width, but without changing the HTML code.

I've tried using child selectors and inline display but I can't figure out how to get the second column to start evenly.

This is what I'm trying to achieve in CSS. That way if I keep adding to the list, it keeps alternating the content between columns, as well as always having the second column be even.

li {
display: inline;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
<li>Item 1</li>
<li>Item Longer 2</li>
<li>Item really long 3</li>
<li>Item this 4</li>
<li>Item five 5</li>
<li>Item 6</li>
</ul></code>```

https://jsfiddle.net/u85avecb/

答:
Try using a flexbox.

ul {
display: flex;
flex-direction: column;
list-style: none;
max-height: 60px;
flex-wrap: wrap;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
<li>Item 1</li>
<li>Item Longer 2</li>
<li>Item really long 3</li>
<li>Item this 4</li>
<li>Item five 5</li>
<li>Item 6</li>
</ul></code>```

Body:
I have an html list that I need to get split into two columns. I'm curious if I can do this purely in CSS without changing the HTML code.

For example:

I have a list like this:

Item 1

Item Longer 2

Item really long 3

Item this 4

Item five 5

Item 6

But I want to display the list as two columns with equal width, but without changing the HTML code.

I've tried using child selectors and inline display but I can't figure out how to get the second column to start evenly.

This is what I'm trying to achieve in CSS. That way if I keep adding to the list, it keeps alternating the content between columns, as well as always having the second column be even.

li {
display: inline;
}

Item 1

Item Longer 2

Item really long 3

Item this 4

Item five 5

Item 6

https://jsfiddle.net/u85avecb/

Body:
Try using a flexbox.

ul {
display: flex;
flex-direction: column;
list-style: none;
max-height: 60px;
flex-wrap: wrap;
}

<ul>
<li>Item 1</li>
<li>Item Longer 2</li>
<li>Item really long 3</li>
<li>Item this 4</li>
<li>Item five 5</li>
<li>Item 6</li>
</ul>


问:
Unignore a directory in git?
I have a directory in my repository that is being ignored. My repository name is CI and in it is a directory .teamcity

I want this directory(.teamcity) to be a normal directory and not be ignored. How would I do that?

答:
I have just fight with this ..

Removing the .gitgnore file was not enough.

I also had to remove the cache with :

```<code>git rm -r --cached
git add .
</code>```

Title: Unignore a directory in git?

Body:
I have just fight with this ..

Removing the .gitgnore file was not enough.

I also had to remove the cache with :

git rm -r --cached
git add .


问:
Lodash filter ignore case
is there a way of case-insensitive filter with lodash? I tried this (see below), but this works only partly (when the user input is also lowercase). Another problem is here after one search all the characters are in lower case.

I want to filter regardless of how (lower case or upper).

```<code> filter(q: string) {
    let query = q.trim();
    let searchData = [];
    searchData = clone(this.data);

    searchData = searchData.map((entity) => {
        entity.email = entity.email.toLowerCase();
        return entity;
    });

    if (query) {
        this.approverEntities = filter(searchData, (a) => a.email.indexOf(query) >= 0);
    } else {
        this.approverEntities = this.data;
    }
}
</code>```

thanks in advance!

答:
This approach worked out great for me:

this.approverEntities = _.filter(searchData, (a) =>  {return new RegExp(a.email, 'i').test(query)});
```

<p>The one caveat is that if the <code>a.email</code> contains any special characters the regex expression will process it as regex tokens (<em>e.g. parenthesis, brackets, etc.</em>). This solution will handle special characters regardless...</p>

<pre class="lang-js prettyprint-override"><code>this.approverEntities = _.filter(searchData, (a) =>  {return a.email.toLowerCase() == query.toLowerCase()});
</code>```

Title: Lodash filter ignore case

Body:
is there a way of case-insensitive filter with lodash? I tried this (see below), but this works only partly (when the user input is also lowercase). Another problem is here after one search all the characters are in lower case.

I want to filter regardless of how (lower case or upper).

 filter(q: string) {
    let query = q.trim();
    let searchData = [];
    searchData = clone(this.data);

    searchData = searchData.map((entity) => {
        entity.email = entity.email.toLowerCase();
        return entity;
    });

    if (query) {
        this.approverEntities = filter(searchData, (a) => a.email.indexOf(query) >= 0);
    } else {
        this.approverEntities = this.data;
    }
}

thanks in advance!

Body:
This approach worked out great for me:

this.approverEntities = _.filter(searchData, (a) =>  {return new RegExp(a.email, 'i').test(query)});

The one caveat is that if the a.email contains any special characters the regex expression will process it as regex tokens (e.g. parenthesis, brackets, etc.). This solution will handle special characters regardless...

this.approverEntities = _.filter(searchData, (a) =>  {return a.email.toLowerCase() == query.toLowerCase()});


问:
how to Add current file to "delete list" except file with mp3 and mp4 extension?
i want to make delete-list but except mp3 and mp4 file

my code is

error
Fatal error: Call to undefined function endsWith() in E:\xampp\htdocs\tes\index.php on line 39

```<code>    $files = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($rootPath),
    RecursiveIteratorIterator::LEAVES_ONLY
);

foreach ($files as $name => $file)
{
    // Skip directories (they would be added automatically)
    if (!$file->isDir())
    {
        // Get real and relative path for current file
        $filePath = $file->getRealPath();
        $relativePath = substr($filePath, strlen($rootPath) + 1);

        // Add current file to archive
        $zip->addFile($filePath, $relativePath);
        $zip->close();

        // Add current file to "delete list"
        // delete it later cause ZipArchive create archive only after calling close function and ZipArchive lock files until archive created)
        if ($file->getFilename().endsWith(".mp3")) error at this code
        {
            $filesToDelete[] = $filePath;
        }
    }
}
</code>```

anyone help me please

答:
The is no endsWith function. You need to create your own. Check this example.

startsWith() and endsWith() functions in PHP

Body:
i want to make delete-list but except mp3 and mp4 file

my code is

error
Fatal error: Call to undefined function endsWith() in E:\xampp\htdocs\tes\index.php on line 39

    $files = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($rootPath),
    RecursiveIteratorIterator::LEAVES_ONLY
);

foreach ($files as $name => $file)
{
    // Skip directories (they would be added automatically)
    if (!$file->isDir())
    {
        // Get real and relative path for current file
        $filePath = $file->getRealPath();
        $relativePath = substr($filePath, strlen($rootPath) + 1);

        // Add current file to archive
        $zip->addFile($filePath, $relativePath);
        $zip->close();

        // Add current file to "delete list"
        // delete it later cause ZipArchive create archive only after calling close function and ZipArchive lock files until archive created)
        if ($file->getFilename().endsWith(".mp3")) error at this code
        {
            $filesToDelete[] = $filePath;
        }
    }
}

anyone help me please


问:
C#Append data from one text file to another and then acknowledge user that it was done successfully
I have a program in C# where I need to append all the data from the a text file to another text file, then the clear the first text file. Now I need some way to check if the data has been completely transferred and was successful and then display this information to the user in a MessageBox saying this was successful.

Here is what I am currently doing to append the data.

```<code> private void updateLog()
    {
        #region ifexists

        if (!File.Exists(localLog + "A.txt"))
        {
            FileStream file = File.Create(localLog + "A.txt");
            file.Close();
        }
        if (!File.Exists(localLog + "B.txt"))
        {
            FileStream file = File.Create(localLog + "B.txt");
            file.Close();
        }

        #endregion

        try
        {
            //reading files into input & output
            using (Stream a_input = File.OpenRead(localLog + @"\A.txt"))
            using (Stream b_input = File.OpenRead(localLog + @"\B.txt"))

            using (Stream a_output = new FileStream(server + @"\A.txt", FileMode.Append, FileAccess.Write, FileShare.None))
            using (Stream b_output = new FileStream(server + @"\B.txt", FileMode.Append, FileAccess.Write, FileShare.None))
            {
                //copying from input to output
                a_input.CopyTo(a_output);
                b_input.CopyTo(b_output);
                copiedFlag = true; // I want some sort of flag to check, this is not much help
            }

            //clearing input
            if (copiedFlag == true) // based on that flag I want to clear the 1st text, if the data is not copied then I do not want to clear the 1st text file
            {
                File.WriteAllText(localLog + @"\A.txt", string.Empty);
                File.WriteAllText(localLog + @"\B.txt", string.Empty);
            }
        }
        catch (Exception a)
        {
            System.Diagnostics.Debug.WriteLine("synchronization");
            exceptionHandler();
        }
    }
</code>```

All I'm doing is appending one file to another and then clearing the first file, but I want to make sure that the data is appended before I clear and loose it.

答: Your approach seems like overkill.  Why not use System.IO.File.Copy method?  You don't need to open streams to do a plain file copy.</p>

Body:
I have a program in C# where I need to append all the data from the a text file to another text file, then the clear the first text file. Now I need some way to check if the data has been completely transferred and was successful and then display this information to the user in a MessageBox saying this was successful.

Here is what I am currently doing to append the data.

 private void updateLog()
    {
        #region ifexists

        if (!File.Exists(localLog + "A.txt"))
        {
            FileStream file = File.Create(localLog + "A.txt");
            file.Close();
        }
        if (!File.Exists(localLog + "B.txt"))
        {
            FileStream file = File.Create(localLog + "B.txt");
            file.Close();
        }

        #endregion

        try
        {
            //reading files into input & output
            using (Stream a_input = File.OpenRead(localLog + @"\A.txt"))
            using (Stream b_input = File.OpenRead(localLog + @"\B.txt"))

            using (Stream a_output = new FileStream(server + @"\A.txt", FileMode.Append, FileAccess.Write, FileShare.None))
            using (Stream b_output = new FileStream(server + @"\B.txt", FileMode.Append, FileAccess.Write, FileShare.None))
            {
                //copying from input to output
                a_input.CopyTo(a_output);
                b_input.CopyTo(b_output);
                copiedFlag = true; // I want some sort of flag to check, this is not much help
            }

            //clearing input
            if (copiedFlag == true) // based on that flag I want to clear the 1st text, if the data is not copied then I do not want to clear the 1st text file
            {
                File.WriteAllText(localLog + @"\A.txt", string.Empty);
                File.WriteAllText(localLog + @"\B.txt", string.Empty);
            }
        }
        catch (Exception a)
        {
            System.Diagnostics.Debug.WriteLine("synchronization");
            exceptionHandler();
        }
    }

All I'm doing is appending one file to another and then clearing the first file, but I want to make sure that the data is appended before I clear and loose it.


问:
PHP - highlight text from a string containing HTML
So I'm making a search function for comments. Someone else here helped me with the SQL query.
What I also want to do is to highlight the search query text in the results.

The results are stored as HTML inside a $variable.
How can I wrap the search query text inside a  tag for example, without messing up the html.

for eg. the search query can be foo bar and the output can look like:

```<code><p>bla bla foo bar bla</p>
</code>```

so it should be something like:

```<code><p>bla <span class="highlight">foo bar</span> bla bla</p>
</code>```

答:
Simple find and replace:</p>

```<code>$resultHTML = str_replace($searchString, '<span class="highlight">'.$searchString.'</span>', $resultHTML );
</code>```

Body:
So I'm making a search function for comments. Someone else here helped me with the SQL query.
What I also want to do is to highlight the search query text in the results.

The results are stored as HTML inside a $variable.
How can I wrap the search query text inside a  tag for example, without messing up the html.

for eg. the search query can be foo bar and the output can look like:

bla bla foo bar bla

so it should be something like:

bla foo bar bla bla

Body:
Simple find and replace:

$resultHTML = str_replace($searchString, '<span class="highlight">'.$searchString.'</span>', $resultHTML );


问:
Javascript hide menu on outside click
I got the following html:

```<code><div id="otherdiv"></div>
 <div class="overlay">
  <div class="menu">
    <ul>
      <li><a href="#">Val1</a></li>
     <li><a href="#">Val2</a></li>
    </ul>
   </div>
</div>
</code>```

and JS code:

```<code>$(document).ready(function(){
$('#otherdiv').on('mouseup', function(e){
     var left  = e.clientX  + "px";
     var top  = e.clientY  + "px";
     var div = $('.overlay');
     div[0].style.left = left;
     div[0].style.top = top;
     $(".overlay").show(200);
   });
 $(document).on('click', function(e) {
    $('.overlay').hide(200);
  });
});
</code>```

I need to hide my .overlay when the user clicks somewhere outside it and show it when the user clicks #otherdiv. When I attach an event to document and click on otherdiv, my overlay shows and then immediately hides. How to fix that behaviour? Thank you.

答:
On document.click check if the event.target is not the #otherdiv  or  is not a children of the #otherdiv and  event.target is not the .overlay or its children then hide the $(".overlay").

A sample snippet.Added a css for the #otherdiv and .overlay for demo>the overlay will be hidden only when the user clicks outside

$(document).ready(function(){
 $('#otherdiv').on('mouseup', function(e){
      e.preventDefault();
     var left  = e.clientX  + "px";
     var top  = e.clientY  + "px";
     var div = $('.overlay');
     div[0].style.left = left;
     div[0].style.top = top;
     $(".overlay").show(200);
   });
  $(document).on('click', function(e) {

  if( ! $('#otherdiv').is(e.target)&&    $('#otherdiv').has(e.target).length === 0 && !$('.overlay').is(e.target)  && $('.overlay').has(e.target).length === 0 ){
    $('.overlay').hide(200);
  }

  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#otherdiv{
 width:100%;
 height:50px;
 background:#ddd;
}

.overlay{

 background:red;
}</code>```

  click here to show

Val1

Val2

```

Title: Javascript hide menu on outside click

Body:
I got the following html:

Val1

Val2

and JS code:

$(document).ready(function(){
$('#otherdiv').on('mouseup', function(e){
     var left  = e.clientX  + "px";
     var top  = e.clientY  + "px";
     var div = $('.overlay');
     div[0].style.left = left;
     div[0].style.top = top;
     $(".overlay").show(200);
   });
 $(document).on('click', function(e) {
    $('.overlay').hide(200);
  });
});

I need to hide my .overlay when the user clicks somewhere outside it and show it when the user clicks #otherdiv. When I attach an event to document and click on otherdiv, my overlay shows and then immediately hides. How to fix that behaviour? Thank you.

Body:
On document.click check if the event.target is not the #otherdiv  or  is not a children of the #otherdiv and  event.target is not the .overlay or its children then hide the $(".overlay").

A sample snippet.Added a css for the #otherdiv and .overlay for demo>the overlay will be hidden only when the user clicks outside

$(document).ready(function(){
 $('#otherdiv').on('mouseup', function(e){
      e.preventDefault();
     var left  = e.clientX  + "px";
     var top  = e.clientY  + "px";
     var div = $('.overlay');
     div[0].style.left = left;
     div[0].style.top = top;
     $(".overlay").show(200);
   });
  $(document).on('click', function(e) {

  if( ! $('#otherdiv').is(e.target)&&    $('#otherdiv').has(e.target).length === 0 && !$('.overlay').is(e.target)  && $('.overlay').has(e.target).length === 0 ){
    $('.overlay').hide(200);
  }

  });
});

#otherdiv{
 width:100%;
 height:50px;
 background:#ddd;
}

.overlay{

 background:red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="otherdiv">
  click here to show
</div>
 <div class="overlay">
  <div class="menu">
    <ul>
      <li><a href="#">Val1</a></li>
     <li><a href="#">Val2</a></li>
    </ul>
   </div>
</div>


问:
Passing additional parameter to d3.svg.line()
I'm making a site that graphs datasets picked by the user from a large collection.  In order to normalize the plots (user option) I'm finding max(y) for each dataset and I'm trying to use that as a denominator in my line().y() but I can't figure out a good way to get it in.

The datasets are csvs that all look like this:

```<code>site0586,id,depth,age,sed,quant,conc,influx,level
1, 94297, 0.1400, 8.390, 0.097, 50.5100, 50.5100, 4.87496, "C0P0"
2, 94298, 0.1760, 45.690, 0.083, 52.5800, 52.5800, 4.35011, "C0P0"
3, 94299, 0.2030, 73.660, 0.135, 29.8500, 29.8500, 4.03080, "C0P0"
...
</code>```

Default x and y are "age" and "conc" but are user-choosable.  User picks datasets and they get plotted on the same graph, one after another.  As plots are added the graph's scale adjusts to fit the overall max-x and max-y and earlier plots update to conform.  X's can vary between datasets by a good bit and y's can vary by five orders of magnitude so small-value lines can get considerably squashed.  Got this going with a little transitioning and it works great.

Sometimes User wants to see the y's with a [0,1] normalization so small-value trends will be visible on the same x-scale as large-value ones; that's an option.  Easy -- reset the y domain to [0,1] and divide each plot's y's by that dataset's max(y).  For the dots that works perfectly; for the lines I'm having a lot of trouble.

It's one graph so I build one data structure; as User picks each dataset I download it, nest() it and push it onto an array, and since I'm going to need the maxes later, while I'm there I find the domains of each variable, put them in an object called heads and append that to the nested data.  So my data structure looks like this:

```<code>datae:  [
{ "key": "300",
  "values": [
    {"site0300": 1, "id": 60383, "depth": 0,  ... }, ...
    {"site0300": 182, ... }
  ],
  "heads": { "depth": [0,5.9], "age": [107.4,16589.5], ...}
},
{ "key": "586",
  "values": [
    {"site0586": 1, ...}, ...
  ],
  "heads": {...}
}
]
</code>```

I've got my line().y() set up to (potentially) use a denominator that could be either 1 or thisData.max(y):

```<code>var lineFn = d3.svg.line()
  .x(function(d) { return xScale(d[xVar]) })
  .y(function(d) { return yScale(d[yVar]/normer) });
</code>```

except I can't figure out how to get datae[thisLineIdx].heads[yVar[1]] into the call:

```<code>var lines = graf.selectAll('.line')
  .data(datae);

lines.enter()
  .append('path')
    .attr("d", function(d) { return lineFn(d.values) })
</code>```

Each member of lines gets the right entry from datae but since svg.line() only wants to hear about arrays (and won't communicate anything from its insides) it only does anything if I call it with datae[thisLineIdx].values, and then datae[thisLineIdx].heads is inaccessible.

I could set up all the datae[idx].heads as a global but there must be a better way than that -- I just can't see any way to calculate that max(y) from within line(), nor any idiomatic way to include it in the call.

答:
Ach -- duh!  Been stuck on this (one day a week) for ages, and was halfway there all the time.  Now that last code block goes:

```<code>var lines = graf.selectAll('.line')
  .data(datae);

lines.enter()
  .append('path')
    .attr("d", function(d) {
      normer = gOpts.normIt.state ? d.heads[yVar][1] : 1;
      return lineFn(d.values) })
</code>```

And now my lineFn() does what I want, when I want.

However, I dislike this solution because it does leave normer (declared at a higher level) floating around in a semi-global way, outside the relevant scope, ready to cause some other mischief.  So I consider this the dumb way and if anyone can suggest something more sophisticated I'd be very grateful.

Body:
I'm making a site that graphs datasets picked by the user from a large collection.  In order to normalize the plots (user option) I'm finding max(y) for each dataset and I'm trying to use that as a denominator in my line().y() but I can't figure out a good way to get it in.

The datasets are csvs that all look like this:

site0586,id,depth,age,sed,quant,conc,influx,level
1, 94297, 0.1400, 8.390, 0.097, 50.5100, 50.5100, 4.87496, "C0P0"
2, 94298, 0.1760, 45.690, 0.083, 52.5800, 52.5800, 4.35011, "C0P0"
3, 94299, 0.2030, 73.660, 0.135, 29.8500, 29.8500, 4.03080, "C0P0"
...

Default x and y are "age" and "conc" but are user-choosable.  User picks datasets and they get plotted on the same graph, one after another.  As plots are added the graph's scale adjusts to fit the overall max-x and max-y and earlier plots update to conform.  X's can vary between datasets by a good bit and y's can vary by five orders of magnitude so small-value lines can get considerably squashed.  Got this going with a little transitioning and it works great.

Sometimes User wants to see the y's with a [0,1] normalization so small-value trends will be visible on the same x-scale as large-value ones; that's an option.  Easy -- reset the y domain to [0,1] and divide each plot's y's by that dataset's max(y).  For the dots that works perfectly; for the lines I'm having a lot of trouble.

It's one graph so I build one data structure; as User picks each dataset I download it, nest() it and push it onto an array, and since I'm going to need the maxes later, while I'm there I find the domains of each variable, put them in an object called heads and append that to the nested data.  So my data structure looks like this:

datae:  [
{ "key": "300",
  "values": [
    {"site0300": 1, "id": 60383, "depth": 0,  ... }, ...
    {"site0300": 182, ... }
  ],
  "heads": { "depth": [0,5.9], "age": [107.4,16589.5], ...}
},
{ "key": "586",
  "values": [
    {"site0586": 1, ...}, ...
  ],
  "heads": {...}
}
]

I've got my line().y() set up to (potentially) use a denominator that could be either 1 or thisData.max(y):

var lineFn = d3.svg.line()
  .x(function(d) { return xScale(d[xVar]) })
  .y(function(d) { return yScale(d[yVar]/normer) });

except I can't figure out how to get datae[thisLineIdx].heads[yVar[1]] into the call:

var lines = graf.selectAll('.line')
  .data(datae);

lines.enter()
  .append('path')
    .attr("d", function(d) { return lineFn(d.values) })

Each member of lines gets the right entry from datae but since svg.line() only wants to hear about arrays (and won't communicate anything from its insides) it only does anything if I call it with datae[thisLineIdx].values, and then datae[thisLineIdx].heads is inaccessible.

I could set up all the datae[idx].heads as a global but there must be a better way than that -- I just can't see any way to calculate that max(y) from within line(), nor any idiomatic way to include it in the call.

Body:
Ach -- duh!  Been stuck on this (one day a week) for ages, and was halfway there all the time.  Now that last code block goes:

var lines = graf.selectAll('.line')
  .data(datae);

lines.enter()
  .append('path')
    .attr("d", function(d) {
      normer = gOpts.normIt.state ? d.heads[yVar][1] : 1;
      return lineFn(d.values) })

And now my lineFn() does what I want, when I want.

However, I dislike this solution because it does leave normer (declared at a higher level) floating around in a semi-global way, outside the relevant scope, ready to cause some other mischief.  So I consider this the dumb way and if anyone can suggest something more sophisticated I'd be very grateful.


问:
type of high order functions
if I specify the (I think) correct type for a high order function the OCaml compiler rejects the second usage of that function.

The code

```<code>let foo ():string  =
    let f: ('a -> string) -> 'a -> string = fun g v -> g v
    in let h = string_of_int
    in let i = string_of_float
    in let x = f h 23
    in let y = f i 23.0
    in x ^ y
</code>```

leads to the following error message

```File "test.ml", line 6, characters 14-15:
Error: This expression has type float -> string
       but an expression was expected of type int -> string```

So the first usage of f seems to fix the type of its first parameter to int -> string. I could understand that. But what I don't get is that omitting the type restriction on f fixes the problem.

```<code>let foo ():string  =
    let f g v = g v
    in let h = string_of_int
    in let i = string_of_float
    in let x = f h 23
    in let y = f i 23.0
    in x ^ y</code>```

And moving f to global scope fixes the problem, too:

```<code>let f: ('a -> string) -> 'a -> string = fun g v -> g v

let foo ():string  =
  let h = string_of_int
  in let i = string_of_float
  in let x = f h 23
  in let y = f i 23.0
  in x ^ y</code>```

Why is it that the first example does not compile while the later ones do?

答:
As a reference point, the equivalent F#

```<code>let foo ():string  =
    let f: ('a -> string) -> 'a -> string = fun g v -> g v
    let h = string
    let i = string
    let x = f h 23
    let y = f i 23.0
    x ^ y
</code>```

compiles.

Title: type of high order functions

Body:
if I specify the (I think) correct type for a high order function the OCaml compiler rejects the second usage of that function.

The code

let foo ():string  =
    let f: ('a -> string) -> 'a -> string = fun g v -> g v
    in let h = string_of_int
    in let i = string_of_float
    in let x = f h 23
    in let y = f i 23.0
    in x ^ y

leads to the following error message

File "test.ml", line 6, characters 14-15:
Error: This expression has type float -> string
       but an expression was expected of type int -> string

So the first usage of f seems to fix the type of its first parameter to int -> string. I could understand that. But what I don't get is that omitting the type restriction on f fixes the problem.

let foo ():string  =
    let f g v = g v
    in let h = string_of_int
    in let i = string_of_float
    in let x = f h 23
    in let y = f i 23.0
    in x ^ y

And moving f to global scope fixes the problem, too:

let f: ('a -> string) -> 'a -> string = fun g v -> g v

let foo ():string  =
  let h = string_of_int
  in let i = string_of_float
  in let x = f h 23
  in let y = f i 23.0
  in x ^ y

Why is it that the first example does not compile while the later ones do?

Body:
As a reference point, the equivalent F#

let foo ():string  =
    let f: ('a -> string) -> 'a -> string = fun g v -> g v
    let h = string
    let i = string
    let x = f h 23
    let y = f i 23.0
    x ^ y

compiles.