问:
Spring kafka does not support Large message consumers
I am using spring Kafka to consume message produced by LinkedIn large message supported Kafka client

Given that this Kafka client always overrides AUTO_OFFSET_RESET_CONFIG to none as shown in its constructor.

```<code>private LiKafkaConsumerImpl(LiKafkaConsumerConfig configs,
    Deserializer<K> keyDeserializer,
    Deserializer<V> valueDeserializer,
    Deserializer<LargeMessageSegment> largeMessageSegmentDeserializer,
    Auditor<K, V> consumerAuditor) {
        _kafkaConsumer = new KafkaConsumer<>(configs.configForVanillaConsumer(),
        byteArrayDeserializer,
        byteArrayDeserializer);
    }
Map<String, Object> configForVanillaConsumer() {
    Map<String, Object> newConfigs = new HashMap<>();
    newConfigs.putAll(this.originals());
    newConfigs.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);
    newConfigs.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "none");
    return newConfigs;
}
</code>```

So Once I start using batch commit and setting the ENABLE_AUTO_COMMIT_CONFIG to false, it throws the following error:

[org.springframework.kafka.KafkaListenerEndpointContainer#0-1-C-1] ERROR o.a.k.c.c.i.ConsumerCoordinator - User provided listener com.linkedin.kafka.clients.consumer.LiKafkaConsumerRebalanceListener for group document-event-consumer failed on partition assignment org.apache.kafka.clients.consumer.NoOffsetForPartitionException: Undefined offset with no reset policy for partition: DocumentEvents-2
          at org.apache.kafka.clients.consumer.internals.Fetcher.resetOffset(Fetcher.java:369)
          at org.apache.kafka.clients.consumer.internals.Fetcher.updateFetchPositions(Fetcher.java:247)
          at org.apache.kafka.clients.consumer.KafkaConsumer.updateFetchPositions(KafkaConsumer.java:1602)
          at org.apache.kafka.clients.consumer.KafkaConsumer.position(KafkaConsumer.java:1265)
          at com.linkedin.kafka.clients.consumer.LiKafkaConsumerImpl.position(LiKafkaConsumerImpl.java:403)
          at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer$1.onPartitionsAssigned(KafkaMessageListenerContainer.java:447)
          at com.linkedin.kafka.clients.consumer.LiKafkaConsumerRebalanceListener.onPartitionsAssigned(LiKafkaConsumerRebalanceListener.java:62)
          at org.apache.kafka.clients.consumer.internals.ConsumerCoordinator.onJoinComplete(ConsumerCoordinator.java:255)
          at org.apache.kafka.clients.consumer.internals.AbstractCoordinator.joinGroupIfNeeded(AbstractCoordinator.java:339)
          at org.apache.kafka.clients.consumer.internals.AbstractCoordinator.ensureActiveGroup(AbstractCoordinator.java:303)
          at org.apache.kafka.clients.consumer.internals.ConsumerCoordinator.poll(ConsumerCoordinator.java:286)
          at org.apache.kafka.clients.consumer.KafkaConsumer.pollOnce(KafkaConsumer.java:1030)
          at org.apache.kafka.clients.consumer.KafkaConsumer.poll(KafkaConsumer.java:995)
          at com.linkedin.kafka.clients.consumer.LiKafkaConsumerImpl.poll(LiKafkaConsumerImpl.java:231)
          at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.run(KafkaMessageListenerContainer.java:558)
          at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
          at java.util.concurrent.FutureTask.run(FutureTask.java:266)
          at java.lang.Thread.run(Thread.java:745)

This issue happens because it is the first time for this consumer group to consume messages from this topic, so it tries to use the offset reset policy.

Although I set it to "earliest", it got overridden to "none" by the underlying LinkedIn kafka client

I tried also to override ConsumerRebalanceListener to manually seek to the beginning in this case, but actually it does not come to this point.

How can I solve this issue?

答:
Interesting; please open an issue in GitHub.

We should catch that exception if the policy is none.

In the meantime, you might be able to work around it by using the regular client just once, to actually set an initial offset for the group (you don't have to actually have to receive any messages, just get the partitions assigned and set the initial position for the group).

Body:
I am using spring Kafka to consume message produced by LinkedIn large message supported Kafka client

Given that this Kafka client always overrides AUTO_OFFSET_RESET_CONFIG to none as shown in its constructor.

private LiKafkaConsumerImpl(LiKafkaConsumerConfig configs,
    Deserializer<K> keyDeserializer,
    Deserializer<V> valueDeserializer,
    Deserializer<LargeMessageSegment> largeMessageSegmentDeserializer,
    Auditor<K, V> consumerAuditor) {
        _kafkaConsumer = new KafkaConsumer<>(configs.configForVanillaConsumer(),
        byteArrayDeserializer,
        byteArrayDeserializer);
    }
Map<String, Object> configForVanillaConsumer() {
    Map<String, Object> newConfigs = new HashMap<>();
    newConfigs.putAll(this.originals());
    newConfigs.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);
    newConfigs.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "none");
    return newConfigs;
}

So Once I start using batch commit and setting the ENABLE_AUTO_COMMIT_CONFIG to false, it throws the following error:

[org.springframework.kafka.KafkaListenerEndpointContainer#0-1-C-1] ERROR o.a.k.c.c.i.ConsumerCoordinator - User provided listener com.linkedin.kafka.clients.consumer.LiKafkaConsumerRebalanceListener for group document-event-consumer failed on partition assignment org.apache.kafka.clients.consumer.NoOffsetForPartitionException: Undefined offset with no reset policy for partition: DocumentEvents-2
          at org.apache.kafka.clients.consumer.internals.Fetcher.resetOffset(Fetcher.java:369)
          at org.apache.kafka.clients.consumer.internals.Fetcher.updateFetchPositions(Fetcher.java:247)
          at org.apache.kafka.clients.consumer.KafkaConsumer.updateFetchPositions(KafkaConsumer.java:1602)
          at org.apache.kafka.clients.consumer.KafkaConsumer.position(KafkaConsumer.java:1265)
          at com.linkedin.kafka.clients.consumer.LiKafkaConsumerImpl.position(LiKafkaConsumerImpl.java:403)
          at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer$1.onPartitionsAssigned(KafkaMessageListenerContainer.java:447)
          at com.linkedin.kafka.clients.consumer.LiKafkaConsumerRebalanceListener.onPartitionsAssigned(LiKafkaConsumerRebalanceListener.java:62)
          at org.apache.kafka.clients.consumer.internals.ConsumerCoordinator.onJoinComplete(ConsumerCoordinator.java:255)
          at org.apache.kafka.clients.consumer.internals.AbstractCoordinator.joinGroupIfNeeded(AbstractCoordinator.java:339)
          at org.apache.kafka.clients.consumer.internals.AbstractCoordinator.ensureActiveGroup(AbstractCoordinator.java:303)
          at org.apache.kafka.clients.consumer.internals.ConsumerCoordinator.poll(ConsumerCoordinator.java:286)
          at org.apache.kafka.clients.consumer.KafkaConsumer.pollOnce(KafkaConsumer.java:1030)
          at org.apache.kafka.clients.consumer.KafkaConsumer.poll(KafkaConsumer.java:995)
          at com.linkedin.kafka.clients.consumer.LiKafkaConsumerImpl.poll(LiKafkaConsumerImpl.java:231)
          at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.run(KafkaMessageListenerContainer.java:558)
          at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
          at java.util.concurrent.FutureTask.run(FutureTask.java:266)
          at java.lang.Thread.run(Thread.java:745)

This issue happens because it is the first time for this consumer group to consume messages from this topic, so it tries to use the offset reset policy.

Although I set it to "earliest", it got overridden to "none" by the underlying LinkedIn kafka client

I tried also to override ConsumerRebalanceListener to manually seek to the beginning in this case, but actually it does not come to this point.

How can I solve this issue?


来源: stackexchange

问:
Bundle angular 2 project with lazy loaded module using gulp
I have an app which serves components with lazy loading and it works fine on development environment but it gives an error after I bundle it for production mentioned below.

```<code>ErrorHandler : Error: Uncaught (in promise): TypeError: System.import is not a function
TypeError: System.import is not a function
    at a.loadAndCompile (1499149250078.main.bundle.js?version=4562730455:formatted:37406)
    at a.load (1499149250078.main.bundle.js?version=4562730455:formatted:37397)
    at a.loadModuleFactory (1499149250078.main.bundle.js?version=4562730455:formatted:42937)
    at a.load (1499149250078.main.bundle.js?version=4562730455:formatted:42926)
    at b.project (1499149250078.main.bundle.js?version=4562730455:formatted:43327)
    at b._tryNext (1499149250078.main.bundle.js?version=4562730455:formatted:50090)
    at b._next (1499149250078.main.bundle.js?version=4562730455:formatted:50084)
    at b.next (1499149250078.main.bundle.js?version=4562730455:formatted:55977)
    at b._subscribe (1499149250078.main.bundle.js?version=4562730455:formatted:54037)
    at b.a.subscribe (1499149250078.main.bundle.js?version=4562730455:formatted:55865)
</code>```

this is how I am creating a bundle using gulp

```<code>gulp.task('bundle:app', function () {
     var builder = new Builder('./','./systemjs.config.js');
     builder.buildStatic('app/main.js', './dist/' + jsMainBundleName, {minify:true})
        .catch(function (err) {
            console.log('App bundle error');
            console.log(err);
        });
});
</code>```

Here is my system.config.js

```<code>(function (global) {

  var angular2ModalVer = '@2.0.0-beta.11';
  //var plugin = 'bootstrap'; // js-native / vex
  global.angular2ModalVer = angular2ModalVer;

  System.config({
    paths: {
      // paths serve as alias
      'npm:': 'node_modules/'
    },
    // map tells the System loader where to look for things
    map: {
      // our app is within the app folder
      app: 'app',

      // angular bundles
      '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
      '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
      '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
      '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
      '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
      '@angular/upgrade': 'npm:@angular/upgrade/bundles/upgrade.umd.js',

      // other libraries
      'rxjs': 'npm:rxjs',
      '@angular2-material/core': 'npm:@angular2-material/core/core.umd.js',
      '@angular2-material/toolbar': 'npm:@angular2-material/toolbar/toolbar.umd.js',
      '@angular2-material/sidenav': 'npm:@angular2-material/sidenav/sidenav.umd.js',
      'ng2-cookies': 'node_modules/ng2-cookies',
      'angular2-modal': 'node_modules/angular2-modal',
      'angular2-modal/plugins/bootstrap': 'node_modules/angular2-modal/bundles/angular2-modal.bootstrap.umd.js',

      //shims
      'core-js-shim': 'npm:core-js/client/shim.min.js',
      'zone': 'npm:zone.js/dist/zone.js',
      'reflect': 'npm:reflect-metadata/Reflect.js',
      'css': 'node_modules/systemjs-plugin-css/css.js',
      'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
      //'angular2-in-memory-web-api': { main: 'index.js', defaultExtension: 'js' },
    },

    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
      app: {
        main: './main.js',
        defaultExtension: 'js'
      },
      rxjs: {
        defaultExtension: 'js'
      },
      'ng2-cookies': {
        defaultExtension: 'js'
      },
      'angular2-modal': {
        defaultExtension: 'js', main: 'bundles/angular2-modal.umd'
      },
      'angular2-modal/plugins/bootstrap}': {
        defaultExtension: 'js', main: 'angular2-modal.bootstrap.umd'
      },
      'angular2-in-memory-web-api': {
        defaultExtension: 'js', main: 'index.js'
      },
    }
  });
})(this);
</code>```

and this is how I am routing the modules.

```<code>{ path: 'profile', loadChildren:'./app/ui/dashboard/profile.module#ProfileRouteModule' }
</code>```

Thank You!

答:
You will need to add the system polyfill to your index.html page

e.g

```<code><script src="node_modules/systemjs/dist/system.src.js"></script>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have an app which serves components with lazy loading and it works fine on development environment but it gives an error after I bundle it for production mentioned below.

ErrorHandler : Error: Uncaught (in promise): TypeError: System.import is not a function
TypeError: System.import is not a function
    at a.loadAndCompile (1499149250078.main.bundle.js?version=4562730455:formatted:37406)
    at a.load (1499149250078.main.bundle.js?version=4562730455:formatted:37397)
    at a.loadModuleFactory (1499149250078.main.bundle.js?version=4562730455:formatted:42937)
    at a.load (1499149250078.main.bundle.js?version=4562730455:formatted:42926)
    at b.project (1499149250078.main.bundle.js?version=4562730455:formatted:43327)
    at b._tryNext (1499149250078.main.bundle.js?version=4562730455:formatted:50090)
    at b._next (1499149250078.main.bundle.js?version=4562730455:formatted:50084)
    at b.next (1499149250078.main.bundle.js?version=4562730455:formatted:55977)
    at b._subscribe (1499149250078.main.bundle.js?version=4562730455:formatted:54037)
    at b.a.subscribe (1499149250078.main.bundle.js?version=4562730455:formatted:55865)

this is how I am creating a bundle using gulp

gulp.task('bundle:app', function () {
     var builder = new Builder('./','./systemjs.config.js');
     builder.buildStatic('app/main.js', './dist/' + jsMainBundleName, {minify:true})
        .catch(function (err) {
            console.log('App bundle error');
            console.log(err);
        });
});

Here is my system.config.js

(function (global) {

  var angular2ModalVer = '@2.0.0-beta.11';
  //var plugin = 'bootstrap'; // js-native / vex
  global.angular2ModalVer = angular2ModalVer;

  System.config({
    paths: {
      // paths serve as alias
      'npm:': 'node_modules/'
    },
    // map tells the System loader where to look for things
    map: {
      // our app is within the app folder
      app: 'app',

      // angular bundles
      '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
      '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
      '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
      '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
      '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
      '@angular/upgrade': 'npm:@angular/upgrade/bundles/upgrade.umd.js',

      // other libraries
      'rxjs': 'npm:rxjs',
      '@angular2-material/core': 'npm:@angular2-material/core/core.umd.js',
      '@angular2-material/toolbar': 'npm:@angular2-material/toolbar/toolbar.umd.js',
      '@angular2-material/sidenav': 'npm:@angular2-material/sidenav/sidenav.umd.js',
      'ng2-cookies': 'node_modules/ng2-cookies',
      'angular2-modal': 'node_modules/angular2-modal',
      'angular2-modal/plugins/bootstrap': 'node_modules/angular2-modal/bundles/angular2-modal.bootstrap.umd.js',

      //shims
      'core-js-shim': 'npm:core-js/client/shim.min.js',
      'zone': 'npm:zone.js/dist/zone.js',
      'reflect': 'npm:reflect-metadata/Reflect.js',
      'css': 'node_modules/systemjs-plugin-css/css.js',
      'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
      //'angular2-in-memory-web-api': { main: 'index.js', defaultExtension: 'js' },
    },

    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
      app: {
        main: './main.js',
        defaultExtension: 'js'
      },
      rxjs: {
        defaultExtension: 'js'
      },
      'ng2-cookies': {
        defaultExtension: 'js'
      },
      'angular2-modal': {
        defaultExtension: 'js', main: 'bundles/angular2-modal.umd'
      },
      'angular2-modal/plugins/bootstrap}': {
        defaultExtension: 'js', main: 'angular2-modal.bootstrap.umd'
      },
      'angular2-in-memory-web-api': {
        defaultExtension: 'js', main: 'index.js'
      },
    }
  });
})(this);

and this is how I am routing the modules.

{ path: 'profile', loadChildren:'./app/ui/dashboard/profile.module#ProfileRouteModule' }

Thank You!

Body:
You will need to add the system polyfill to your index.html page

e.g

<script src="node_modules/systemjs/dist/system.src.js"></script>


问:
Binding text blocks inside a user control using MVVM and WPF
I am still new in MVVM and WPF
and I've looked at some examples however still did not found exactly the answers to my question.

I have a ListBox which each Item should add a new user control using ObservableCollection. In the user control I have an several Text blocks which I want to bound the texts of them to the same ObservableCollection which contain the Data.

However I am not sure how to bind the Text blocks to the ObservableCollection

Would be happy for a code example.

I'm also attaching my code, this is my userControl XAML:

```<code><UserControl x:Class="ProtocolAnalyzerGui.UserControlls.MenuControlls.UCSingleLine"
             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"
             mc:Ignorable="d"
             d:DesignHeight="100" d:DesignWidth="300">
    <Grid Background="#FF454545">

    <Grid.RowDefinitions>
        <RowDefinition Height="1*"></RowDefinition>
        <RowDefinition Height="1*"></RowDefinition>
    </Grid.RowDefinitions>

    <TextBlock x:Name="TBHeader" Foreground="White" HorizontalAlignment="Center" VerticalAlignment="Center" ></TextBlock>

    <Grid Grid.Row="1">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="1*"></ColumnDefinition>
            <ColumnDefinition Width="10"></ColumnDefinition>
            <ColumnDefinition Width="1*"></ColumnDefinition>
            <ColumnDefinition Width="10"></ColumnDefinition>
            <ColumnDefinition Width="1*"></ColumnDefinition>
            <ColumnDefinition Width="10"></ColumnDefinition>
            <ColumnDefinition Width="1*"></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <TextBlock x:Name="TBDatanTime" Grid.Column="0" Foreground="White" Text="{Binding DataAndTime }" ></TextBlock>
        <TextBlock x:Name="TBComPort" Grid.Column="2" Foreground="White"  Text="{Binding ComPort }" ></TextBlock>
        <TextBlock x:Name="TBTranslation" Grid.Column="4" Foreground="White" Text="{Binding Translation }" ></TextBlock>
        <TextBlock x:Name="TBDataBytesArray" Grid.Column="6" Foreground="White" Text="{Binding Header }" ></TextBlock>
    </Grid>
</Grid>
</UserControl>
</code>```

in the main window XAML:

```<code> <ScrollViewer Grid.Row="3" HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Auto">
        <ListBox x:Name="LBListBox">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel>
                        <myControlls:UCSingleLine x:Name="DataUserContoll"
 DataContext="{Binding DataForGui}"></myControlls:UCSingleLine>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>

        </ListBox>
    </ScrollViewer>
</code>```

the binding of the listbox Itemsource is inside this function:

```<code>        private void MI_SerialPortStart_Click(object sender, RoutedEventArgs e)
        {
            LBListBox.ItemsSource = DataForGui;
            _SerialPortTakeCare.Start();

        }
</code>```

also attaching my dataCode:

```<code>public class Data : INotifyPropertyChanged
{

        private string _DataAndTime;

        public string DataAndTime
        {
            get { return _DataAndTime; }
            set
            {
                _DataAndTime = value;
                OnPropertyChanged("DataAndTime");
            }
        }
        private string _ComPort;

        public string ComPort
        {
            get { return _ComPort; }
            set
            {
                _ComPort = value;
                OnPropertyChanged("ComPort");
            }
        }
        private string _Translation;

        public string Translation
        {
            get { return _Translation; }
            set
            {
                _Translation = value;
                OnPropertyChanged("Translation");
            }
        }
        private string _Header;

        public string Header
        {
            get { return _Header; }
            set
            {
                _Header = value;
                OnPropertyChanged("Header");
            }
        }
        private string _Data_ARR;

        public string Data_ARR
        {
            get { return _Data_ARR; }
            set
            {
                _Data_ARR = value;
                OnPropertyChanged("Data_ARR");

            }
        }

        public Data()
        {
            _ComPort = "";
            _Data_ARR = "";
            _DataAndTime = "";
            _Header = "";
            _Translation = "";
        }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
}
}
</code>```

答:
You just need to set the data context of your user control and then add the appropriate bindings.

In your main window, this line should look as follows:

```<code><local:UserControl1 DataContext="{Binding}" x:Name="DataUserContoll"/>
</code>```

And in the user control, the code should look more like this:

```<code><TextBlock x:Name="TBDatanTime" Grid.Column="0" Foreground="White" Text="{Binding TextField1}" />
<TextBlock x:Name="TBComPort" Grid.Column="2" Foreground="White" Text="{Binding TextField2}"/>
<TextBlock x:Name="TBTranslation" Grid.Column="4" Foreground="White" Text="{Binding TextField3}"/>
<TextBlock x:Name="TBDataBytesArray" Grid.Column="6" Foreground="White" Text="{Binding TextField4}"/>
</code>```

... and you should change the placeholder field names I have put in (e.g. "TextField1") to be the actual string properties of the objects inside your collection "DataForGui".

Body:
I am still new in MVVM and WPF
and I've looked at some examples however still did not found exactly the answers to my question.

I have a ListBox which each Item should add a new user control using ObservableCollection. In the user control I have an several Text blocks which I want to bound the texts of them to the same ObservableCollection which contain the Data.

However I am not sure how to bind the Text blocks to the ObservableCollection

Would be happy for a code example.

I'm also attaching my code, this is my userControl XAML:

<UserControl x:Class="ProtocolAnalyzerGui.UserControlls.MenuControlls.UCSingleLine"
             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"
             mc:Ignorable="d"
             d:DesignHeight="100" d:DesignWidth="300">
    <Grid Background="#FF454545">

    <Grid.RowDefinitions>
        <RowDefinition Height="1*"></RowDefinition>
        <RowDefinition Height="1*"></RowDefinition>
    </Grid.RowDefinitions>

    <TextBlock x:Name="TBHeader" Foreground="White" HorizontalAlignment="Center" VerticalAlignment="Center" ></TextBlock>

    <Grid Grid.Row="1">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="1*"></ColumnDefinition>
            <ColumnDefinition Width="10"></ColumnDefinition>
            <ColumnDefinition Width="1*"></ColumnDefinition>
            <ColumnDefinition Width="10"></ColumnDefinition>
            <ColumnDefinition Width="1*"></ColumnDefinition>
            <ColumnDefinition Width="10"></ColumnDefinition>
            <ColumnDefinition Width="1*"></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <TextBlock x:Name="TBDatanTime" Grid.Column="0" Foreground="White" Text="{Binding DataAndTime }" ></TextBlock>
        <TextBlock x:Name="TBComPort" Grid.Column="2" Foreground="White"  Text="{Binding ComPort }" ></TextBlock>
        <TextBlock x:Name="TBTranslation" Grid.Column="4" Foreground="White" Text="{Binding Translation }" ></TextBlock>
        <TextBlock x:Name="TBDataBytesArray" Grid.Column="6" Foreground="White" Text="{Binding Header }" ></TextBlock>
    </Grid>
</Grid>
</UserControl>

in the main window XAML:

 <ScrollViewer Grid.Row="3" HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Auto">
        <ListBox x:Name="LBListBox">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel>
                        <myControlls:UCSingleLine x:Name="DataUserContoll"
 DataContext="{Binding DataForGui}"></myControlls:UCSingleLine>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>

        </ListBox>
    </ScrollViewer>

the binding of the listbox Itemsource is inside this function:

        private void MI_SerialPortStart_Click(object sender, RoutedEventArgs e)
        {
            LBListBox.ItemsSource = DataForGui;
            _SerialPortTakeCare.Start();

        }

also attaching my dataCode:

public class Data : INotifyPropertyChanged
{

        private string _DataAndTime;

        public string DataAndTime
        {
            get { return _DataAndTime; }
            set
            {
                _DataAndTime = value;
                OnPropertyChanged("DataAndTime");
            }
        }
        private string _ComPort;

        public string ComPort
        {
            get { return _ComPort; }
            set
            {
                _ComPort = value;
                OnPropertyChanged("ComPort");
            }
        }
        private string _Translation;

        public string Translation
        {
            get { return _Translation; }
            set
            {
                _Translation = value;
                OnPropertyChanged("Translation");
            }
        }
        private string _Header;

        public string Header
        {
            get { return _Header; }
            set
            {
                _Header = value;
                OnPropertyChanged("Header");
            }
        }
        private string _Data_ARR;

        public string Data_ARR
        {
            get { return _Data_ARR; }
            set
            {
                _Data_ARR = value;
                OnPropertyChanged("Data_ARR");

            }
        }

        public Data()
        {
            _ComPort = "";
            _Data_ARR = "";
            _DataAndTime = "";
            _Header = "";
            _Translation = "";
        }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
}
}

Body:
You just need to set the data context of your user control and then add the appropriate bindings.

In your main window, this line should look as follows:

<local:UserControl1 DataContext="{Binding}" x:Name="DataUserContoll"/>

And in the user control, the code should look more like this:

<TextBlock x:Name="TBDatanTime" Grid.Column="0" Foreground="White" Text="{Binding TextField1}" />
<TextBlock x:Name="TBComPort" Grid.Column="2" Foreground="White" Text="{Binding TextField2}"/>
<TextBlock x:Name="TBTranslation" Grid.Column="4" Foreground="White" Text="{Binding TextField3}"/>
<TextBlock x:Name="TBDataBytesArray" Grid.Column="6" Foreground="White" Text="{Binding TextField4}"/>

... and you should change the placeholder field names I have put in (e.g. "TextField1") to be the actual string properties of the objects inside your collection "DataForGui".


问:
Stored Procedure to Sum values based on multiple conditions and a table join
I am trying to write a stored procedure for the following set of data:

Table A:

```<code>ReconID | service    | customer   | date
1       | Service A  | Customer A | July 2017
2       | Service A  | Customer A | July 2017
3       | Service A  | Customer B | July 2017
4       | Service A  | Customer B | Aug 2017
</code>```

Table B:

```<code>ReconID | actual_duration
1       | 10
2       | 20
3       | 5
4       | 2
</code>```

I would like to:

1)  Join the two tables,

2)  Group by: Service, Customer, and Month+Year and then sum the actual duration.

So, in this case my new table would have the following:

```<code>service    | customer | date | sum_actual_duration
Service A  | Customer A | July 2017  | 30    *(First two records were summed to make 30)*
Service A  | Customer B | July 2017  | 5
Service A  | Customer B | Aug 2017   | 2
</code>```

**Attempted but failed Stored procedure :( **

```<code>create PROCEDURE sum_ActualDuration
    @service varchar(50),
    @customer varchar(50),
    @date varchar(10),
    @sum_value int OUTPUT

SET @sum_value = (SELECT SUM( Z.actual_duration)
    FROM B
    LEFT OUTER JOIN A
    ON (A.ReconID = B.ReconID
WHERE A.service = @service AND A.customer = @customer AND A.date = @date
    )
AS
Begin
-- INSERT the new record
INSERT INTO sum_ActualDuration (service, customer, date, sum_value)
VALUES(@service, @customer, @date, @sum_value
    FROM B
    LEFT OUTER JOIN A
    ON (A.ReconID = B.ReconID)
    WHERE service = @service AND customer = @customer AND date = @date
)
end
</code>```

Any help is much appreciated!

--- UPDATED with answer ---

```<code>/* --- CREATE TABLE --- */

--DROP TABLE A;
--DROP TABLE B;

CREATE TABLE A(reconID integer, service text, customer text, date text);

INSERT INTO A VALUES(1, 'Service A', 'Customer A', 'Jul-17');
INSERT INTO A VALUES(2, 'Service A', 'Customer A', 'Jul-17');
INSERT INTO A VALUES(3, 'Service A', 'Customer B', 'Jul-17');
INSERT INTO A VALUES(4, 'Service A', 'Customer B', 'Aug-17');
COMMIT;

SELECT * FROM A;

CREATE TABLE B(reconID integer, actual_duration integer);

INSERT INTO B VALUES(1, '10');
INSERT INTO B VALUES(2, '20');
INSERT INTO B VALUES(3, '5');
INSERT INTO B VALUES(4, '2');
COMMIT;

SELECT * FROM B;

/* --- STORED PROCEDURE --- */

--CREATE PROC sp_actualDuration
--AS

--DROP TABLE sum_ActualDuration;
CREATE TABLE sum_ActualDuration(service text, customer text, date text, sum_value integer);

INSERT INTO sum_ActualDuration (service, customer, date, sum_value)
SELECT a.service, a.customer, a.date, SUM(b.actual_duration)
FROM A a LEFT OUTER JOIN
    B b
    ON a.ReconID = b.ReconID
    GROUP BY a.service, a.customer, a.date;
    --WHERE a.service="Service A" AND a.customer="Customer A" AND a.date="Jul-17";

--END

--EXEC sp_actualDuration

SELECT * FROM sum_ActualDuration;
</code>```

答:
You can use group by and sum as below:</p>

```<code>Select B.Service, B.Customer, B.[Date], Sum(A.Actual_duration)
FROM B
LEFT OUTER JOIN A
ON (A.ReconID = B.ReconID)
group by B.Service, B.Customer, B.[Date]
</code>```

Body:
I am trying to write a stored procedure for the following set of data:

Table A:

ReconID | service    | customer   | date
1       | Service A  | Customer A | July 2017
2       | Service A  | Customer A | July 2017
3       | Service A  | Customer B | July 2017
4       | Service A  | Customer B | Aug 2017

Table B:

ReconID | actual_duration
1       | 10
2       | 20
3       | 5
4       | 2

I would like to:

1)  Join the two tables,

2)  Group by: Service, Customer, and Month+Year and then sum the actual duration.

So, in this case my new table would have the following:

service    | customer | date | sum_actual_duration
Service A  | Customer A | July 2017  | 30    *(First two records were summed to make 30)*
Service A  | Customer B | July 2017  | 5
Service A  | Customer B | Aug 2017   | 2

**Attempted but failed Stored procedure :( **

create PROCEDURE sum_ActualDuration
    @service varchar(50),
    @customer varchar(50),
    @date varchar(10),
    @sum_value int OUTPUT

SET @sum_value = (SELECT SUM( Z.actual_duration)
    FROM B
    LEFT OUTER JOIN A
    ON (A.ReconID = B.ReconID
WHERE A.service = @service AND A.customer = @customer AND A.date = @date
    )
AS
Begin
-- INSERT the new record
INSERT INTO sum_ActualDuration (service, customer, date, sum_value)
VALUES(@service, @customer, @date, @sum_value
    FROM B
    LEFT OUTER JOIN A
    ON (A.ReconID = B.ReconID)
    WHERE service = @service AND customer = @customer AND date = @date
)
end

Any help is much appreciated!

--- UPDATED with answer ---

/* --- CREATE TABLE --- */

--DROP TABLE A;
--DROP TABLE B;

CREATE TABLE A(reconID integer, service text, customer text, date text);

INSERT INTO A VALUES(1, 'Service A', 'Customer A', 'Jul-17');
INSERT INTO A VALUES(2, 'Service A', 'Customer A', 'Jul-17');
INSERT INTO A VALUES(3, 'Service A', 'Customer B', 'Jul-17');
INSERT INTO A VALUES(4, 'Service A', 'Customer B', 'Aug-17');
COMMIT;

SELECT * FROM A;

CREATE TABLE B(reconID integer, actual_duration integer);

INSERT INTO B VALUES(1, '10');
INSERT INTO B VALUES(2, '20');
INSERT INTO B VALUES(3, '5');
INSERT INTO B VALUES(4, '2');
COMMIT;

SELECT * FROM B;

/* --- STORED PROCEDURE --- */

--CREATE PROC sp_actualDuration
--AS

--DROP TABLE sum_ActualDuration;
CREATE TABLE sum_ActualDuration(service text, customer text, date text, sum_value integer);

INSERT INTO sum_ActualDuration (service, customer, date, sum_value)
SELECT a.service, a.customer, a.date, SUM(b.actual_duration)
FROM A a LEFT OUTER JOIN
    B b
    ON a.ReconID = b.ReconID
    GROUP BY a.service, a.customer, a.date;
    --WHERE a.service="Service A" AND a.customer="Customer A" AND a.date="Jul-17";

--END

--EXEC sp_actualDuration

SELECT * FROM sum_ActualDuration;

Body:
You can use group by and sum as below:

Select B.Service, B.Customer, B.[Date], Sum(A.Actual_duration)
FROM B
LEFT OUTER JOIN A
ON (A.ReconID = B.ReconID)
group by B.Service, B.Customer, B.[Date]


答:
I think you can do this all in one statement, an INSERT . . . SELECT:

```<code>INSERT INTO sum_ActualDuration (service, customer, date, sum_value)
    SELECT a.service, a.customer, a.date, SUM(b.actual_duration)
    FROM A a LEFT OUTER JOIN
         B b
         ON a.ReconID = b.ReconID
    WHERE a.service = @service AND a.customer = @customer AND a.date = @date;
</code>```

You would seem to want the A table to be the first table for the outer join.  Also note that I qualified all the column names.

Title: Stored Procedure to Sum values based on multiple conditions and a table join

Body:
I think you can do this all in one statement, an INSERT . . . SELECT:

INSERT INTO sum_ActualDuration (service, customer, date, sum_value)
    SELECT a.service, a.customer, a.date, SUM(b.actual_duration)
    FROM A a LEFT OUTER JOIN
         B b
         ON a.ReconID = b.ReconID
    WHERE a.service = @service AND a.customer = @customer AND a.date = @date;

You would seem to want the A table to be the first table for the outer join.  Also note that I qualified all the column names.


问:
Events on elements in Relative Layout not firing
I am using Xamarin Forms and events on elements inside of a relative layout are not firing.  I tried to register them in code behind as well and still not firing.  I have -250 constraint on it because buttons were showing up on the bottom of the screen and it was the only way I could move them up.
Here is my xaml:</p>

```<code> <StackLayout Orientation="Vertical">
    <RelativeLayout>
        <Grid Margin="0,0,10,0"
              x:Name="grid"
              RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToParent, Property=Y, Factor=0, Constant=10}"
              RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToParent, Property=X, Factor=0, Constant=0}"
              >

        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="50*" />
            <ColumnDefinition Width="50*" />
        </Grid.ColumnDefinitions>

        <Label Grid.Column="0"
               Grid.Row="0"
                Text="IP Address"
               Margin="10,10,0,0"
               HorizontalOptions="StartAndExpand"/>
        <Entry Grid.Column="1"
               Grid.Row="0"
            x:Name="IPAddress"
            Placeholder="IP"
               WidthRequest="200"

                Margin="0,0,10,0"
            HorizontalOptions="EndAndExpand"/>
        <Label Grid.Column="0"
               Grid.Row="1"
                Text="Port"
               Margin="10,10,0,0"
               MinimumWidthRequest="100"
               HorizontalOptions="Start"/>
        <Entry Grid.Column="1"
               Grid.Row="1"
            x:Name="Port"
               Margin="0,0,10,0"
            Placeholder="Port"
                WidthRequest="200"
            HorizontalOptions="End"/>
        <Label Grid.Column="0"
               Grid.Row="2"
               Margin="10,10,0,0"
                Text="User Name"
               MinimumWidthRequest="100"
               HorizontalOptions="Start"/>
        <Entry Grid.Column="1"
               Grid.Row="2"
            x:Name="UserName"
               Margin="0,0,10,0"
                WidthRequest="200"
            Placeholder="User Name"
            HorizontalOptions="End"/>
        <Label Grid.Column="0"
               Grid.Row="3"
               Margin="10,10,0,0"
                Text="Password"
               MinimumWidthRequest="100"
               HorizontalOptions="Start"/>
        <Entry Grid.Column="1"
               Grid.Row="3"
            x:Name="Password"
               IsPassword="True"
               Margin="0,0,10,0"
                WidthRequest="200"
            Placeholder="Password"
            HorizontalOptions="End"/>

        </Grid>

    </RelativeLayout>
    <RelativeLayout
        IsEnabled="True">
        <Button x:Name="SaveBtn"
                IsEnabled="True"
                WidthRequest="100"
                RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToParent, Property=Y, Factor=0, Constant=-250}"
                RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToParent, Property=X, Factor=0, Constant=30}"
                Clicked="SaveBtn_Clicked"
                BorderColor="Gray"
                Text="Save"></Button>
        <Button x:Name="ClearFavorites"
                IsEnabled="True"
                WidthRequest="120"
                RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToParent, Property=Y, Factor=0, Constant=-250}"
                RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width, Factor=0.5, Constant=20}"
                Clicked="ClearFavorites_Clicked"
                BorderColor="Gray"
                Text="Clear Favorites"></Button>
    </RelativeLayout>
</StackLayout>
</code>```

答:
After discussion on chat this seems to work</p>

```<code><StackLayout Orientation="Vertical">
<RelativeLayout>
<Grid Margin="0,0,10,0"
x:Name="grid"
RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToParent, Property=Y, Factor=0, Constant=10}"
RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToParent, Property=X, Factor=0, Constant=0}"
>

<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50*" />
<ColumnDefinition Width="50*" />
</Grid.ColumnDefinitions>

<Label Grid.Column="0"
Grid.Row="0"
Text="IP Address"
Margin="10,10,0,0"
HorizontalOptions="StartAndExpand"/>
<Entry Grid.Column="1"
Grid.Row="0"
x:Name="IPAddress"
Placeholder="IP"
WidthRequest="200"

Margin="0,0,10,0"
HorizontalOptions="EndAndExpand"/>
<Label Grid.Column="0"
Grid.Row="1"
Text="Port"
Margin="10,10,0,0"
MinimumWidthRequest="100"
HorizontalOptions="Start"/>
<Entry Grid.Column="1"
Grid.Row="1"
x:Name="Port"
Margin="0,0,10,0"
Placeholder="Port"
WidthRequest="200"
HorizontalOptions="End"/>
<Label Grid.Column="0"
Grid.Row="2"
Margin="10,10,0,0"
Text="User Name"
MinimumWidthRequest="100"
HorizontalOptions="Start"/>
<Entry Grid.Column="1"
Grid.Row="2"
x:Name="UserName"
Margin="0,0,10,0"
WidthRequest="200"
Placeholder="User Name"
HorizontalOptions="End"/>
<Label Grid.Column="0"
Grid.Row="3"
Margin="10,10,0,0"
Text="Password"
MinimumWidthRequest="100"
HorizontalOptions="Start"/>
<Entry Grid.Column="1"
Grid.Row="3"
x:Name="Password"
IsPassword="True"
Margin="0,0,10,0"
WidthRequest="200"
Placeholder="Password"
HorizontalOptions="End"/>

</Grid>

</RelativeLayout>
<RelativeLayout
IsEnabled="True">
<Button x:Name="SaveBtn"
IsEnabled="True"
WidthRequest="100"
RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToParent, Property=Y, Factor=0, Constant=50}"
RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToParent, Property=X, Factor=0, Constant=30}"
Clicked="SaveBtn_Clicked"
BorderColor="Gray"
Text="Save"></Button>
<Button x:Name="ClearFavorites"
IsEnabled="True"
WidthRequest="120"
RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToParent, Property=Y, Factor=0, Constant=50}"
RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width, Factor=0.5, Constant=20}"
Clicked="ClearFavorites_Clicked"
BorderColor="Gray"
Text="Clear Favorites"></Button>
</RelativeLayout>
</StackLayout>
</code>```

Body:
I am using Xamarin Forms and events on elements inside of a relative layout are not firing.  I tried to register them in code behind as well and still not firing.  I have -250 constraint on it because buttons were showing up on the bottom of the screen and it was the only way I could move them up.
Here is my xaml:

 <StackLayout Orientation="Vertical">
    <RelativeLayout>
        <Grid Margin="0,0,10,0"
              x:Name="grid"
              RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToParent, Property=Y, Factor=0, Constant=10}"
              RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToParent, Property=X, Factor=0, Constant=0}"
              >

        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="50*" />
            <ColumnDefinition Width="50*" />
        </Grid.ColumnDefinitions>

        <Entry Grid.Column="1"
               Grid.Row="0"
            x:Name="IPAddress"
            Placeholder="IP"
               WidthRequest="200"

                Margin="0,0,10,0"
            HorizontalOptions="EndAndExpand"/>

        <Entry Grid.Column="1"
               Grid.Row="1"
            x:Name="Port"
               Margin="0,0,10,0"
            Placeholder="Port"
                WidthRequest="200"
            HorizontalOptions="End"/>

        <Entry Grid.Column="1"
               Grid.Row="2"
            x:Name="UserName"
               Margin="0,0,10,0"
                WidthRequest="200"
            Placeholder="User Name"
            HorizontalOptions="End"/>

        <Entry Grid.Column="1"
               Grid.Row="3"
            x:Name="Password"
               IsPassword="True"
               Margin="0,0,10,0"
                WidthRequest="200"
            Placeholder="Password"
            HorizontalOptions="End"/>

        </Grid>

    </RelativeLayout>
    <RelativeLayout
        IsEnabled="True">
        <Button x:Name="SaveBtn"
                IsEnabled="True"
                WidthRequest="100"
                RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToParent, Property=Y, Factor=0, Constant=-250}"
                RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToParent, Property=X, Factor=0, Constant=30}"
                Clicked="SaveBtn_Clicked"
                BorderColor="Gray"
                Text="Save"></Button>
        <Button x:Name="ClearFavorites"
                IsEnabled="True"
                WidthRequest="120"
                RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToParent, Property=Y, Factor=0, Constant=-250}"
                RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width, Factor=0.5, Constant=20}"
                Clicked="ClearFavorites_Clicked"
                BorderColor="Gray"
                Text="Clear Favorites"></Button>
    </RelativeLayout>
</StackLayout>

Body:
After discussion on chat this seems to work

<StackLayout Orientation="Vertical">
<RelativeLayout>
<Grid Margin="0,0,10,0"
x:Name="grid"
RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToParent, Property=Y, Factor=0, Constant=10}"
RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToParent, Property=X, Factor=0, Constant=0}"
>

<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50*" />
<ColumnDefinition Width="50*" />
</Grid.ColumnDefinitions>

<Label Grid.Column="0"
Grid.Row="0"
Text="IP Address"
Margin="10,10,0,0"
HorizontalOptions="StartAndExpand"/>
<Entry Grid.Column="1"
Grid.Row="0"
x:Name="IPAddress"
Placeholder="IP"
WidthRequest="200"

Margin="0,0,10,0"
HorizontalOptions="EndAndExpand"/>
<Label Grid.Column="0"
Grid.Row="1"
Text="Port"
Margin="10,10,0,0"
MinimumWidthRequest="100"
HorizontalOptions="Start"/>
<Entry Grid.Column="1"
Grid.Row="1"
x:Name="Port"
Margin="0,0,10,0"
Placeholder="Port"
WidthRequest="200"
HorizontalOptions="End"/>
<Label Grid.Column="0"
Grid.Row="2"
Margin="10,10,0,0"
Text="User Name"
MinimumWidthRequest="100"
HorizontalOptions="Start"/>
<Entry Grid.Column="1"
Grid.Row="2"
x:Name="UserName"
Margin="0,0,10,0"
WidthRequest="200"
Placeholder="User Name"
HorizontalOptions="End"/>
<Label Grid.Column="0"
Grid.Row="3"
Margin="10,10,0,0"
Text="Password"
MinimumWidthRequest="100"
HorizontalOptions="Start"/>
<Entry Grid.Column="1"
Grid.Row="3"
x:Name="Password"
IsPassword="True"
Margin="0,0,10,0"
WidthRequest="200"
Placeholder="Password"
HorizontalOptions="End"/>

</Grid>

</RelativeLayout>
<RelativeLayout
IsEnabled="True">
<Button x:Name="SaveBtn"
IsEnabled="True"
WidthRequest="100"
RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToParent, Property=Y, Factor=0, Constant=50}"
RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToParent, Property=X, Factor=0, Constant=30}"
Clicked="SaveBtn_Clicked"
BorderColor="Gray"
Text="Save"></Button>
<Button x:Name="ClearFavorites"
IsEnabled="True"
WidthRequest="120"
RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToParent, Property=Y, Factor=0, Constant=50}"
RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width, Factor=0.5, Constant=20}"
Clicked="ClearFavorites_Clicked"
BorderColor="Gray"
Text="Clear Favorites"></Button>
</RelativeLayout>
</StackLayout>


问:
C: read in more than one file
Hey guys using POSIX API system calls read, write, open, etc. I can open, read, write to a file  and copy its contents to an output file. How would I go about copying more than one file to an output file using related system calls only?

I currently have:

```<code>filein = open(argv[1],O_RDONLY,0);
</code>```

to open one file.(which is argv1 but I'd like to know how to do argv2 and argv3 etc.)

I tried :

```<code>j=0;
filein = open(argv[j],O_RDONLY,0);
</code>```

but that prints out contents of argv0 into my outputfile.

I am stuck on the next stage to do more than one file. (I also have an EOF loop so after 1 file it exits-How would I make this continue for the next file).

Please could you help me with how to approach the next stage? Thanks.

答:
Use a loop to read all the files. Start at 1 to skip the current executing process which is located at argv[0].</p>

```<code>for(int i = 1; i < argc; ++i)
{
    int filein = open(argv[i],O_RDONLY,0);
    // ... process file
    close(filein)
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: C: read in more than one file

Body:
Hey guys using POSIX API system calls read, write, open, etc. I can open, read, write to a file  and copy its contents to an output file. How would I go about copying more than one file to an output file using related system calls only?

I currently have:

filein = open(argv[1],O_RDONLY,0);

to open one file.(which is argv1 but I'd like to know how to do argv2 and argv3 etc.)

I tried :

j=0;
filein = open(argv[j],O_RDONLY,0);

but that prints out contents of argv0 into my outputfile.

I am stuck on the next stage to do more than one file. (I also have an EOF loop so after 1 file it exits-How would I make this continue for the next file).

Please could you help me with how to approach the next stage? Thanks.

Body:
Use a loop to read all the files. Start at 1 to skip the current executing process which is located at argv[0].

for(int i = 1; i < argc; ++i)
{
    int filein = open(argv[i],O_RDONLY,0);
    // ... process file
    close(filein)
}


问:
How to update MPNowPlayingInfoCenter in Swift?
In objective c, I've been using code like this to update MPNowPlayingInfoCenter:

```<code>[[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:
    @{ MPMediaItemPropertyArtist : @"Artist!",
        MPMediaItemPropertyTitle : @"Title! }];
</code>```

But in Swift, it doesn't seem like the function "setNowPlayingInfo" is recognized:

```<code>MPNowPlayingInfoCenter.defaultCenter()....  // Can't identify 'setNowPlayingInfo()'
</code>```

Is there anything I'm missing?

答:
Previous answer by @Jack no longer works as is, and needs some modifications.

Swift 3 compiler complains about 2 things.

String is not directly convertible to AnyObject, and so the two dictionary entry values must be casted from String to AnyObject.

defaultCenter() has been renamed to default().

so a viable code will look like this:

```<code>MPNowPlayingInfoCenter.default().nowPlayingInfo = [MPMediaItemPropertyArtist : "Artist!" as AnyObject,  MPMediaItemPropertyTitle : "Title!" as AnyObject]
</code>```

Body:
In objective c, I've been using code like this to update MPNowPlayingInfoCenter:

[[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:
    @{ MPMediaItemPropertyArtist : @"Artist!",
        MPMediaItemPropertyTitle : @"Title! }];

But in Swift, it doesn't seem like the function "setNowPlayingInfo" is recognized:

MPNowPlayingInfoCenter.defaultCenter()....  // Can't identify 'setNowPlayingInfo()'

Is there anything I'm missing?

Body:
Previous answer by @Jack no longer works as is, and needs some modifications.

Swift 3 compiler complains about 2 things.

String is not directly convertible to AnyObject, and so the two dictionary entry values must be casted from String to AnyObject.

defaultCenter() has been renamed to default().

so a viable code will look like this:

MPNowPlayingInfoCenter.default().nowPlayingInfo = [MPMediaItemPropertyArtist : "Artist!" as AnyObject,  MPMediaItemPropertyTitle : "Title!" as AnyObject]


问:
Getting elements from XML file in Perl
I have a file on a server that I want to parse in Perl. I've tried it with XML:Simple and XML:LibXML and I can't get the xml elements in both cases.

This is my .xml file:

```<code><csixml version="1.0">
    <head>
    <details>
        <name-link>linkName</name-link>
        <table>links</table>
        <model>XS1-556</model>
    </details>
        <fields>
            <field name="name1" />
            <field name="name2"/>
            <field name="name3"/>
            <field name="name4"/>
            <field name="name5"/>
            <field name="name6" />
            <field name="name7"/>
            <field name="name8"/>
            <field name="name9"/>
            <field name="name10"/>
            <field name="name11"/>
            <field name="name12x"/>
            <field name="name13"/>
            <field name="name14"/>
            <field name="name15"/>
            <field name="name16"/>
            <field name="name17"/>
        </fields>
    </head>
    <data>
        <record time="2017/06/01 00:00:00" no="742">
        <v1>14.85</v1>
        <v2>34.1</v2>
        <v3>600</v3>
        <v4>0</v4>
        <v5>0</v5>
        <v6>0</v6>
        <v7>0</v7>
        <v8>11.22</v8>
        <v9>0.41</v9>
        <v10>215</v10>
        <v11>7.043</v11>
        <v12>1.325</v12>
        <v13>2017-05-31T23:47:14</v13>
        <v14>202.3</v14>
        <v15>0</v15>
        <v16>42.85</v16>
        <v17>12.25</v17>
        </record>
        </data>
    </csixml>
</code>```

And this is the code :

```<code>my $parser = new XML::Simple;
$data = $parser->XMLin( get( $url ));

#print Dumper($data);

print $data->{'r'}[0]{'v1'};
print $data->{'r'}[1]{'v2'};
</code>```

When I try it with XML:LibXML it gives me an error that says:

```<code>Start tag expected, '<' not found
</code>```

答:
XML::Simple is flaky and should not be used (even the author agrees) but, having said that, it's a relatively simple fix to get your program working as expected.

You're walking your data structure incorrectly. You need to take a closer look at your Data:Dumper output. Your $data variable is equivalent to the top-level <csixml> tag. Everything else is hashes within that. So, to get to the piece of the data structure you want, you need:

```<code>print $data->{data}{r}{v1}
print $data->{data}{r}{v2}
</code>```

I also see that you're using the "indirect object notation" (new XML::Simple) to create your parser object. This usually works fine, but when it doesn't you'll waste days trying to work out what has gone wrong. Instead, please use the standard syntax - XML::Simple->new.

Update: Here's the code I was using:

```<code>#!/usr/bin/perl

use strict;
use warnings;

use Path::Tiny;
use XML::Simple;
use Data::Dumper;

my $file = 'test.xml';
my $xml  = path($file)->slurp;

my $parser = new XML::Simple;
my $data = $parser->XMLin($xml);

#print Dumper($data);

print $data->{data}{'r'}{'v1'};
print $data->{data}{'r'}{'v2'};
</code>```

Title: Getting elements from XML file in Perl

Body:
I have a file on a server that I want to parse in Perl. I've tried it with XML:Simple and XML:LibXML and I can't get the xml elements in both cases.

This is my .xml file:

<csixml version="1.0">

        <name-link>linkName</name-link>

links

        <model>XS1-556</model>

        <fields>
            <field name="name1" />
            <field name="name2"/>
            <field name="name3"/>
            <field name="name4"/>
            <field name="name5"/>
            <field name="name6" />
            <field name="name7"/>
            <field name="name8"/>
            <field name="name9"/>
            <field name="name10"/>
            <field name="name11"/>
            <field name="name12x"/>
            <field name="name13"/>
            <field name="name14"/>
            <field name="name15"/>
            <field name="name16"/>
            <field name="name17"/>
        </fields>

    <data>
        <record time="2017/06/01 00:00:00" no="742">
        <v1>14.85</v1>
        <v2>34.1</v2>
        <v3>600</v3>
        <v4>0</v4>
        <v5>0</v5>
        <v6>0</v6>
        <v7>0</v7>
        <v8>11.22</v8>
        <v9>0.41</v9>
        <v10>215</v10>
        <v11>7.043</v11>
        <v12>1.325</v12>
        <v13>2017-05-31T23:47:14</v13>
        <v14>202.3</v14>
        <v15>0</v15>
        <v16>42.85</v16>
        <v17>12.25</v17>
        </record>
        </data>
    </csixml>

And this is the code :

my $parser = new XML::Simple;
$data = $parser->XMLin( get( $url ));

#print Dumper($data);

print $data->{'r'}[0]{'v1'};
print $data->{'r'}[1]{'v2'};

When I try it with XML:LibXML it gives me an error that says:

Start tag expected, '<' not found

Body:
XML::Simple is flaky and should not be used (even the author agrees) but, having said that, it's a relatively simple fix to get your program working as expected.

You're walking your data structure incorrectly. You need to take a closer look at your Data:Dumper output. Your $data variable is equivalent to the top-level <csixml> tag. Everything else is hashes within that. So, to get to the piece of the data structure you want, you need:

print $data->{data}{r}{v1}
print $data->{data}{r}{v2}

I also see that you're using the "indirect object notation" (new XML::Simple) to create your parser object. This usually works fine, but when it doesn't you'll waste days trying to work out what has gone wrong. Instead, please use the standard syntax - XML::Simple->new.

Update: Here's the code I was using:

#!/usr/bin/perl

use strict;
use warnings;

use Path::Tiny;
use XML::Simple;
use Data::Dumper;

my $file = 'test.xml';
my $xml  = path($file)->slurp;

my $parser = new XML::Simple;
my $data = $parser->XMLin($xml);

#print Dumper($data);

print $data->{data}{'r'}{'v1'};
print $data->{data}{'r'}{'v2'};


问:
Jquery show hide issue on server
I am creating a simple show/hide all toggle button for my images in my instagram feed. It works fine in the fiddle but when I put the same code on my server nothing works with no error. Can anyone help me troubleshoot why this isn't working.

Here is the HTML

```<code><div class="btn btn-success toggleAll">
    Show All/Hide All
</div>
</code>```

Here is the Javascript

```<code>$('.toggleAll').on('click',function(){
    $('.pp, .coat, .heart-wrap, .comment-wrap, .check-wrap, .grip .btn').slideToggle('fast');
});
</code>```

and here is the jsfiddle that works

https://jsfiddle.net/galnova/ua0ojhhe/5/

Here is my site where it doesn't work

http://galnova.com

Any help is welcome guys.

答:
Try </p>

```<code>$(document).on('click', '.toggleAll', function(){
    $('.pp, .coat, .heart-wrap, .comment-wrap, .check-wrap, .grip .btn').slideToggle('fast');
});
</code>```

Title: Jquery show hide issue on server

Body:
I am creating a simple show/hide all toggle button for my images in my instagram feed. It works fine in the fiddle but when I put the same code on my server nothing works with no error. Can anyone help me troubleshoot why this isn't working.

Here is the HTML

    Show All/Hide All

Here is the Javascript

$('.toggleAll').on('click',function(){
    $('.pp, .coat, .heart-wrap, .comment-wrap, .check-wrap, .grip .btn').slideToggle('fast');
});

and here is the jsfiddle that works

https://jsfiddle.net/galnova/ua0ojhhe/5/

Here is my site where it doesn't work

http://galnova.com

Any help is welcome guys.

Body:
Try

$(document).on('click', '.toggleAll', function(){
    $('.pp, .coat, .heart-wrap, .comment-wrap, .check-wrap, .grip .btn').slideToggle('fast');
});


问:
snakemake - output one only file from multiple input files in one rule
I'm using snakemake for the first time in order to build a basic pipeline using cutadapt, bwa and GATK (trimming ; mapping ; calling). I would like to run this pipeline on every fastq file contained in a directory, without having to specify their name or whatever in the snakefile or in the config file. I would like to succeed in doing this.

The first two steps (cutadapt and bwa / trimming and mapping) are running fine, but I'm encountering some problems with GATK.

First, I have to generate g.vcf files from bam files. I'm doing this using these rules:

configfile: "config.yaml"

import os
import glob

rule all:
    input:
        "merge_calling.g.vcf"

rule cutadapt:
    input:
        read="data/Raw_reads/{sample}_R1_{run}.fastq.gz",
        read2="data/Raw_reads/{sample}_R2_{run}.fastq.gz"
    output:
        R1=temp("trimmed_reads/{sample}_R1_{run}.fastq.gz"),
        R2=temp("trimmed_reads/{sample}_R2_{run}.fastq.gz")
    threads:
        10
    shell:
        "cutadapt -q {config[Cutadapt][Quality_value]} -m {config[Cutadapt][min_length]} -a {config[Cutadapt][forward_adapter]} -A  {config[Cutadapt][reverse_adapter]} -o {output.R1} -p '{output.R2}' {input.read} {input.read2}"

rule bwa_map:
    input:
        genome="data/genome.fasta",
        read=expand("trimmed_reads/{{sample}}_{pair}_{{run}}.fastq.gz", pair=["R1", "R2"])
    output:
        temp("mapped_bam/{sample}_{run}.bam")
    threads:
        10
    params:
        rg="@RG\\tID:{sample}\\tPL:ILLUMINA\\tSM:{sample}"
    shell:
        "bwa mem -t 2 -R '{params.rg}' {input.genome} {input.read} | samtools view -Sb - > {output}"

rule picard_sort:
    input:
        "mapped_bam/{sample}.bam"
    output:
        "sorted_reads/{sample}.bam"
    shell:
        "java -Xmx4g -jar /home/alexandre/picard-tools/picard.jar SortSam I={input} O={output} SO=coordinate VALIDATION_STRINGENCY=SILENT"

rule picard_rmdup:
    input:
        bam="sorted_reads/{sample}.bam"
    output:
        "rmduped_reads/{sample}.bam",
        "picard_stats/{sample}.bam"
    params:
        reads="rmduped_reads/{sample}.bam",
        stats="picard_stats/{sample}.bam",
    shell:
        "java -jar -Xmx2g /home/alexandre/picard-tools/picard.jar MarkDuplicates "
        "I={input.bam} "
        "O='{params.reads}' "
        "VALIDATION_STRINGENCY=SILENT "
        "MAX_FILE_HANDLES_FOR_READ_ENDS_MAP=1000 "
        "REMOVE_DUPLICATES=TRUE "
        "M='{params.stats}'"

rule samtools_index:
    input:
        "rmduped_reads/{sample}.bam"
    output:
        "rmduped_reads/{sample}.bam.bai"
    shell:
        "samtools index {input}"

rule GATK_raw_calling:
    input:
        bam="rmduped_reads/{sample}.bam",
        bai="rmduped_reads/{sample}.bam.bai",
        genome="data/genome.fasta"
    output:
        "Raw_calling/{sample}.g.vcf",
    shell:
        "java -Xmx4g -jar /home/alexandre/GenomeAnalysisTK-3.7/GenomeAnalysisTK.jar -ploidy 2 --emitRefConfidence GVCF -T HaplotypeCaller -R {input.genome} -I {input.bam} --genotyping_mode DISCOVERY -o {output}"
```

<p>These rules work fine. For example, if I have the files :
    Cla001d_S281_L001_R1_001.fastq.gz
    Cla001d_S281_L001_R2_001.fastq.gz</p>

<p>I can create one bam file (<code>Cla001d_S281_L001_001.bam</code>) and from that bam file create a GVCF file (<code>Cla001d_S281_L001_001.g.vcf</code>). I have a lot of sample like this one, and I need to create one GVCF file for each, and then merge these GVCF files into one file. The problem is that I'm unable to give the list of the file to merge to the following rule:</p>

<pre class="lang-python prettyprint-override"><code>rule GATK_merge:
    input:
        ???
    output:
        "merge_calling.g.vcf"
    shell:
        "java -Xmx4g -jar /home/alexandre/GenomeAnalysisTK-3.7/GenomeAnalysisTK.jar "
        "-T CombineGVCFs "
        "-R data/genome.fasta "
        "--variant {input} "
        "-o {output}"
</code>```

I tried several things in order to do that, but cannot succeed. The problem is the link between the two rules (GATK_raw_calling and GATK_merge that is supposed to merge the output of GATK_raw_calling). I can't output one single file if I'm specifying the output of GATK_raw_calling as the input of the following rule (Wildcards in input files cannot be determined from output files), and  I'm unable to make a link between the two rules if I'm not specifying these files as an input...

Is there a way to succeed in doing that? The difficulty is that I'm not defining a list of names or whatever, I think.

Thanks you in advance for your help.

答:
You can achieve this by using a python function as an input for your rule, as described in the snakemake documentation here.

Could look like this for example:

```<code># Define input files
def gatk_inputs(wildcards):
    files = expand("Raw_calling/{sample}.g.vcf", sample=<samples list>)
    return files

# Rule
rule gatk:
    input: gatk_inputs
    output: <output file name>
    run: ...
</code>```

Hope this helps.

Body:
I'm using snakemake for the first time in order to build a basic pipeline using cutadapt, bwa and GATK (trimming ; mapping ; calling). I would like to run this pipeline on every fastq file contained in a directory, without having to specify their name or whatever in the snakefile or in the config file. I would like to succeed in doing this.

The first two steps (cutadapt and bwa / trimming and mapping) are running fine, but I'm encountering some problems with GATK.

First, I have to generate g.vcf files from bam files. I'm doing this using these rules:

configfile: "config.yaml"

import os
import glob

rule all:
    input:
        "merge_calling.g.vcf"

rule cutadapt:
    input:
        read="data/Raw_reads/{sample}_R1_{run}.fastq.gz",
        read2="data/Raw_reads/{sample}_R2_{run}.fastq.gz"
    output:
        R1=temp("trimmed_reads/{sample}_R1_{run}.fastq.gz"),
        R2=temp("trimmed_reads/{sample}_R2_{run}.fastq.gz")
    threads:
        10
    shell:
        "cutadapt -q {config[Cutadapt][Quality_value]} -m {config[Cutadapt][min_length]} -a {config[Cutadapt][forward_adapter]} -A  {config[Cutadapt][reverse_adapter]} -o {output.R1} -p '{output.R2}' {input.read} {input.read2}"

rule bwa_map:
    input:
        genome="data/genome.fasta",
        read=expand("trimmed_reads/{{sample}}_{pair}_{{run}}.fastq.gz", pair=["R1", "R2"])
    output:
        temp("mapped_bam/{sample}_{run}.bam")
    threads:
        10
    params:
        rg="@RG\\tID:{sample}\\tPL:ILLUMINA\\tSM:{sample}"
    shell:
        "bwa mem -t 2 -R '{params.rg}' {input.genome} {input.read} | samtools view -Sb - > {output}"

rule picard_sort:
    input:
        "mapped_bam/{sample}.bam"
    output:
        "sorted_reads/{sample}.bam"
    shell:
        "java -Xmx4g -jar /home/alexandre/picard-tools/picard.jar SortSam I={input} O={output} SO=coordinate VALIDATION_STRINGENCY=SILENT"

rule picard_rmdup:
    input:
        bam="sorted_reads/{sample}.bam"
    output:
        "rmduped_reads/{sample}.bam",
        "picard_stats/{sample}.bam"
    params:
        reads="rmduped_reads/{sample}.bam",
        stats="picard_stats/{sample}.bam",
    shell:
        "java -jar -Xmx2g /home/alexandre/picard-tools/picard.jar MarkDuplicates "
        "I={input.bam} "
        "O='{params.reads}' "
        "VALIDATION_STRINGENCY=SILENT "
        "MAX_FILE_HANDLES_FOR_READ_ENDS_MAP=1000 "
        "REMOVE_DUPLICATES=TRUE "
        "M='{params.stats}'"

rule samtools_index:
    input:
        "rmduped_reads/{sample}.bam"
    output:
        "rmduped_reads/{sample}.bam.bai"
    shell:
        "samtools index {input}"

rule GATK_raw_calling:
    input:
        bam="rmduped_reads/{sample}.bam",
        bai="rmduped_reads/{sample}.bam.bai",
        genome="data/genome.fasta"
    output:
        "Raw_calling/{sample}.g.vcf",
    shell:
        "java -Xmx4g -jar /home/alexandre/GenomeAnalysisTK-3.7/GenomeAnalysisTK.jar -ploidy 2 --emitRefConfidence GVCF -T HaplotypeCaller -R {input.genome} -I {input.bam} --genotyping_mode DISCOVERY -o {output}"

These rules work fine. For example, if I have the files :
    Cla001d_S281_L001_R1_001.fastq.gz
    Cla001d_S281_L001_R2_001.fastq.gz

I can create one bam file (Cla001d_S281_L001_001.bam) and from that bam file create a GVCF file (Cla001d_S281_L001_001.g.vcf). I have a lot of sample like this one, and I need to create one GVCF file for each, and then merge these GVCF files into one file. The problem is that I'm unable to give the list of the file to merge to the following rule:

rule GATK_merge:
    input:
        ???
    output:
        "merge_calling.g.vcf"
    shell:
        "java -Xmx4g -jar /home/alexandre/GenomeAnalysisTK-3.7/GenomeAnalysisTK.jar "
        "-T CombineGVCFs "
        "-R data/genome.fasta "
        "--variant {input} "
        "-o {output}"

I tried several things in order to do that, but cannot succeed. The problem is the link between the two rules (GATK_raw_calling and GATK_merge that is supposed to merge the output of GATK_raw_calling). I can't output one single file if I'm specifying the output of GATK_raw_calling as the input of the following rule (Wildcards in input files cannot be determined from output files), and  I'm unable to make a link between the two rules if I'm not specifying these files as an input...

Is there a way to succeed in doing that? The difficulty is that I'm not defining a list of names or whatever, I think.

Thanks you in advance for your help.

Body:
You can achieve this by using a python function as an input for your rule, as described in the snakemake documentation here.

Could look like this for example:

# Define input files
def gatk_inputs(wildcards):
    files = expand("Raw_calling/{sample}.g.vcf", sample=<samples list>)
    return files

# Rule
rule gatk:
    input: gatk_inputs
    output: <output file name>
    run: ...

Hope this helps.


问:
Can I see the relations as well in the Class Diagram of VS?
Is it possible to see the relations in the class diagrams as well as the inheritance?

How?

Thanks!

答: Yes, if you have a property that is a reference to another class (in the diagram), righ-click that property and select "Show as Association" (or a name like that).</p>


问:
Style not being applied to WPF button on mouse over
I have defined a Style for my button:

```<code><Style x:Key="MyStyle" TargetType="{x:Type Button}">

    <Setter Property="BorderBrush" Value="Transparent"/>
    <Setter Property="BorderThickness" Value="0 0 0 3"/>

    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="BorderBrush" Value="Orange" />
        </Trigger>
        <Trigger Property="IsPressed" Value="True">
            <Setter Property="BorderBrush" Value="Red" />
        </Trigger>
    </Style.Triggers>

</Style>
</code>```

Now, I apply it to the WPF button as below:

```<code><Button>
    <Button.Style>
        <Style TargetType="Button" BasedOn="{StaticResource MyStyle}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate>
                        <StackPanel Orientation="Vertical">
                            <Image Height="20" Width="20" Stretch="UniformToFill" Source="./Resources/Add.png"/>
                            <Label HorizontalAlignment="Center">Add</Label>
                        </StackPanel>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <Trigger Property="IsPressed" Value="True">
                    <Setter Property="BorderBrush" Value="Green" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>
</code>```

This shows a button with an image and a label under the image.
Also, on mouse over, the button border at the bottom is shown with Orange color and on mouse pressed it change its bottom border to Green color (note that initial color is overrided. I have another button which I want to show its bottom border red and not green on mouse pressed).

My problem is that bottom border for button is not being shown orange on mouse over.

UPDATE:

As Mishka said I forgot the border... see now:

```<code><Button>
    <Button.Style>
        <Style TargetType="Button" BasedOn="{StaticResource MyStyle}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate>
                       <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}">
                        <StackPanel Orientation="Vertical">
                            <Image Height="20" Width="20" Stretch="UniformToFill" Source="./Resources/Add.png"/>
                            <Label HorizontalAlignment="Center">Add</Label>
                        </StackPanel>
                      </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <Trigger Property="IsPressed" Value="True">
                    <Setter Property="BorderBrush" Value="Green" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>
</code>```

答:
No object(Like 'Border') exist in your ControlTemplate to receive that BorderBrush's value.

You need to wrap you controls with a Border and have its value like BorderBrush and BorderThickness, TemplateBinding to the properties on the Button:

```<code><Border BorderBrush="{TemplateBinding BorderBrush}">
</Border>
</code>```

Body:
I have defined a Style for my button:

</Style>

Now, I apply it to the WPF button as below:

<Button>
    <Button.Style>

        </Style>
    </Button.Style>
</Button>

This shows a button with an image and a label under the image.
Also, on mouse over, the button border at the bottom is shown with Orange color and on mouse pressed it change its bottom border to Green color (note that initial color is overrided. I have another button which I want to show its bottom border red and not green on mouse pressed).

My problem is that bottom border for button is not being shown orange on mouse over.

UPDATE:

As Mishka said I forgot the border... see now:

<Button>
    <Button.Style>

        </Style>
    </Button.Style>
</Button>

Body:
No object(Like 'Border') exist in your ControlTemplate to receive that BorderBrush's value.

You need to wrap you controls with a Border and have its value like BorderBrush and BorderThickness, TemplateBinding to the properties on the Button:

<Border BorderBrush="{TemplateBinding BorderBrush}">
</Border>


问:
Using meteor HTTP to connect to ethereum node
I am trying to copy the following curl command using meteor HTTP

curl -X POST --data '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":83}' http://localhost:8545

The command is from here

This is what I tried:

HTTP.call('POST',"http://localhost:8545",{data:{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":83}},function(res,error){console.log(res)})

but it returns null. The curl command gives {"jsonrpc":"2.0","id":83,"result":"(the blocknumber)"}

答:
You have to swap error and res params.</p>

```<code>HTTP.call('POST',"http://localhost:8545",{data:{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":83}},function(error, res){console.log(res)})
</code>```

Body:
You have to swap error and res params.

HTTP.call('POST',"http://localhost:8545",{data:{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":83}},function(error, res){console.log(res)})


问:
Default images in template level in Weebly
Is there any way to set default image sources in the 'header type html' in order for page editors to see an image in the page edit mode?

Because when I add an image as the following

```<code><div class="text-center">
  {sec-two-image1:image global="false"}
</div>
</code>```

What I see in the page edit is only an image icon which does not make a good sense for the user.
See : http://prntscr.com/fqxmzf

My purpse is to present a proper view for him to understand how it will look like after publishing? But I guess the images given in the template level ( I mean the elements provided as a custom html ) are not rendered properly.
Any way to succeed it?

答:
Because the image that you are seeing is HTML, see screenshot, you wouldn't be able to change it with CSS.. AND you might not be able to do it with JavaScript or Jquery either.

But that being said, you can certainly change the white background area using CSS. You would do something like;

```<code>#icontent .weebly-image-area-placeholder {
    background: url(background.png) no-repeat;
    background-position: 50% 0;
    box-shadow: inset 0px 0px 15px 0px #000000;
    cursor: pointer;
}
</code>```

Note that you really only need to use background: url(background.png) no-repeat; in the CSS noted above, but I have added all of the CSS for that placeholder so you can see that you can change the other aspects of it as well.

Leaving the placeholder image in place, would at least let the user know that they can and should replace that image.

Body:
Is there any way to set default image sources in the 'header type html' in order for page editors to see an image in the page edit mode?

Because when I add an image as the following

  {sec-two-image1:image global="false"}

What I see in the page edit is only an image icon which does not make a good sense for the user.
See : http://prntscr.com/fqxmzf

My purpse is to present a proper view for him to understand how it will look like after publishing? But I guess the images given in the template level ( I mean the elements provided as a custom html ) are not rendered properly.
Any way to succeed it?

Body:
Because the image that you are seeing is HTML, see screenshot, you wouldn't be able to change it with CSS.. AND you might not be able to do it with JavaScript or Jquery either.

But that being said, you can certainly change the white background area using CSS. You would do something like;

#icontent .weebly-image-area-placeholder {
    background: url(background.png) no-repeat;
    background-position: 50% 0;
    box-shadow: inset 0px 0px 15px 0px #000000;
    cursor: pointer;
}

Note that you really only need to use background: url(background.png) no-repeat; in the CSS noted above, but I have added all of the CSS for that placeholder so you can see that you can change the other aspects of it as well.

Leaving the placeholder image in place, would at least let the user know that they can and should replace that image.


问:
Running countdown timer faster when i back to activity
I make a service for countdown timer, in activity i put a text view for show time every seconds: 100 - 0, but when i leave activity and back to that. i see timer as run very fast, but i want to this run just every second. where is problem ?

MainActivity:

```<code>public static final String mBroadcastIntegerAction = "com.example.broadcast.integer";
private IntentFilter mIntentFilter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    showTime = (TextView) findViewById(R.id.textView1);

    mIntentFilter = new IntentFilter();
    mIntentFilter.addAction(mBroadcastIntegerAction);

    Intent serviceIntent = new Intent(this, AppServiceDay.class);
    startService(serviceIntent);
}

@Override
public void onResume() {
    super.onResume();
    registerReceiver(mReceiver, mIntentFilter);
}

private BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

        if (intent.getAction().equals(mBroadcastIntegerAction)) {
            int second = intent.getIntExtra("Time", 0);

            showTime.setText("" + second);
        }
    }
};
    @Override
protected void onPause() {
    registerReceiver(mReceiver, mIntentFilter);
//      unregisterReceiver(mReceiver);
    super.onPause();
}
</code>```

Service:

```<code>public class AppServiceDay extends Service {

CountDownTimer cdt;
public static Handler mHandler;
int downer = 1000;
int time = 100;
int mainTime = 100000;

@Override
public void onCreate() {
    super.onCreate();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    cdt = new CountDownTimer(mainTime, downer) {
        @Override
        public void onTick(long millisUntilFinished) {

            time -= 1;

            Intent broadcastIntent = new Intent();
            broadcastIntent.setAction(MainActivity.mBroadcastIntegerAction);
            broadcastIntent.putExtra("Time", time);
            sendBroadcast(broadcastIntent);
        }

        @Override
        public void onFinish() {
            time = 100;
            this.start();
        }
    };
    cdt.start();

    return super.onStartCommand(intent, flags, startId);
}

@Override
public IBinder onBind(Intent arg0) {
    return null;
}
}
</code>```

答:
onStartCommand is triggered everytime startService is called and in onStartCommand you are creating new countdown object,

Add a null check before creating new countdown object it will fix your duplicate timer running at same time.

```<code>@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    If(cdt == null) {
        cdt = new CountDownTimer(mainTime, downer) {
            @Override
            public void onTick(long millisUntilFinished) {
                time -= 1;
                Intent broadcastIntent = new Intent();
                broadcastIntent.setAction(MainActivity.mBroadcastIntegerAction);

                broadcastIntent.putExtra("Time", time);
                sendBroadcast(broadcastIntent);

            }

            @Override
            public void onFinish() {
                time = 100;
                this.start();
            }
        };
        cdt.start();
    }

    return super.onStartCommand(intent, flags, startId);
}
</code>```

Body:
I make a service for countdown timer, in activity i put a text view for show time every seconds: 100 - 0, but when i leave activity and back to that. i see timer as run very fast, but i want to this run just every second. where is problem ?

MainActivity:

public static final String mBroadcastIntegerAction = "com.example.broadcast.integer";
private IntentFilter mIntentFilter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    showTime = (TextView) findViewById(R.id.textView1);

    mIntentFilter = new IntentFilter();
    mIntentFilter.addAction(mBroadcastIntegerAction);

    Intent serviceIntent = new Intent(this, AppServiceDay.class);
    startService(serviceIntent);
}

@Override
public void onResume() {
    super.onResume();
    registerReceiver(mReceiver, mIntentFilter);
}

private BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

        if (intent.getAction().equals(mBroadcastIntegerAction)) {
            int second = intent.getIntExtra("Time", 0);

            showTime.setText("" + second);
        }
    }
};
    @Override
protected void onPause() {
    registerReceiver(mReceiver, mIntentFilter);
//      unregisterReceiver(mReceiver);
    super.onPause();
}

Service:

public class AppServiceDay extends Service {

CountDownTimer cdt;
public static Handler mHandler;
int downer = 1000;
int time = 100;
int mainTime = 100000;

@Override
public void onCreate() {
    super.onCreate();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    cdt = new CountDownTimer(mainTime, downer) {
        @Override
        public void onTick(long millisUntilFinished) {

            time -= 1;

            Intent broadcastIntent = new Intent();
            broadcastIntent.setAction(MainActivity.mBroadcastIntegerAction);
            broadcastIntent.putExtra("Time", time);
            sendBroadcast(broadcastIntent);
        }

        @Override
        public void onFinish() {
            time = 100;
            this.start();
        }
    };
    cdt.start();

    return super.onStartCommand(intent, flags, startId);
}

@Override
public IBinder onBind(Intent arg0) {
    return null;
}
}

Body:
onStartCommand is triggered everytime startService is called and in onStartCommand you are creating new countdown object,

Add a null check before creating new countdown object it will fix your duplicate timer running at same time.

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    If(cdt == null) {
        cdt = new CountDownTimer(mainTime, downer) {
            @Override
            public void onTick(long millisUntilFinished) {
                time -= 1;
                Intent broadcastIntent = new Intent();
                broadcastIntent.setAction(MainActivity.mBroadcastIntegerAction);

                broadcastIntent.putExtra("Time", time);
                sendBroadcast(broadcastIntent);

            }

            @Override
            public void onFinish() {
                time = 100;
                this.start();
            }
        };
        cdt.start();
    }

    return super.onStartCommand(intent, flags, startId);
}


问:
Getting FFProbe Information With Python
I've been attempting to figure this out for forever now (I'm new to programming) and I can't figure it out.

I'm attempting to build a script that will test the file, and give me output from which I can get information like "Audio Format" that I can then put into the filename.  However, I can't even get the script to return any file info.  I've hit a wall at inserting an input file...

So at this point I just need help getting it to spit out info based on the argvs I've thrown in.  Hopefully I'll be able to figure out how to parse the audio info from that.

My attempt that seems to be close:

```<code>#!/usr/bin/python
import os, sys, subprocess, shlex, re
from subprocess import call
def probe_file(filename):
    p = subprocess.Popen(['/opt/local/bin/ffprobe', '-show_format', '-pretty', '-loglevel quiet', -i filename], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
    print filename
    print p.communicate()
[probe_file (f) for f in os.listdir('.') if not f.startswith('.')]
</code>```

答:
Here is technique I think it is both simple to use and easy to parse (tested with ffmpeg 3.x):

```<code>import subprocess
import xml.etree

def ffprobe(executable, filename):
    '''Runs ``ffprobe`` executable over ``filename``, returns parsed XML

    Parameters:

        executable (str): Full path leading to ``ffprobe``
        filename (str): Full path leading to the file to be probed

    Returns:

        xml.etree.ElementTree: containing all parsed elements

    '''

    cmd = [
        executable,
        '-v', 'quiet',
        '-print_format', 'xml', #here is the trick
        '-show_format',
        '-show_streams',
        filename,
        ]

    return xml.etree.ElementTree.fromstring(subprocess.check_output(cmd))
</code>```

The data available comes from a string representation that looks like this:

```<code> <ffprobe>
   <streams>
     <stream index="0" codec_name="h264" codec_long_name="H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10" profile="Constrained Baseline" codec_type="video" codec_time_base="1/60" codec_tag_string="avc1" codec_tag="0x31637661" width="560" height="320" coded_width="560" coded_height="320" has_b_frames="0" sample_aspect_ratio="0:1" display_aspect_ratio="0:1" pix_fmt="yuv420p" level="30" color_range="tv" color_space="bt709" color_transfer="bt709" color_primaries="bt709" chroma_location="left" refs="1" is_avc="true" nal_length_size="4" r_frame_rate="30/1" avg_frame_rate="30/1" time_base="1/90000" start_pts="0" start_time="0.000000" duration_ts="498000" duration="5.533333" bit_rate="465641" bits_per_raw_sample="8" nb_frames="166">
       <disposition default="1" dub="0" original="0" comment="0" lyrics="0" karaoke="0" forced="0" hearing_impaired="0" visual_impaired="0" clean_effects="0" attached_pic="0" timed_thumbnails="0"/>
       <tag key="creation_time" value="2010-03-20T21:29:11.000000Z"/>
       <tag key="language" value="und"/>
       <tag key="encoder" value="JVT/AVC Coding"/>
     </stream>
     <stream>...</stream>
   </streams>
   <format filename="/Users/andre/Projects/qnap/librarian/librarian/data/movie.mp4" nb_streams="2" nb_programs="0" format_name="mov,mp4,m4a,3gp,3g2,mj2" format_long_name="QuickTime / MOV" start_time="0.000000" duration="5.568000" size="383631" bit_rate="551193" probe_score="100">
     <tag key="major_brand" value="mp42"/>
     <tag key="minor_version" value="0"/>
     <tag key="compatible_brands" value="mp42isomavc1"/>
     <tag key="creation_time" value="2010-03-20T21:29:11.000000Z"/>
     <tag key="encoder" value="HandBrake 0.9.4 2009112300"/>
   </format>
 </ffprobe>
</code>```

Title: Getting FFProbe Information With Python

Body:
I've been attempting to figure this out for forever now (I'm new to programming) and I can't figure it out.

I'm attempting to build a script that will test the file, and give me output from which I can get information like "Audio Format" that I can then put into the filename.  However, I can't even get the script to return any file info.  I've hit a wall at inserting an input file...

So at this point I just need help getting it to spit out info based on the argvs I've thrown in.  Hopefully I'll be able to figure out how to parse the audio info from that.

My attempt that seems to be close:

#!/usr/bin/python
import os, sys, subprocess, shlex, re
from subprocess import call
def probe_file(filename):
    p = subprocess.Popen(['/opt/local/bin/ffprobe', '-show_format', '-pretty', '-loglevel quiet', -i filename], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
    print filename
    print p.communicate()
[probe_file (f) for f in os.listdir('.') if not f.startswith('.')]

Body:
Here is technique I think it is both simple to use and easy to parse (tested with ffmpeg 3.x):

import subprocess
import xml.etree

def ffprobe(executable, filename):
    '''Runs ``ffprobe`` executable over ``filename``, returns parsed XML

    Parameters:

        executable (str): Full path leading to ``ffprobe``
        filename (str): Full path leading to the file to be probed

    Returns:

        xml.etree.ElementTree: containing all parsed elements

    '''

    cmd = [
        executable,
        '-v', 'quiet',
        '-print_format', 'xml', #here is the trick
        '-show_format',
        '-show_streams',
        filename,
        ]

    return xml.etree.ElementTree.fromstring(subprocess.check_output(cmd))

The data available comes from a string representation that looks like this:

 <ffprobe>
   <streams>
     <stream index="0" codec_name="h264" codec_long_name="H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10" profile="Constrained Baseline" codec_type="video" codec_time_base="1/60" codec_tag_string="avc1" codec_tag="0x31637661" width="560" height="320" coded_width="560" coded_height="320" has_b_frames="0" sample_aspect_ratio="0:1" display_aspect_ratio="0:1" pix_fmt="yuv420p" level="30" color_range="tv" color_space="bt709" color_transfer="bt709" color_primaries="bt709" chroma_location="left" refs="1" is_avc="true" nal_length_size="4" r_frame_rate="30/1" avg_frame_rate="30/1" time_base="1/90000" start_pts="0" start_time="0.000000" duration_ts="498000" duration="5.533333" bit_rate="465641" bits_per_raw_sample="8" nb_frames="166">
       <disposition default="1" dub="0" original="0" comment="0" lyrics="0" karaoke="0" forced="0" hearing_impaired="0" visual_impaired="0" clean_effects="0" attached_pic="0" timed_thumbnails="0"/>
       <tag key="creation_time" value="2010-03-20T21:29:11.000000Z"/>
       <tag key="language" value="und"/>
       <tag key="encoder" value="JVT/AVC Coding"/>
     </stream>
     <stream>...</stream>
   </streams>
   <format filename="/Users/andre/Projects/qnap/librarian/librarian/data/movie.mp4" nb_streams="2" nb_programs="0" format_name="mov,mp4,m4a,3gp,3g2,mj2" format_long_name="QuickTime / MOV" start_time="0.000000" duration="5.568000" size="383631" bit_rate="551193" probe_score="100">
     <tag key="major_brand" value="mp42"/>
     <tag key="minor_version" value="0"/>
     <tag key="compatible_brands" value="mp42isomavc1"/>
     <tag key="creation_time" value="2010-03-20T21:29:11.000000Z"/>
     <tag key="encoder" value="HandBrake 0.9.4 2009112300"/>
   </format>
 </ffprobe>