text:
Q: how to get value currently binded to textbox? i need your advice, please:)
I have a textbox inside a FlipView bound to title property, that shows current Title of a page.
<TextBlock x:Name="jmeno" FontSize="26.667" FontWeight="Light" Text="{Binding Title}" TextWrapping="Wrap" />

And i have a media element showing a video.
<MediaElement x:Name="mmedia" Source="Video/prvniVideo.mp4" Height="300"  Grid.Row="1" KeyUp="mmedia_KeyUp" />

I would like to open different video on different pages and I am trying to accomplish it like this - read the actual display value of texblock and base on that decide, which video to open in media element.
Something like this.
        string AktualniStranka;
        AktualniStranka = jmeno.Text;

        if (AktualniStranka == "Exercise 1")
        {
            mmedia.Source = new Uri("ms-appx:/Video/prvniVideo.mp4", UriKind.RelativeOrAbsolute);
            mmedia.Play();
        }
        else
        {
            mmedia.Source = new Uri("ms-appx:/Video/Gumm.mp4", UriKind.RelativeOrAbsolute);
            mmedia.Play();
        }

But it is not working - I have tried to read just the text of the textblock and put it in another textblock and it is not working either,  I have spent almost the whole day trying to make it work.. Please help guys:)
Full XAML code:
<common:LayoutAwarePage
x:Name="pageRoot"
x:Class="ContosoCookbook.ItemDetailPage"
DataContext="{Binding DefaultViewModel, RelativeSource={RelativeSource Self}}"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:ContosoCookbook"
xmlns:data="using:ContosoCookbook.Data"
xmlns:common="using:ContosoCookbook.Common"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">

<Page.Resources>

    <!-- Collection of items displayed by this page -->
    <Style x:Name="transportStyle"  TargetType="Button">
        <Setter Property="Height" Value="40" />
        <Setter Property="Width" Value="75" />
        <Setter Property="FontSize" Value="11" />
    </Style>

    <CollectionViewSource
        x:Name="itemsViewSource"
        Source="{Binding Items}"
        d:Source="{Binding AllGroups[0].Items, Source={d:DesignInstance Type=data:SampleDataSource, IsDesignTimeCreatable=True}}"/>

    <common:ListConverter x:Key="ListConverter" />

    <Style x:Key="BragAppBarButtonStyle" TargetType="Button" BasedOn="{StaticResource AppBarButtonStyle}">
        <Setter Property="AutomationProperties.AutomationId" Value="BragAppBarButton"/>
        <Setter Property="AutomationProperties.Name" Value="Brag"/>
        <Setter Property="Content" Value=""/>
    </Style>

    <Style x:Key="ReminderAppBarButtonStyle" TargetType="Button" BasedOn="{StaticResource AppBarButtonStyle}">
        <Setter Property="AutomationProperties.AutomationId" Value="ReminderAppBarButton"/>
        <Setter Property="AutomationProperties.Name" Value="Reminder"/>
        <Setter Property="Content" Value=""/>
    </Style>

    <local:ProductLicenseDataSource x:Key="License" />
    <common:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>

</Page.Resources>

<Page.BottomAppBar>
    <AppBar x:Name="PageAppBar" Padding="10,0,10,0">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="50*"/>
                <ColumnDefinition Width="50*"/>
            </Grid.ColumnDefinitions>
            <StackPanel x:Name="LeftCommands" Orientation="Horizontal" Grid.Column="0" HorizontalAlignment="Left">
                <Button x:Name="BragButton" HorizontalAlignment="Left" Style="{StaticResource BragAppBarButtonStyle}" Click="OnBragButtonClicked" />
                <Button x:Name="PinRecipeButton" HorizontalAlignment="Left" Style="{StaticResource PinAppBarButtonStyle}" Click="OnPinRecipeButtonClicked" />
                <Button x:Name="ReminderButton" HorizontalAlignment="Left" Style="{StaticResource ReminderAppBarButtonStyle}" Click="OnReminderButtonClicked" />
            </StackPanel>
            <StackPanel x:Name="RightCommands" Orientation="Horizontal" Grid.Column="1" HorizontalAlignment="Right">
            </StackPanel>
        </Grid>
    </AppBar>
</Page.BottomAppBar>

<!--
    This grid acts as a root panel for the page that defines two rows:
    * Row 0 contains the back button and page title
    * Row 1 contains the rest of the page layout
-->
<Grid
    Style="{StaticResource LayoutRootStyle}"
    DataContext="{Binding Group}"
    d:DataContext="{Binding AllGroups[0], Source={d:DesignInstance Type=data:SampleDataSource, IsDesignTimeCreatable=True}}">

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

    <!--
        The remainder of the page is one large FlipView that displays details for
        one item at a time, allowing the user to flip through all items in the chosen
        group
    -->

    <FlipView
        x:Name="flipView"
        AutomationProperties.AutomationId="ItemsFlipView"
        AutomationProperties.Name="Item Details"
        TabIndex="1"
        Grid.RowSpan="2"
        ItemsSource="{Binding Source={StaticResource itemsViewSource}}">

        <FlipView.ItemContainerStyle>
            <Style TargetType="FlipViewItem">
                <Setter Property="Margin" Value="0,137,0,0"/>
            </Style>
        </FlipView.ItemContainerStyle>

        <FlipView.ItemTemplate>
            <DataTemplate>
                <UserControl Loaded="StartLayoutUpdates" Unloaded="StopLayoutUpdates">
                    <ScrollViewer x:Name="scrollViewer" Style="{StaticResource VerticalScrollViewerStyle}" Grid.Row="1">

                        <!-- Three-column grid for item-detail layout -->
                        <Grid Margin="120,0,20,20">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="600" />
                                <ColumnDefinition Width="40" />
                                <ColumnDefinition />
                            </Grid.ColumnDefinitions>

                            <StackPanel Orientation="Vertical" Grid.Column="0">
                                <TextBlock x:Name="jmeno" FontSize="26.667" FontWeight="Light" Text="{Binding Title}" TextWrapping="Wrap" />

                            </StackPanel>

                            <StackPanel Orientation="Vertical" Grid.Column="4">
                                <TextBlock FontSize="26.667" FontWeight="Light" Text="Description" Margin="0,0,0,16"/>

                                <TextBlock FontSize="26.667" FontWeight="Light" Text="{Binding ShortDesctiption}" TextWrapping="Wrap"/>
                                <ScrollViewer Style="{StaticResource VerticalScrollViewerStyle}">
                                    <Grid>
                                        <TextBlock FontSize="20" FontWeight="Light" Text="{Binding Directions}" TextWrapping="Wrap" Visibility="{Binding IsLicensed, Source={StaticResource License}, Converter={StaticResource BooleanToVisibilityConverter }}" />
                                        <Button Width="225" Height="120" Background="#30ffffff" Click="OnPurchaseProduct" Visibility="{Binding IsTrial, Source={StaticResource License}, Converter={StaticResource BooleanToVisibilityConverter }}">
                                            <Button.Content>
                                                <TextBlock Text="{Binding FormattedPrice, Source={StaticResource License}}" TextWrapping="Wrap" TextAlignment="Center" />
                                            </Button.Content>
                                        </Button>
                                    </Grid>
                                </ScrollViewer>
                            </StackPanel>
                        </Grid>

                        <VisualStateManager.VisualStateGroups>
                            <!-- Visual states reflect the app's view state inside the FlipView -->
                            <VisualStateGroup x:Name="ApplicationViewStates">
                                <VisualState x:Name="FullScreenLandscape"/>
                                <VisualState x:Name="Filled"/>

                                <!-- Respect the narrower 100-pixel margin convention for portrait -->
                                <VisualState x:Name="FullScreenPortrait">
                                    <Storyboard>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="image" Storyboard.TargetProperty="MaxHeight">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="400"/>
                                        </ObjectAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>

                                <!-- When snapped, the content is reformatted and scrolls vertically -->
                                <VisualState x:Name="Snapped">
                                    <Storyboard>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="scrollViewer" Storyboard.TargetProperty="Style">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource VerticalScrollViewerStyle}"/>
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="image" Storyboard.TargetProperty="MaxHeight">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="160"/>
                                        </ObjectAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>
                            </VisualStateGroup>
                        </VisualStateManager.VisualStateGroups>
                    </ScrollViewer>
                </UserControl>
            </DataTemplate>

        </FlipView.ItemTemplate>
    </FlipView>
    <!-- MEDIA PANEL-->

    <StackPanel Orientation="Vertical" Grid.Row="1" >
        <Border   BorderThickness="5" BorderBrush="White" Background="Black"   HorizontalAlignment="Left" Margin="165,50,0,0" VerticalAlignment="Top">
            <ContentControl x:Name="VideoContainer" Height="300" KeyUp="VideoContainer_KeyUp"     >

                <MediaElement x:Name="mmedia" Source="Video/prvniVideo.mp4" Height="300"  Grid.Row="1" KeyUp="mmedia_KeyUp" />
            </ContentControl>
        </Border>

        <StackPanel Orientation="Horizontal" Margin="140,20,0,0">
            <Button Name="btnPlay" Click="btnPlay_Click"
        Style="{StaticResource transportStyle}" Content="Play" />
            <Button Name="btnPause" Click="btnPause_Click"
        Style="{StaticResource transportStyle}" Content="Pause" />
            <Button Name="btnStop" Click="btnStop_Click"
        Style="{StaticResource transportStyle}" Content="Stop" />
            <Button Name="btnReverse" Click="btnReverse_Click"
        Style="{StaticResource transportStyle}" Content="Rewind" />
            <Button Name="btnForward" Click="btnForward_Click"
        Style="{StaticResource transportStyle}" Content="Forward" />
            <Button Name="btnVolumeUp" Click="btnVolumeUp_Click"
        Style="{StaticResource transportStyle}" Content="-" />
            <Button Name="btnVolumeDown" Click="btnVolumeDown_Click"
        Style="{StaticResource transportStyle}" Content="+" />
            <Button Name="btnMute" Click="btnMute_Click"
        Style="{StaticResource transportStyle}" Content="Mute" />
        </StackPanel>
        <Button x:Name="btnFullScreenToggle" Click="btnFullScreenToggle_Click"
        Style="{StaticResource transportStyle}" Content="Full Screen ON" Margin="290,0,0,0" Width="302" />

        <TextBlock x:Name="poser" FontSize="26.667" FontWeight="Light" Text="poser" TextWrapping="Wrap" />

    </StackPanel>

    <!-- FlipView used in portrait mode -->
    <FlipView
        x:Name="portraitFlipView"
        AutomationProperties.AutomationId="ItemsFlipView"
        AutomationProperties.Name="Item Details"
        Grid.Row="1"
        Margin="0,-3,20,0"
        ItemsSource="{Binding Source={StaticResource itemsViewSource}}"
        Visibility="Collapsed">

        <FlipView.ItemTemplate>
            <DataTemplate>
                <UserControl Loaded="StartLayoutUpdates" Unloaded="StopLayoutUpdates">
                    <ScrollViewer x:Name="scrollViewer" Style="{StaticResource VerticalScrollViewerStyle}" Grid.Row="1">

                        <!-- Vertical StackPanel for item-detail layout -->
                        <StackPanel Orientation="Vertical" Margin="100,0,20,0">
                            <StackPanel Orientation="Vertical">
                                <TextBlock FontSize="26.667" FontWeight="Light" Text="{Binding Title}" TextWrapping="Wrap"/>
                                <Image x:Name="image" Width="400" Margin="0,20,0,40" Stretch="Uniform" Source="{Binding Image}" HorizontalAlignment="Left"/>
                            </StackPanel>

                            <StackPanel Orientation="Vertical">
                                <TextBlock FontSize="26.667" FontWeight="Light" Text="Ingredients" Margin="0,0,0,16"/>
                                <TextBlock FontSize="20" FontWeight="Light" LineHeight="32.5" Text="{Binding Ingredients, Converter={StaticResource ListConverter}}" TextWrapping="Wrap" />
                            </StackPanel>

                            <StackPanel Orientation="Vertical">
                                <TextBlock FontSize="26.667" FontWeight="Light" Text="Directions" Margin="0,24,0,16"/>
                                <ScrollViewer Style="{StaticResource VerticalScrollViewerStyle}">
                                    <Grid>
                                        <TextBlock FontSize="20" FontWeight="Light" Text="{Binding Directions}" TextWrapping="Wrap" Visibility="{Binding IsLicensed, Source={StaticResource License}, Converter={StaticResource BooleanToVisibilityConverter }}" />
                                        <Button Width="225" Height="120" Background="#30ffffff" Click="OnPurchaseProduct" Visibility="{Binding IsTrial, Source={StaticResource License}, Converter={StaticResource BooleanToVisibilityConverter }}">
                                            <Button.Content>
                                                <TextBlock Text="{Binding FormattedPrice, Source={StaticResource License}}" TextWrapping="Wrap" TextAlignment="Center" />
                                            </Button.Content>
                                        </Button>

                                    </Grid>
                                </ScrollViewer>
                            </StackPanel>
                        </StackPanel>
                    </ScrollViewer>
                </UserControl>
            </DataTemplate>
        </FlipView.ItemTemplate>
    </FlipView>

    <FlipView
        x:Name="snappedFlipView"
        AutomationProperties.AutomationId="ItemsFlipView"
        AutomationProperties.Name="Item Details"
        Grid.Row="1"
        Margin="0,-3,0,0"
        ItemsSource="{Binding Source={StaticResource itemsViewSource}}"
        Visibility="Collapsed">

        <FlipView.ItemTemplate>
            <DataTemplate>
                <UserControl Loaded="StartLayoutUpdates" Unloaded="StopLayoutUpdates">
                    <ScrollViewer x:Name="scrollViewer" Style="{StaticResource VerticalScrollViewerStyle}" Grid.Row="1">

                        <!-- Vertical StackPanel for item-detail layout -->
                        <StackPanel Orientation="Vertical" Margin="20,0,20,0">
                            <StackPanel Orientation="Vertical">
                                <TextBlock FontSize="20" FontWeight="Light" Text="{Binding Title}" TextWrapping="Wrap"/>
                                <Image x:Name="image" Width="260" Margin="0,12,0,40" Stretch="Uniform" Source="{Binding Image}" HorizontalAlignment="Left"/>
                            </StackPanel>
                            <StackPanel Orientation="Vertical">
                                <TextBlock FontSize="20" FontWeight="Light" Text="Ingredients" Margin="0,0,0,16"/>
                                <TextBlock FontSize="16" FontWeight="Light" TextWrapping="Wrap" Text="{Binding Ingredients, Converter={StaticResource ListConverter}}" />
                            </StackPanel>
                        </StackPanel>
                    </ScrollViewer>
                </UserControl>
            </DataTemplate>
        </FlipView.ItemTemplate>
    </FlipView>

    <!-- Back button and page title -->
    <Grid HorizontalAlignment="Left" >
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Button x:Name="backButton" Click="GoBack" IsEnabled="{Binding Frame.CanGoBack, ElementName=pageRoot}" Style="{StaticResource BackButtonStyle}"/>
        <TextBlock x:Name="pageTitle" Text="{Binding Title}" Style="{StaticResource PageHeaderTextStyle}" Grid.Column="1" IsHitTestVisible="false"/>
        <Button Name="btnFullScreenOff" Click="btnFullScreenToggle_Click"
        Style="{StaticResource transportStyle}" Content="Full Screen OFF" HorizontalAlignment="Right" Grid.Column="1" Margin="0,56,495,36" RenderTransformOrigin="-9.161,0.266" Height="48" Width="106" Visibility="Collapsed" />
    </Grid>

    <VisualStateManager.VisualStateGroups>

        <!-- Visual states reflect the application's view state -->
        <VisualStateGroup x:Name="ApplicationViewStates">
            <VisualState x:Name="FullScreenLandscape"/>
            <VisualState x:Name="Filled"/>

            <!-- The back button respects the narrower 100-pixel margin convention for portrait -->
            <VisualState x:Name="FullScreenPortrait">
                <Storyboard>
                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="backButton" Storyboard.TargetProperty="Style">
                        <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PortraitBackButtonStyle}"/>
                    </ObjectAnimationUsingKeyFrames>

                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="flipView" Storyboard.TargetProperty="Visibility">
                        <DiscreteObjectKeyFrame KeyTime="0" Value="Collapsed"/>
                    </ObjectAnimationUsingKeyFrames>
                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="portraitFlipView" Storyboard.TargetProperty="Visibility">
                        <DiscreteObjectKeyFrame KeyTime="0" Value="Visible"/>
                    </ObjectAnimationUsingKeyFrames>

                </Storyboard>
            </VisualState>

            <!-- The back button and title have different styles when snapped -->
            <VisualState x:Name="Snapped">
                <Storyboard>
                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="backButton" Storyboard.TargetProperty="Style">
                        <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource SnappedBackButtonStyle}"/>
                    </ObjectAnimationUsingKeyFrames>
                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="pageTitle" Storyboard.TargetProperty="Style">
                        <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource SnappedPageHeaderTextStyle}"/>
                    </ObjectAnimationUsingKeyFrames>
                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="flipView" Storyboard.TargetProperty="Visibility">
                        <DiscreteObjectKeyFrame KeyTime="0" Value="Collapsed"/>
                    </ObjectAnimationUsingKeyFrames>
                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="snappedFlipView" Storyboard.TargetProperty="Visibility">
                        <DiscreteObjectKeyFrame KeyTime="0" Value="Visible"/>
                    </ObjectAnimationUsingKeyFrames>

                </Storyboard>
            </VisualState>
        </VisualStateGroup>
    </VisualStateManager.VisualStateGroups>
</Grid>

Full C# code:

A: What I see is that you are trying to get the value displayed, from the name of you Textblock (jmeno), right ?
You should not do that. Your textblock is defined in a datatemplate, the only reason to assign it a name is to apply a storyboard.
What you should do, is get your Flipview's SelectedItem object (which is your visual element datacontext), and get the Title property of that data object.
So :
(flipView.SelectedItem as -WhateverYourTypeIs-).Title, and there you should have your value.


text:
Q: How to create a new array with the same content? I use an external library to iterate over the array. It has the next() function to go to the next array item and returns false if there is no next item. If the next() is called the first time, then it returns the first item.
But here is how it works -
var a = ['item1'];
a.next(); // 'item1' is returned
...
a = ['item1']; // it could be called several times
a.next(); // false is returned, but 'item1' is expected

Is there any way to make a array to be treated as new array by next() function?
I tried to add new elements to a (a.push(' ')) and it works well, but then I have to deal with an empty array elements.

A: If it's a one dimensional array you could probably do something like:
let newArray = [...oldArray];

This would create a new array.
Can I ask you why you are using an external library to map over an array?

A: You could use the spread operator to create a shallow copy of that array.

var a = [1,2,3];
var b = [...a];

a.push(4);

console.log("a = " + a);
console.log("b = " + b);

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to display ASP.NET MVC 3 view as a popup I need to display a full view (.cshtml webpage) as a pop-up in ASP.NET MVC 3. Currently the webpage to become a popup is controlled by MVC controller and behaves as another view. The popup webpage will display when a button is clicked from another .cshtml webpage and I would not like to exit from the origin view when the button is clicked. I am thinking about using jquery.show() to make the view as a pop-up, although this is not a requirement. What changes do I need to make?

A: Make a jquery ajax call like this:
      $.ajax({
            url: /myController/Popup,
            type: 'GET',
            data: id,
            success: function (result) {
                $("#myTag").html(result);
             }
      });

Then in the controller just return a partial view, something like this:
   public ActionResult Popup(int id)
    {

        /* construct the viewmodel */
        myViewModel = ....
        .
        return PartialView("MyPartialView", myViewModel);
    }

This partial view will then be added to myTag.

A: Make an ajax call to the url of the action, something like...
$.ajax({
         url: "@Url.Action("youractionname")"
        ,type: "POST"
        ,data: data
        ,success: function(response)
        {
            $(document).append("
" + response + "
");
        }
    });

Obviously, your html may need to be adjusted a little, maybe a modal div to block access to the below page, and .popup will need to be defined to make it appear as a popup.

A: One way to accomplish this is to use http://fancybox.net/ and just load the new webpage as an iframe inside the fancybox. Check at fancybox exemples at the bottom.
jQuery.show() has nothing to do with creating popups. It is used to hide/show elements in the DOM.


text:
Q: Using an Array as a Whille loop condition I am trying specify a condition by saying that if an array is not equal to an array run loop. So for example:
array1 [1,2,3]
array2 [1,2,3]
Here array1 does equal array2 as the elements in 0 in both arrays are the same, the elements in 1 in both arrays are the same and so on...
The code I have so far doesn't seem to work. Is there a way of comparing two arrays and if all elements in one match all the elements in the second one the condition is true.
Here is my test code:
int C1Mean[3];
int C2Mean[3];
int prv_mean1[3];
int prv_mean2[3];

while (C1Mean[3] = prv_mean1[3] && C2Mean[3] = prv_mean2[3])
{
    //code
}

Thanks chaps.

A: As commented you access your arrays out of bounds, and you are using assignments (single =) instead or comparisons (==).
To compare your arrays (element by element), you can use std::equal :
while(std::equal(std::begin(C1Mean), std::end(C1Mean), std::begin(prv_mean1))
   && std::equal(std::begin(C2Mean), std::end(C2Mean), std::begin(prv_mean2)))
{
 ...
}

Or without c++11 :
while(std::equal(C1Mean, C1Mean + sizeof C1Mean / sizeof *C1Mean, prv_mean1)
   && std::equal(C2Mean, C2Mean + sizeof C2Mean / sizeof *C2Mean, prv_mean2))
{
 ...
}

A: In c++11, you may use std::array, and use ==:
std::array<int, 3> C1Mean;
std::array<int, 3> C2Mean;
std::array<int, 3> prv_mean1;
std::array<int, 3> prv_mean2;

while (C1Mean == prv_mean1 && C2Mean == prv_mean2)
{
    //code
}

A: You are not using comparison operator (==) but assignment (=), so you change the value of CMean[i] in the condition and the condition would be false only when one of prv_mean2 would be equal to zero. And no, you can't compare the whole arrays.

A: If you are able to use c++11 you can use a generic function. The generic function is:
bool equal(beginIterator, endIterator, beginIterator Other);

This generic function will compare all values in a range. Note that the second array must be at least as long as the first array.
Since an array is nog an object you cannot use arr.begin () and you should use std::begin(arr) and std::end(arr). These functions come with #include.
Furthermore, if you can use c++11 you can also use the standad container std::array or std::vector. Then you can just state arr1 == arr2.
Note: I wrote this on my mobile and didn't check whether the generic function actually works on arrays. I will check this when at home again and eventually remove my post.

A: You can create a function to compare the two arrays that will return 1 if they are equal and 0 otherwise. Say, for example,
while(areEqual(C1Mean,prv_mean1) && areEqual(C2Mean,prv_mean2))
{
 //Perform your task
}

where
int areEqual(int array1[],int array2[])
{
 //compare them and return 1 if equal else return 0;
}

A: It seems like you need a double equals("=="). Try:
while (C1Mean[3] == prv_mean1[3] && C2Mean[3] == prv_mean2[3])
{
    //code
}


text:
Q: How to config nginx about proxy_pass? I run tomcat and my nginx.conf like this

If in http://127.0.0.1:8080/edu/b.html or http://192.168.0.102:8080/edu/b.html it's ok
If in http://192.168.0.102:9001/edu/b.html it can't work

my computer ip now is 192.168.0.102

error message
[error] 17810#17810: *12 connect() failed (111: Connection refused) while connecting to upstream, client: 192    .168.0.102, server: 192.168.0.102, request: "GET /edu/b.html HTTP/1.1", upstream: "http://127.0.0.1:8000/edu/b.html", host: "192.    168.0.102:9001"

Where is error? What should I do?

A: It is trying to connect to http://127.0.0.1:8000/edu/b.html(upstream) instead of http://192.168.0.102:8080/edu/b.html. You need to change the upstream port in your nginx.conf


text:
Q: Docker first user with docker I'm trying to create a docker image of a gerrit instance contening just an admininstator.
I have no problem to create gerrit instance but I can't create the admin user.
Have you an idea to create this first user ?

A: The documentation states:

The first user to sign-in and register an account will be automatically placed into the fully privileged Administrators group, permitting server management over the web and over SSH.
  Subsequent users will be automatically registered as unprivileged users.

So depending on your authentication method, simply log in with a user.


text:
Q: Is it possible to add #fragment part of uri in Vaadin 14 and RouterLink? Is it possible to add #fragment part of URI in Vaadin 14 and RouterLink?
I can't find anything in Vaadin docs.
I need this to have fast access to a specific part of the view from another view.

A:
Is it possible to add #fragment part of URI in Vaadin 14 and RouterLink?

No, that is not possible. There is a solution to your problem*, but RouterLink does not have any means to define an url fragment so it would scroll to the HTML element with the given id.

*How could your needs be implemented instead:
Let your target view class implement HasUrlParameter<String> (use @Wildcard annotation on setParameter, so that you also can navigate to this view without specifying a fragment-parameter).
In the setParameter method in your view, you then read the given parameter and if it's not empty you could execute some javascript that scrolls to the element with the given id. Now you can specify the fragment in the RouterLink like this:
new RouterLink("MyView", MyView.class, "#my-fragment");
Yes, this is not an optimal solution, not by a long shot, but if you really need it, you could do it.
Please create a ticket for adding API to RouterLink for defining url fragments in the github repo of vaadin-flow, if you want this to happen.


text:
Q: WSO2 Identity Server: SOAP Services failing to update user claim values after first time I have been using WSO2 IS 5.3.0. I am using SOAP service of RemoteUserStoreManagerService. Operation is setUserClaimValues. This is used to update value of failed login attempts by user. However, this service calls work only for the first time and then it does not work until wso2 restarted. The SOAP service does not return any error though any time.
When I hit it through SOAP-UI, I get following response with blank body.
HTTP/1.1 202 Accepted
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
X-Frame-Options: DENY
Content-Type: text/xml;charset=UTF-8
Transfer-Encoding: chunked
Date: Wed, 22 Mar 2017 21:03:16 GMT
Server: WSO2 Carbon Server

SOAP Request for setting value
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:ser="http://service.ws.um.carbon.wso2.org" xmlns:xsd="http://common.mgt.user.carbon.wso2.org/xsd">
   <soap:Header/>
   <soap:Body>
      <ser:setUserClaimValues>
         <!--Optional:-->
         <ser:userName>superadmin03</ser:userName>

          <ser:claims>
            <!--Optional:-->
            <xsd:claimURI>http://wso2.org/claims/identity/failedLoginAttempts</xsd:claimURI>
            <!--Optional:-->
            <xsd:value>2</xsd:value>
         </ser:claims>

      </ser:setUserClaimValues>
   </soap:Body>
</soap:Envelope>

SOAP Response for getting value
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:ser="http://service.ws.um.carbon.wso2.org">
   <soap:Header/>
   <soap:Body>
      <ser:getUserClaimValues>
         <!--Optional:-->
         <ser:userName>superadmin03</ser:userName>

      </ser:getUserClaimValues>
   </soap:Body>
</soap:Envelope>

When I call getUserClaimValues for same attribute, it does not show me new value but same old value.
I am trying to update value for http://wso2.org/claims/identity/failedLoginAttempts
Here's what I found in logs in WSO2 though SOAP service does not return any faults.
[2017-03-22 16:03:20,012]  WARN {org.wso2.carbon.server.admin.module.handler.AuthenticationHandler} -  Illegal access attempt at [2017-03-22 16:03:20,0012] from IP address 127.0.0.1 while trying to authenticate access to service RemoteUserStoreManagerService

Any help is very much appreciated!
Regards,
Sagar Shah

A: It looks like you have enabled both identityMgtEventListeners in identity.xml file.
Either
org.wso2.carbon.identity.mgt.IdentityMgtEventListener
or
org.wso2.carbon.identity.governance.listener.IdentityMgtEventListener
Should be enabled at once.
Thanks
Isura.

A: I have a issue where the user's FailedLoginAttempt is not getting reset to 0 after one successful login action.


text:
Q: Jupyter Notebook throwing Setx Error I opened Jupyter Notebook for the first time going to lay down some code only to be met with a password prompt. Seemed odd because I've never opened it on this PC and it doesn't prompt me for a password on my laptop. I took to the Google Machine for an answer how to disable the password, which was the jupyter_notebook_config.py file to which (supposedly) I was to enter the following command c.NotebookApp.token = u''
Now the browser window opens up with
Invalid number of parameters
Invalid number of parameters
Invalid number of parameters
Invalid number of parameters
ERROR: Invalid syntax. Default option is not allowed more than '2' time(s).
Type "SETX /?" for usage.
Invalid number of parameters
Invalid number of parameters
Invalid number of parameters
Invalid number of parameters
ERROR: Invalid syntax. Default option is not allowed more than '2' time(s).
Type "SETX /?" for usage.

I even went so far as to uninstall Anaconda entirely, then reinstalled, and this error is still popping up.
What the ever loving (*&%(*&^ did I do, how do I fix it, and why on this beautiful Earth does eve
In[140]: frame.reindex(index = ['a','b','c','d'],columns = states).ffill()

Out[142]:

Texas   Utah    California

a   1.0 NaN 2.0

b   1.0 NaN 2.0

c   4.0 NaN 5.0

d   7.0 NaN 8.0rything involving code have to be so god-damned complicated?


text:
Q: Linking Button to an existing activity in android I have an activity that has already been crated for nav drawer. I would like to connect a button for search in for quick navigation in that I don't need to open the drawer for search here is my code as follow:
main.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/nav_search"
        android:icon="@drawable/ic_search"
        android:title="@string/search"
        app:showAsAction="always" />

</menu>

Am main activity is as follow.
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

    Fragment currFragment;
    boolean isLoggedPrev, isLoggedCurrent;
    NavigationView navigationView;
    boolean doubleBackToExitPressedOnce = false;
    public static int offsetY = 0;
    private AdView adView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {

            public void onDrawerClosed(View view) {
                super.onDrawerClosed(view);
            }

            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                if (UserAccessSession.getInstance(MainActivity.this).getUserSession() != null) {
                    isLoggedCurrent = true;
                } else {
                    isLoggedCurrent = false;
                }

                if (isLoggedCurrent != isLoggedPrev) {
                    isLoggedPrev = isLoggedCurrent;
                    checkLoginNavigation();
                }
            }
        };

        drawer.setDrawerListener(toggle);
        toggle.syncState();

        TypedValue tv = new TypedValue();
        if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
            offsetY = TypedValue.complexToDimensionPixelSize(tv.data, getResources().getDisplayMetrics());
            Config.OFFSET_Y = offsetY;
        }
        showFragment(new HomeFragment());
        showAds();
    }

    public void checkLoginNavigation() {
        navigationView.getMenu().clear();
        UserSession userSession = UserAccessSession.getInstance(this).getUserSession();
        if (userSession != null) {
            navigationView.inflateMenu(R.menu.activity_main_drawer_logged);
        } else {
            navigationView.inflateMenu(R.menu.activity_main_drawer_not_logged);
        }
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            if (doubleBackToExitPressedOnce) {
                super.onBackPressed();
                return;
            }
            doubleBackToExitPressedOnce = true;
            Toast.makeText(this, R.string.tap_back_again_to_exit, Toast.LENGTH_SHORT).show();
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    doubleBackToExitPressedOnce = false;
                }
            }, 2000);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        Intent i;
        int id = item.getItemId();
        if(id == R.id.nav_home) {
            showFragment(new HomeFragment());
            setTitle(R.string.app_name);
        }
        if(id == R.id.nav_categories) {
            showFragment(new CategoryFragment());
            setTitle(R.string.categories);
        }
        if(id == R.id.nav_favorites) {
            showFragment(new FavoritesFragment());
            setTitle(R.string.favorites);
        }
        if(id == R.id.nav_featured) {
            showFragment(new FeaturedFragment());
            setTitle(R.string.featured);
        }
        if(id == R.id.nav_search) {
            i = new Intent(this, SearchActivity.class);
            startActivity(i);
        }
        if(id == R.id.nav_news) {
            showFragment(new NewsFragment());
            setTitle(R.string.latest_news);
        }
        if(id == R.id.nav_about_us) {
            showFragment(new AboutUsFragment());
            setTitle(R.string.about_us);
        }
        if(id == R.id.nav_terms_condition) {
            showFragment(new TermsConditionFragment());
            setTitle(R.string.terms_and_conditions);
        }
        if(id == R.id.nav_settings) {
            i = new Intent(this, SettingsActivity.class);
            startActivity(i);
        }
        if(id == R.id.nav_login) {
            i = new Intent(this, LoginActivity.class);
            startActivity(i);
        }
        if(id == R.id.nav_profile) {
            i = new Intent(this, ProfileActivity.class);
            startActivity(i);
        }
        if(id == R.id.nav_my_events) {
            i = new Intent(this, MyEventsActivity.class);
            startActivity(i);
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    public void showFragment(Fragment fragment) {
        if (currFragment != null && fragment.getClass().equals(currFragment.getClass()))
            return;

        currFragment = fragment;
        FragmentManager fragmentManager = this.getSupportFragmentManager();
        if (fragmentManager == null)
            return;

        FragmentTransaction ft = fragmentManager.beginTransaction();
        if (ft == null)
            return;

        ft.replace(R.id.content_frame, fragment).commitAllowingStateLoss();
    }

I would love when I click the search button it loads the activity for search, which is currently being used by navigation drawer.

A: FYI
android:id="@+id/nav_search" is MenuItem  not part of NavigationItem remove it from your onNavigationItemSelected() and add in to onOptionsItemSelected()
Try this
@Override
public boolean onOptionsItemSelected(MenuItem item) {
   int id = item.getItemId();
   if(id == R.id.nav_search) {
       i = new Intent(this, SearchActivity.class);
       startActivity(i);
       return true;
   }

   return super.onOptionsItemSelected(item);
}

A: Its the MenuItem not NavigationItem.
  @Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == R.id.nav_search) {
        // do your stuff here
    }
    return super.onOptionsItemSelected(item);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.yourMenu,menu);
    return super.onCreateOptionsMenu(menu);
}


text:
Q: Actionscript class "undefined property" errors I am having a lot of problems with setting up a webcam connection.
I read that I should use a class for the connection, so that the onBWDone() method is defined and I don't get an error about this method.
The actionscript class:
package cam  {
    public class WebcamSetup {

    public var appURL:String;

    public function setConnection():NetStream

    {
        nc:NetConnection = new NetConnection();
        nc.client = this;
        nc.addEventListener(NetStatusEvent.NET_STATUS, onNetStatus);
        nc.addEventListener(AsyncErrorEvent.ASYNC_ERROR, onAsyncError);
        nc.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError);
        nc.connect(appURL);

        ns:NetStream = new NetStream(nc);

        return ns;
    }

    public function onBWDone():void{
    }
    }
}

In the flash file, I do this:
import cam.WebcamSetup;

var wc:WebcamSetup = new WebcamSetup();
wc.appURL = "rtmp://xxxxx";

var nss:NetStream = wc.setConnection();

var camera = Camera.getCamera();

if (camera != null){

    myVid.attachCamera(camera);

    nss.attachCamera(camera);
}

I get loads of "undefined method" and "undefined property" errors.
And can I not do a return like this? I get the error "return value must be undefined".

A: The first problem I see is that your function setConnection has the return type void (which means that the function returns nothing).
public function setConnection():void

should be
public function setConnection():NetStream

Then AS3 knows that the object returned from the setConnection function will be of the type NetStream.
It would be useful if you pasted the errors you're getting.
Is getCamera a static function within the Camera class? It's hard to know what's happening.

A: i've answered almost the same question yesterday (you should wait for NetConnection to connect before creating a NetStream) and btw your nss and camera variables have no type declaration and var nss = wc.setConnection(); means nothing as long as setConnection() returns void


text:
Q: Keep a button disabled until a valid entry is entered (realtime check) I am looking for a way of keeping a button disabled until a valid value is entered into a field. The issue is it has to enable in realtime and without the need for a button to be clicked to check the value.
So for example in the below sample code, if the username of the individual is David1234, the button QR must remain disabled until all characters are entered. So anything other than David1234 been entered will result in the button remianing disabled. Typing David1234 will result in the button becoming active and will become clickable to the user.
import tkinter as tk
import os

#Create QR code window
def QR():
    qr_window = tk.Toplevel(root)
    qr_window.title("QR Code")
    qr_window.geometry('100x100')
    qr_window.resizable(0,0)
    qr_window.config(bg='lightgrey')
    tk.Label(qr_window, text='Test', justify='left', font='arial 11 bold', bg='light grey').pack()

#Change config state of validation label
def valid():
    validation.configure(state='normal')

validated = False

#Create main window
root = tk.Tk()
root.geometry('250x250')
root.resizable(0, 0)
root.title('Client Code Generator')
root.config(bg='lightgrey')

#user input
user_input_QR = tk.StringVar()
tk.Label(root, text='To generate the QR code, please enter your logon id.', font='arial 15 bold',
         wraplength=180, bg='grey80').pack()
entered = tk.Entry(root, font='arial 15', textvariable=user_input_QR, bg='white')
entered.place(x=15, y=130)

#Validation button. Should remain disabled until user enters a valid ID
validation = tk.Button(root, text='QR', state='disabled', command=QR)
validation.place(x=100, y=160)

#####  This is the section I thought would do the trick, but user_input_QR doesn't process automatically #######
if user_input_QR.get() == os.getlogin() and validated == False:
    valid()
    validated = True

root.mainloop()

I can get similar result by implement the validity check into the QR button itself or a separate button, but that requires the button to be 'normal'.
Is there a way to detect entered characters automatically without the user needing to click a button.


text:
Q: How do you optimize the FuelUX package for deployment with Grunt and Bower? I'm new to Grunt and Bower. When I install FuelUX using bower, it puts about 77 megabytes of files in my app/components/fuelux directory. The default Gruntfile.js that gets generated by yo (using the angular generator) copies all of those file during a Grunt build.
I'm pretty sure I don't need to deploy all those file to my web/app server. What's the best way to ensure that only the necessary files get created in my Grunt dist output directory?

A: I would recommend you get the author of the package to make use of the ignore property for bower.json to ignore everything that isn't needed.
I'm not sure which generator you used, but generator-webapp only copies over what you explicitly define in your Gruntfile/index.html.


text:
Q: Unexpected Connection Reset: A PHP or an Apache issue? I have a PHP script that keeps stopping at the same place every time and my browser reports:

The connection to the server was reset
  while the page was loading.

I have tested this on Firefox and IE, same thing happens. So, I am guessing this is an Apache/PHP config problem. Here are few things I have set.
PHP.ini
max_execution_time = 300000
max_input_time = 300000
memory_limit = 256M

Apache (httpd.conf)
Timeout 300000
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 0

Are the above correct? What can be causing this and what can I set?

I am running PHP (5.2.12.12) as a
  module on Apache (2.2) on a Windows
  Server 2003.

It is very likely this is an Apache or PHP issue as all browsers do the same thing. I think the script runs for exactly 10 mins (600 seconds).

A: I had a similar issue - turns out apache2 was segfaulting. Cause of the segfault was php5-xdebug for 5.3.2-1ubuntu4.14 on Ubuntu 10.04 LTS. Removing xdebug fixed the problem.

A: I also had this problem today, it turned out to be a stray break; statement in the PHP code (outside of any switch or any loop), in a function with a try...catch...finally block.
Looks like PHP crashes in this situation:
<?php

function a ()
{
    break;

    try
    {
    }
    catch (Exception $e)
    {
    }
    finally
    {
    }
}

This was with PHP version 5.5.5.

A: Differences between 2 PHP configs were indeed the root cause of the issue on my end. My app is based on the NuSOAP library.
On config 1 with PHP 5.2, it was running fine as PHP's SOAP extension was off.
On config 2 with PHP 5.3, it was giving "Connection Reset" errors as PHP's SOAP extension was on.
Switching the extension off allowed to get my app running on PHP 5.3 without having to rewrite everything.

A: I had an issue where in certain cases  PHP 5.4 + eAccelerator = connection reset.  There was no error output in any log files, and it only happened on certain URLs, which made it difficult to diagnose.   Turns out it only happened for certain PHP code / certain PHP files, and was due to some incompatibilities with specific PHP code and eAccelerator.  Easiest solution was to disable eAccelerator for that specific site, by adding the following to .htaccess file
php_flag eaccelerator.enable 0
php_flag eaccelerator.optimizer 0
(or equivalent lines in php.ini):
eaccelerator.enable="0"
eaccelerator.optimizer="0"

A: It's an old post, I know, but since I couldn't find the solution to my problem anywhere and I've fixed it, I'll share my experience.
The main cause of my problem was a file_exists() function call.
The file actually existed, but for some reason an extra forward slash on the file location ("//") that normally works on a regular browser, seems not to work in PHP. Maybe your problem is related to something similar. Hope this helps someone!

A: I'd try setting all of the error reporting options
 -b on error batch abort
-V severitylevel
-m error_level
and sending all the output to the client
<?php
echo "
starting sql batch
\n
"; flush();
passthru('sqlcmd -b -m -1 -V 11 -l 3 -E -S TYHSY-01 -d newtest201 -i "E:\PHP_N\M_Create_Log_SP.sql"');
echo '
done.'; flush();

A: My PHP was segfaulting without any additional information as to the cause of it as well. It turned out to be two classes calling each other's magic __call() method because both of them didn't have the method being called. PHP just loops until it's out of memory. But it didn't report the usual "Allowed memory size of * bytes exhausted" message, probably because the methods are "magic".

A: I thought I would add my own experience as well.
I was getting the same error message, which in my case was caused by a PHP error in an exception.
The culprit was a custom exception class that did some logging internally, and a fatal error occurred in that logging mechanism. This caused the exception to not be triggered as expected, and no meaningful message to be displayed either.


text:
Q: Плагин image2 (Enhanced Image) убирает нужный функционал из ckeditor Проблема в том, что при подключении плагина image2 (Enhanced Image) он убирает нужный мне функционал программы и функций диалогового окна становится заметно меньше. Сам плагин мне нужен, так что комментарии и ответы с "Удали этот плагин" не принимаются.
Функционал с image2 (Enhanced Image)

Функционал БЕЗ image2 (Enhanced Image)


text:
Q: Email with digital signature and embedded image I have the below working code for sending digitally signed emails. I have to insert a html based signature with a gif logo which should be pulled from the assembly resources. I have googled around and found Convert.ToBase64String() as possible solution but Outlook does not display the image.
The 2nd approach would be LinkedResource with AlternateView to embed my image, but I actually failed to get it work with the below code. I already have an AlternateView to send the email with the digital signature. Is it possible to somehow add the image as well?
So mailer(to, from, from_name, relay, subject, body, cc1, cc2);.
private void mailer(string toaddress, string fromaddress, string fromaddress_disp, string relays, string mailsubject, string bodytext, string ccman, string cccct)
{
    string certname = "";

    MailAddress from = new MailAddress(fromaddress, fromaddress_disp);
    MailAddress to = new MailAddress(toaddress);
    MailAddress cc_man = new MailAddress(ccman);
    MailAddress cc_cct = new MailAddress(cccct);
    MailMessage message = new MailMessage(from, to);
    message.CC.Add(cc_man);
    message.CC.Add(cc_cct);
    message.Subject = mailsubject;
    message.IsBodyHtml = true;
    string body = "Content-Type: text/html; charset=iso-8859-1 \r\nContent-Transfer-Encoding: 8bit\r\n\r\n" + bodytext;
    byte[] messageData = Encoding.ASCII.GetBytes(body);
    ContentInfo content = new ContentInfo(messageData);

    SignedCms Cms = new SignedCms(new ContentInfo(messageData));
    X509Store store = new X509Store(StoreLocation.CurrentUser);
    store.Open(OpenFlags.ReadOnly);

    RSACryptoServiceProvider csp = null;
    X509Certificate2Collection certCollection = store.Certificates;
    X509Certificate2 cert = null;
    foreach (X509Certificate2 c in certCollection)
    {
        if ((c.Subject.Contains("myEmailAddress")) && (c.FriendlyName.Contains("CompanyEmailDigSig")))
        {
            cert = c;
            break;
        }
    }

    if (cert != null)
    {
            csp = (RSACryptoServiceProvider)cert.PrivateKey;
    }
    else
    {
        throw new Exception("Valid certificate was not found");
    }

    CmsSigner Signer = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, cert);
    Cms.ComputeSignature(Signer);
    byte[] SignedBytes = Cms.Encode();
    MemoryStream signedStream = new MemoryStream(SignedBytes);
    AlternateView signedView = new AlternateView(signedStream, "application/pkcs7-mime; smime-type=signed-data; name=sig.p7m");
    message.AlternateViews.Add(signedView);
    SmtpClient client = new SmtpClient(relays);
    store.Close();

    try
    {
        client.Send(message);
    }
    catch (Exception ex)
    {
    //exception
    }
}

EDIT: I had to re-open this thread as the previously accepted answer is not good enough.

A: I do think that it is not possible to sign the entire message using System.Net.Mail. But this might also help you:- Send Email in C# Tutorial - SSL, HTML, Embedded Image, S/MIME
Also check this:-(Send Email with Embedded Images - ImportHtml - Example):-
using System;
using System.Collections.Generic;
using System.Text;
using EASendMail; //add EASendMail namespace

namespace mysendemail
{
    class Program
    {
        static void Main(string[] args)
        {
            SmtpMail oMail = new SmtpMail("TryIt");
            SmtpClient oSmtp = new SmtpClient();

            // Set sender email address, please change it to yours
            oMail.From = "test@emailarchitect.net";

            // Set recipient email address, please change it to yours
            oMail.To = "support@emailarchitect.net";

            // Set email subject
            oMail.Subject = "test html email with attachment";

            // Your SMTP server address
            SmtpServer oServer = new SmtpServer("smtp.emailarchitect.net");

            // User and password for ESMTP authentication, if your server doesn't require
            // User authentication, please remove the following codes.
            oServer.User = "test@emailarchitect.net";
            oServer.Password = "testpassword";

            // If your SMTP server requires SSL connection, please add this line
            // oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;

            try
            {
               // Import html body and also import linked image as embedded images.
               oMail.ImportHtml( "test  importhtml",
                    "c:\\my picture", //test.gif is in c:\\my picture
                    ImportHtmlBodyOptions.ImportLocalPictures | ImportHtmlBodyOptions.ImportCss );

                Console.WriteLine("start to send email with embedded image...");
                oSmtp.SendMail(oServer, oMail);
                Console.WriteLine("email was sent successfully!");
            }
            catch (Exception ep)
            {
                Console.WriteLine("failed to send email with the following error:");
                Console.WriteLine(ep.Message);
            }
        }
    }
}


text:
Q: How to retrieve full text tweets using tweepy? I am trying to scrape tweets from a user-defined Twitter profile. Having read previous posts I understand that the Twitter JSON has a section for extended tweets. I've added tweet_mode='extended' into my api.user_timeline section and changed .text to .full_text.
However, I am still getting truncated tweets. I understand that retweets have a full_text attribute but I am scraping the timeline and not separating tweets from retweets.
Is there a way to universally query tweets and retrieve the full_text version. I have included my code below.
screen_name_list = ['@x']

for name in screen_name_list:
    user = api.get_user(name)

    #initialize a list to hold all the tweepy Tweets
    alltweets = []

    #make initial request for most recent tweets (200 is the maximum allowed count)
    new_tweets = api.user_timeline(screen_name = name, count = 200,tweet_mode='extended', include_rts=True)

    #save most recent tweets
    alltweets.extend(new_tweets)

    #save the id of the oldest tweet less one
    oldest = alltweets[-1].id - 1

    #keep grabbing tweets until there are no tweets left to grab
    while len(new_tweets) > 0:
      print 'getting tweets before %s' % (oldest)

        #all subsiquent requests use the max_id param to prevent duplicates
        new_tweets = api.user_timeline(screen_name = name, count=200, max_id=oldest, tweet_mode='extended')

        #save most recent tweets
        alltweets.extend(new_tweets)

        #update the id of the oldest tweet less one
        oldest = alltweets[-1].id - 1

        print "...%s tweets downloaded so far" % (len(alltweets))

    #transform the tweepy tweets into a 2D array that will populate the csv
    outtweets = [[tweet.id_str, tweet.created_at, tweet.full_text.encode('utf-8')] for tweet in alltweets]
    tweet_time = [index[1] for index in outtweets]
    tweet_list = [index[2] for index in outtweets]

A: If you replace
tweet.full_text

with
tweet.retweeted_status.full_text if tweet.full_text.startswith("RT @") else tweet.full_text

you will get the full text of the retweet, albeit without the "RT" at the front, so you may also want to add another column in your CSV to indicate retweets, e.g.:
[1 if tweet.full_text.startswith("RT @") else 0] for tweet in alltweets


text:
Q: Keyboard up and down arrows I have one autocomplete search, in which by typing few characters it will show all the names, which matches the entered character. I am populating this data in the jsp using DIV tag, by using mouse I'm able to select the names. But I want to select the names in the DIV tag to be selected using the keyboard up and down arrow. Can anyone please help me out from this.

A: copy and paste this piece of code and try..

<input type="text" id="tb">

1

2

3

4

5

6

7

8

9

10

A: Use the onkeydown and onkeyup events to check for key press events in your results div:
var UP = 38;
var DOWN = 40;
var ENTER = 13;

var getKey = function(e) {
  if(window.event) { return e.keyCode; }  // IE
  else if(e.which) { return e.which; }    // Netscape/Firefox/Opera
};

var keynum = getKey(e);

if(keynum === UP) {
  //Move selection up
}

if(keynum === DOWN) {
  //Move selection down
}

if(keynum === ENTER) {
  //Act on current selection
}

A: I assume that you have an input which handles the input.
map onkeyup-eventhandler for that input in which you read out event.keyCode, and do stuff when it's the appropriate keycodes for up/down-arrow (38, 40), to keep a reference to which node (item in your div) you move the focus to.
Then call the same handler when you hit enter (keyCode 13) as you do onclick.
It's hard to give a coding-example because it highly depend on context, but a tip on how to navigate through your div is to make us of .nextSibling and .previousSibling, aswell as .firstChild and .childNodes.

A: Long time since I did this, but I guess you can use event.keyCode.
If the values returned are 38 and 40, then the user has pressed the up and down arrows respectively.
You then have to select the row above or below your current position. How to select the row would depend on your particular situation.


text:
Q: how to find asymptotic joint distribution of two linear combination of order statistics? Suppose I have n order statistics from some unknown continuous distribution funciton F(x), $X_{1}\leqslant X_{2}\leqslant...\leqslant X_{n}$. And I have two linear combination of these order statistics

*

*$S_{n}=n^{-1}\sum_{i=1}^{n}J_{1}(\frac{i}{n})X_{i}$ in the same manner as in Stigler (1974)

*$T_{n}=n^{-1}\sum_{i=1}^{n}J_{2}(\frac{i}{n})X_{i}$ in the same manner as in Stigler (1974) but with different function form of $J_{2}(\frac{i}{n})$

We assume that $S_{n}$ and $T_{n}$ are well behaved as in Stigler (1974) and both  are asymptotically normal distributed such that  $S_{n}\sim N(s,var1)$ and $T_{n}\sim N(t,var2)$.and depending on Stigler we know how to find var1 and var2.
I believe they are joint asymptotically multivariate normal distributed. My question is that how could I obtain the asymptotic covariance of $S_{n}$ and $T_{n}$ ? The original proof of Stigler only provides univariate case but not joint distribution.
Thank you so much.
Reference
(1) Stigler (1974), Linear Functions of Order Statistics with Smooth Weight Functions, Ann Stat.


text:
Q: Why do i have a multi-second delay in booting linux under vmware fusion? When booting Ubuntu 14.04 (Linux 3.13.0) under VMWare Fusion 7.1.0, booting is slower than i'd expect. In particular, once it has completed, looking at the timestamps in dmesg show some long pauses (2+ seconds) adjacent to messages about ACPI. How can i make it less slow? Is it doing anything in those pauses that i don't need and can disable/hint?
Here's the first pause (===> ~5s), and just before it, a mini-pause (---> ~600ms):
[    0.145333] ACPI: bus type PCI registered
[    0.145335] acpiphp: ACPI Hot Plug PCI Controller Driver version: 0.5
[    0.145489] PCI: MMCONFIG for domain 0000 [bus 00-7f] at [mem 0xf0000000-0xf7ffffff] (base 0xf0000000)
[    0.145490] PCI: MMCONFIG at [mem 0xf0000000-0xf7ffffff] reserved in E820
[    0.151776] PCI: Using configuration type 1 for base access
[    0.153045] bio: create slab <bio-0> at 0
[    0.154170] ACPI: Added _OSI(Module Device)
[    0.154172] ACPI: Added _OSI(Processor Device)
[    0.154173] ACPI: Added _OSI(3.0 _SCP Extensions)
[    0.154173] ACPI: Added _OSI(Processor Aggregator Device)
[    0.163605] [Firmware Bug]: ACPI: BIOS _OSI(Linux) query ignored
---> 0.762966] ACPI: Interpreter enabled
[    0.762980] ACPI Exception: AE_NOT_FOUND, While evaluating Sleep State [\_S2_] (20131115/hwxface-580)
[    0.762985] ACPI Exception: AE_NOT_FOUND, While evaluating Sleep State [\_S3_] (20131115/hwxface-580)
[    0.762994] ACPI: (supports S0 S1 S4 S5)
[    0.762996] ACPI: Using IOAPIC for interrupt routing
[    0.763031] PCI: Using host bridge windows from ACPI; if necessary, use "pci=nocrs" and report a bug
[    0.778294] ACPI: No dock devices found.
===> 5.789452] ACPI: PCI Root Bridge [PCI0] (domain 0000 [bus 00-7f])
[    5.789463] acpi PNP0A03:00: _OSC: OS supports [ExtendedConfig ASPM ClockPM Segments MSI]
[    5.789741] acpi PNP0A03:00: _OSC: platform does not support [AER]
[    5.789996] acpi PNP0A03:00: _OSC: OS now controls [PCIeHotplug PME PCIeCapability]

Here's the next pause (===> ~2.5s):
[    5.880797] ACPI: PCI Interrupt Link [LNKA] (IRQs 3 4 5 6 7 *9 10 11 14 15)
[    5.880852] ACPI: PCI Interrupt Link [LNKB] (IRQs 3 4 5 6 7 9 10 *11 14 15)
[    5.880904] ACPI: PCI Interrupt Link [LNKC] (IRQs 3 4 5 6 7 9 *10 11 14 15)
[    5.880956] ACPI: PCI Interrupt Link [LNKD] (IRQs 3 4 *5 6 7 9 10 11 14 15)
===> 8.417603] ACPI: Enabled 2 GPEs in block 00 to 0F
[    8.417615] ACPI: \_SB_.PCI0: notify handler is installed
[    8.418094] Found 1 acpi root devices
[    8.418615] vgaarb: device added: PCI:0000:00:0f.0,decodes=io+mem,owns=io+mem,locks=none

And the next (==> ~2.1s), apparently after scanning for devices:
[    8.468367] pnp 00:09: Plug and Play ACPI device, IDs PNP0700 (active)
[    8.468505] system 00:0a: [io  0xfce0-0xfcff] has been reserved
[    8.468507] system 00:0a: [mem 0xf0000000-0xf7ffffff] has been reserved
[    8.468508] system 00:0a: [mem 0xfe800000-0xfe9fffff] has been reserved
[    8.468510] system 00:0a: Plug and Play ACPI device, IDs PNP0c02 (active)
==> 10.526525] pnp: PnP ACPI: found 11 devices

A: As mentioned on the Arch Linux wiki, this appears to relate to the support for hot-adding memory to a running machine. If you don't need this (and i didn't), you can disable it with the following line in your .vmx file (there is probably already a "TRUE" in there; change it to "FALSE").
mem.hotadd = "FALSE"

This shaved 10 seconds off my boot time, bringing me down to a total of 10 seconds from the bootloader launching ubuntu to the graphical unity desktop being ready (with my user auto-logged-in). Here, you can see the message after that last delay above (===>) happens under the 1-second mark!
[    0.945859] pnp 00:09: Plug and Play ACPI device, IDs PNP0700 (active)
[    0.945996] system 00:0a: [io  0xfce0-0xfcff] has been reserved
[    0.945998] system 00:0a: [mem 0xf0000000-0xf7ffffff] has been reserved
[    0.946000] system 00:0a: [mem 0xfe800000-0xfe9fffff] has been reserved
[    0.946001] system 00:0a: Plug and Play ACPI device, IDs PNP0c02 (active)
===> 0.948847] pnp: PnP ACPI: found 11 devices


text:
Q: Select nth-child(n) except the first matching child I want to select all elements matching nth-child(2n) in a list except for the first matching element; for example...

li:nth-child(2n) {
  background: red;
}

li:nth-child(2) {
  background: none;
}

One

Two

Three

Four

Five

Six

Seven

Eight

Nine

Ten

The result of this is that only Four, Six, Eight and Ten have a red background color.
I would like to know if there's a better way of expressing the CSS rules though, and if it's possible to express as a single rule:
li:nth-child(2n) {
    background: red;
}

li:nth-child(2) {
    background: none;
}

Can these be combined and still behave the same way?

A: You can use a :not() pseudo-class to exclude the second nth child.
li:nth-child(2n):not(:nth-child(2)) {
  background: red;
}

A better way would be to use the An+B syntax for :nth-child() to select every second child starting with the fourth child.

li:nth-child(2n+4) {
  background: red;
}

One

Two

Three

Four

Five

Six

Seven

Eight

Nine

Ten

A: Sure, use li:nth-child(2n + 4).
The format of the nth-child selector is An+B, where:

*

*A is an integer step size,

*B is an integer offset,

*n is all nonnegative integers, starting from 0.

li:nth-child(2n + 4) {
  background: red;
}

One

Two

Three

Four

Five

Six

Seven

Eight

Nine

Ten

In the format (2n + 4), you're essentially starting from the fourth element (1 based index) and incrementing by two each time. So, 4, 6, 8, ...

A: CSS :nth-child Selectors -> You will find the answer below the README.
NOTE: Remember to scroll down to the bottom.
css-nth-child-selectors codes -> There is also a view of the entire file, separated by header.
I hope it will be useful for you.
The most appropriate for this situation would be the following:

li:nth-child(2n+4) {
    background: red;
}


text:
Q: DDD. Method on entity or service? I'm trying to use DDD when developing a new system. In this system I have places and I need to give access to places based on which adgroups you're a member of. I also need to get a list of allowed places from a list of adgroups.
I've come up with the following:
interface IPlaceRepository
{
  Places[] GetPlacesForGroups(AdGroup[] adGroups);
}

class AdGroup()
{
  string Name { get; private set; }
}

class Place
{
  string Name { get; private set; }
}

Now I need to add a function that grants a group access to a particular place. According to DDD which is the right way to do it? I have a two suggestions.
I assume that adgroups can be considered as value objects.

*

*Add a function to Place.

      void GiveAccessTo(AdGroup adGroup) { ... }

and add a function to IPlaceRepository.
  void AddGroupToPlace(Place p, Group g) { ... }

Then I need to inject the IPlaceRepository into Place for use inside GiveAccessTo.

*

*Another way maybe is to create an ISecurityService? I can think of a method like this on that service.

    void GiveAccessToPlace(AdGroup g, Place p)

In the same way as option 1 I need to implement a method on IPlaceRepository and inject the repository into the service.
Which is the DDD way to do this?

A: Repositories persist complete aggregates, normally you wouldn't have an AddGroupToPlace method.
Since ADGroup is a value object, you can use the GiveAccessTo method to add the groups to the Place aggregate. After doing that, you use the repository to persist the complete Place aggregate.
Services are mostly used when an operation spans multiple aggregates. This can often be avoided using events though.

A: (indirect answer)
Not sure if DDD has some rules specifically for your case. I would follow these steps:

*

*Draw on a paper pad the aggregates, paying attention to the root aggregate (which entity contains another one)

*Draw your queries

*List several approaches to store the list of allowed items

*Keep in mind how you would store this, in a document-oriented database or else where (this is where materialized view may complicate things)

*Several approaches can be valid, return to your queries and pick the best approach (memory consumption, speed, least number of items required to be queried)

*Separate security from business API, use Authorization pattern from the framework you use

*Only use white-listing (list all allowed resources, deny all by default)


text:
Q: Map a list of POJO to another type of list and then passing them to an add method I'm still learning RxJava and can't seem to solve how to iterate over a list and return a another mapped type of list. There after I'd like to call an add method to add the newly mapped type of list to my database.
If I use map() and then flatMap() directly after to add the new list to database it works if its a single object, but not for lists of stream data. That's why I tried with a toList() after map().
I've tried something like this below.
public Observable<List<Assignment>> query(){
    Log.d(TAG, "Fetching data remotely...");

    return mRetrofit.create(AssignmentService.class).GET("token")
        .map(item -> mTransformer.transform(item, Assignment.class))
        .flatMap(mAssignmentLocalDataStore::add);
}


text:
Q: Node JS Request + Express Pipe I have a problem with streaming video files from a server to another.
I wrote this script
var request = require("request"),
    express = require("express");

var app = express();

app.get("/cast", function(req, res) {

    var url = req.query.video;

    res.writeHead(200, {
        'Content-Type': 'video/mp4'
    });

    request({
        url: url,
        headers: {
            Referer: "http://example.com/1706398/" + url
        }
    })
        .on('response', function(response) {

            response.on('data', function(data) {
                console.log("data chunk received: " + data.length)
            });

            response.on('end', function(data) {
                console.log('Video completed');
            });

        })
        .pipe(res);

});

app.listen(8080);

But video response sometimes works sometimes is corrupted, instead if request's data is written in a writeable buffer and saved as video file  it works with any url.
I cannot found any error or problem in my code, here some urls :

Here some url that I tryed:
  https://gist.github.com/FrancisCan/f2bb86f8ff73b45fa192

Thanks :)

A: Remove the writeHead 200, when you are streaming, you should return http 206 results back (partial content), and not http200. I have the same scenario as you (streaming a video file from a blob container in the cloud to an angular application), there is no need for the http200 response.
Update: adding some code on how I do it:
AzureStorageHelper.prototype.streamBlob = function streamBlob(req, res, blob, params) {
    if(!params){
        params.container = container;
    }
    blob_service.getBlobProperties(params.container, blob, function (error, result, response) {
        if(!result) return res.status(404).end();
        if(error) return res.status(500).end();

        var blobLength = result.contentLength;
        var range = req.headers.range ? req.headers.range : "bytes=0-";
        var positions = range.replace(/bytes=/, "").split("-");
        var start = parseInt(positions[0], 10);
        var end = positions[1] ? parseInt(positions[1], 10) : blobLength - 1;
        var chunksize = (end - start) + 1;
        var options = {
            rangeStart: start,
            rangeEnd: end,
        }

        //this is what's interesting for your scenario. I used to set this up myself but it's is now handled by the Azure Storage NodejsSDK

        /*res.writeHead(206, {
            'Accept-Ranges': 'bytes',
            'Content-Range': "bytes " + start + "-" + end + "/" + blobLength,
            'Content-Type': result.contentType,
            'Content-Length': chunksize,
            'Content-MD5': result.contentMD5,
        });*/

        var options = {
            rangeStart: start,
            rangeEnd: end,
        }

//this is an API from the Azure Storage nodejsSDK I use. You might want to check the source of this method in github to see how this lib deals with the http206 responses and the piping
        blob_service.getBlobToStream(params.container, blob, res, options, function (error, result, response) {
            if (error) {
                return res.status(500).end();
            }
        });
    });


text:
Q: Maximum number of concurrent TCP/IP connections - Win XP SP3 Does anyone know what is the maximum number of concurrent TCP/IP connections on Windows XP SP3? I am trying to load test a machine and would like to know what is the max number of tcp connections that can be opened by an application (in my case, java application) towards that machine.

A: Note that often you may be limited by the number of outbound connections supported on the client machine rather than by the number of concurrent connections possible. See this Socket Bind Error for how to tune MAX_USER_PORT to enable more outbound connections from the machine running the tests.

A: I found some very useful information here:
http://smallvoid.com/article/winnt-tcpip-max-limit.html


text:
Q: How to create a System.Drawing.Image from a http image I'm not used to work with remote resources, so maybe this question is trivial, but I'm not sure how to implement it.
I need to load a collection of images that are placed in a http folder, for example http://www.myexsamplesite.com/images.
Inside this directory I could have N images with different names.
I need to show these images in a WinForms application (in a ListView).
The alternative that I'm studying is downloading the images to a tmp dir, and then load them from disk from my WinForms application. I'm using the following:
WebClient fileReader = new WebClient();
 fileReader.DownloadFile(imageAddress, filePath);

to download the files to disk. My question is:
How can I download all the files in the http folder? I guess that I need to enumerate the files in the folder and then download one to one.
The second question and most important. I'm sure that there is a much better mechanism to perform this task. So:
Is there any other way to get the http image content into a System.Drawing.Image?
Remember that I need to get all the files in the http folder.
Thanks in advance

A: First, to get all of the files, you need a way to enumerate them. HTTP does not have any method that lets you download a whole directory, or technically even list what's in a directory. Some web servers are set to send you a pre-defined web page which displays the list of files in a directory when it lacks a default page, but not all are. You could parse that content to get a list of the files you need to download. Otherwise, you'll need to find a way to get that info programmatically, based on the web application itself.
Second, you can load an image from a stream, as I recall. Instead of using WebClient, you can use HttpWebRequest so that you can access the content stream, and feed that into your constructor. However, I think it may be better/easier for you to use a temp directory and load the files from there. Sometimes unexpected things might happen when loading things from a network stream like this (for example, the stream of GIF images with animations is attempted to be kept open to continually read the frames of the animation), which could cause exceptions at odd times you might not be prepared to debug and understand off the bat.
Finally, note that you would only be using mime type here to verify that your content is an image - so you explicitly would not load something that is mime type application/octet-stream into an image object - but only things like image/jpeg, image/gif, image/png etc.


text:
Q: How to autocomplete when source code becomes invalid after user input? I am developing a VSCode extension offering autocompletion for a customized language. It intends to auto suggest based on what user is typing, using info from the compiler, e.g., previously defined variables. However, after user inputs, the source code often becomes invalid and contains syntax error. The compiler fails to parse it and thus cannot offer defined variables, which were available before user inputs. How to handle this kind of incremental change? Does such autocompletion require the compiler to tolerate errors to some extent? There is some discussion here, but is too broad and not conclusive.

A: A parser is not the right tool for code completion, because it requires syntactically correct input, which is almost never available when code completion is required. You could of course cache info from a previous parse run and update this only when the code reaches a valid state from time to time, but this is not going to work well. What would you show when the user just started to write the code (since there was no previous good run)?
Instead I used a different approach in my Code Completion Core for ANTLR4 (antlr4-c3): I use the provied ATN (Augmented Transition Network) to find the current caret position and then look ahead to possible tokens that could follow. This gives you already all possible lexems (numbers, IDs, keywords etc.). If you want to give more details (e.g. class names, variables etc.) a bit more processing is required.
By using a manual walk over the ATN you can at least handle partially correct code. An important requirement is that the code from the beginning until the caret position must be correct, but everything after that can be imperfect.
I use this code completion core for my vscode extension vscode-antlr4, where it works pretty well.


text:
Q: What is the best way to get access to text message inbox programmatically in android I have searched on many sites and blogs for my query. I am confused about what is the best way to import text messages from mobile's inbox into my application. Some recommends SmsManager and some say via content providers.

A: Sounds like you want to use a content resolver.
Short explaination:

*

*Use SMSManager to send sms. Example

*Use ContentResolver to read all existing SMS. Example

*Use BroadcastReceiver to read new incomming SMS. Example
Here is a good SO question which explains how to retrieve SMS from inbox.


text:
Q: compare source control with SQL Database I would like to create a tool to compare my SQL Development Database with Source control repository and create a deployment script to sync both. But I don't have any idea how to proceed. Any suggestions please

A: You have a couple of options, the first is paid you can do it with the Redgate SQL Compare tool or you can get SSDT, create a database project, add your code to it and use that to do the sync (either use sqlpackage or schema compare).
My personal preference is SSDT but the RG paid for solution is simpler.

A: Do you have a file-based source control such as SVN, Git, Perforce to manage your database objects?
With database code deployment using file-based version control repository will cause the following issues:

*

*If a developer copies an artifact generated locally to the test
environment, the next deployment will override this out-of-process
change.

*Developer can forget to update the source control repository after
debugging in the database.

Those source control do not act as the single source of truth because anyone can login to the database and produce a change and forget to apply it in the relevant script of the file-based version control.
What's needed for the database is baseline aware analysis. I recommend you download this white paper for a full discussion on this subject.


text:
Q: Compiling tcpsplice on a 64-bit machine I am trying to compile a small utility called tcpslice.  It's the typical GNU C application.  When I run ./configure, here is the output:

checking build system type... Invalid configuration `x86_64-pc-linux-gnuoldld': machine `x86_64-pc' not recognized
configure: error: /bin/sh ./config.sub x86_64-pc-linux-gnuoldld failed

It appears to not support compilation as a 64-bit Linux application.  So I have a few questions:

*

*Is it possible to set some flags to compile the application as 32-bit AND be able to run it on my 64-bit operating system?

*Is it possible to update the configure script to support 64-bit Linux?  If so, will I be making some serious code changes in the .c files as well?

*I noticed a 64-bit RHEL6 machine on my network has this utility installed and running with an identical version number (1.2a3).  Could I somehow download the source that was used to build it?  I can get access the to RHN if necessary.

A:
Is it possible to set some flags to compile the application as 32-bit AND be  able to run it on my 64-bit operating system?

Yes. -m32 is the option.

Is it possible to update the configure script to support 64-bit Linux? If so,  will I be making some serious code changes in the .c files as well?

You will have to make some code changes to make a purely 32 bit application work on 64 bit. Here's a link that talks about porting code from 32 bit to 64 bit.
I am sorry, I do not know the answer for your 3rd question.
Hope the little information provided by me helps in some way.

A: You've misinterpreted what the configure script is telling you. The solution has nothing to do with CPU bitness.
The error comes down to a too-old version of config.guess, which the package creator generated with libtoolize. To fix it, you will need to have libtool installed, then say:
$ libtoolize --force

You'll find that configure now runs, because libtoolize overwrote the tarball version of config.guess with one appropriate to your system.
You may run into another problem, a "missing" bpf.h file. Just edit tcpslice.c and change this line:
#include <net/bpf.h>

to:
#include <pcap-bpf.h>

With those two changes, I got tcpslice to build on my 64-bit CentOS 5 box.

A: install following packages :
 $apt-get install ia32-libs.

for rhel its different :
look at the answer to this question :
CentOS 64 bit bad ELF interpreter


text:
Q: The material is considered to have passed the test if no antibodies to the mentioned viruses are (were, have been) detected From a Russian text I'm translating into English:

The material is considered to have passed the test if no antibodies to the mentioned viruses are detected.

Can I use were here:

The material is considered to have passed the test if no antibodies to the mentioned viruses were detected.

or would this transform the sentence into the "second conditional", making the situation "unreal and unlikely"?
For some reason, are feels not very suitable to me. Maybe it's better to use have been?

The material passes the test if no antibodies to the mentioned viruses have been detected.

Or maybe are and have been are both suitable in this case?

A: The prinicipal difference between these tenses is as follows:
are (present simple) is appropriate if you wish to state a general truth.

If you heat ice, it melts

were (past simple) is appropriate if you wish to describe the result of the test after it was fully completed, and the result is still valid today.
have been (present perfect) is appropriate if the tests are ongoing: no antiodies have been detected to date, and so the material passes the test at the moment, but it is possible that antibodies may be detected tomorrow.
are and were are therefore appropriate if you consider the results of the test to be final, whereas have been is only necessary if the tests are ongoing, and either it is possible for the test to fail to detect antibodies even though the virus is present, or if the material could be infected with the virus at some time in the future.
You might, for example, use present perfect when talking about tests on a water supply that is subject to constant monitoring:

The water is considered safe for drinking if the pathogen oocyte count has not exceeded x per litre in the past 24 hours.

A: English language rules tend to be bent a bit for different literature styles. For scientific literature, such as in a publication, when you are describing the method of an experiment (which seems to be the case here) the past tense is infinitely preferable. This always seems to be unnatural to my colleagues who feel they were meant to be instructing readers how to carry out a future repeat of the experiment, but that's the way it is (the abstract, however, can be different).
As to "were" or "have been", I know there isn't the distinction in Russian so it makes it difficult. It will depend on how you (or the authors if you can get in touch) view the test and the detection. Do you see the detection as happening at a certain point in time or measured over a period of time? If the former, then use "were", otherwise use "have been".
As an aside, scientific literature is the perfect environment for venting a love of the passive voice. When you consider it, in taking an objective standpoint and reporting observations, it's the objects and the action that is important. To pen a subject (cause) can be presumptuous before conclusive evidence is presented and as such the passive voice, with its shift of emphasis from the subjective subject, is frequently the ideal candidate.


text:
Q: Is there a zero [ 0 ] constant somewhere in any Microsoft .NET class? I'm just curious and I know it's not of much value, but here it goes...
I think that I have seen something like that somewhere but I'm not sure.
I mean something like this:
var zero = Class.Zero;

I tried looking at the Math class but it's not there.
I also know that I can use an unsigned value type like ushort.Min to get a Zero ( 0 ) value; it's not what I'm asking here... :D

A: The .Net Framework doesn't define constants for values like 0.  If you want to use 0 just use 0
Defined numeric constants in the .Net Framework typically revolve around the limits of a given numeric type, values which hold special relevance or cases where the zero value requires special / complex initialization.  For example

*

*Int32.Max

*Int32.Min

*Double.NaN

The literal 0 doesn't fit these categories for most numeric types (Decimal being one exception)

A: Some immutable reference types have pre-defined instances for "empty" values.  String, for example, defines String.Empty.  This is done because a valid String--even one with no characters--must reference a valid heap object, but if there are a thousand empty String variables they may all refer to the same heap object.  Unless an application doesn't happen to use any empty strings at all, creating one empty-string instance at application startup and allowing it to be shared among everyone who needs an empty string will be more efficient than creating a new empty string object every time one is needed.
No such benefit would exist with value types.  Although there are some value-type constants declared (e.g. Math.Pi), their declaration is for convenience, not efficiency.  Saying "myDouble = Math.Pi" is no more efficient than "MyDouble = 3.14159265358979323846264338327950288419716939937510#"--it's just easier to read and validate (would anyone looking at the above code notice if the first "328" were mistyped as "238")?  If one wants a floating-point constant zero, the most natural and easiest-to-read notation would simply be 0#.

A: Do you mean default(T)?
int zero = default(int);

This represents the default value for a given type, for int this is 0. You should not use this if you know already you need zero though, only in the case that you have a type at run time for which you need the default value.

A: There's one for Decimal.Zero and a few other more complex types like TimeSpan.Zero, IntPtr.Zero and BigInteger.Zero. But for regular numeric types, just use 0.


text:
Q: IBM Cloud: Required IAM access policy to see user-specific authorizations (policies)? In IBM Cloud, I have an IAM Access Group for security admins. What policy do I need to grant to have their members READ access to user-specific authorizations, i.e., access policies granted to a user, not an Access Group?
The account owner can see those authorizations by, e.g., the List Policies API. The security admin, when calling that API, either receives an empty list or only a partial list. The Access Group for security admins already has Administrator privilege for IAM Identity Service and IAM Access Group Service.

A: If the policies are based on a resource group you might need Viewer access to the resource group.  In terraform it would be something like this:
resource "ibm_iam_access_group_policy" "shared_policy" {
  access_group_id = ibm_iam_access_group.shared.id
  roles           = ["Viewer"]
  resources {
    resource_type = "resource-group"
    resource      = ibm_resource_group.shared.id
  }
}

New resource groups could be added in the future...

A: To see access policies, the security administrators and hence their related Access Group need *Viewer* privilege on all resources and services that are directly "authorized" to users or service IDs. It is not enough to have Viewer or even Administrator role on IAM Access Groups Service, Viewer on all Account Management as well as on all IAM-enabled services is required.
The following would give Viewer on Account Management services when using Terraform:
resource "ibm_iam_access_group_policy" "cloud-security-admins-account_viewer" {
  access_group_id = ibm_iam_access_group.cloud-security-admins.id
  account_management = true
  roles = [ "Viewer" ]
}

And the next Terraform snippet could be used to give Viewer on all IAM-enabled services:
resource "ibm_iam_access_group_policy" "cloud-security-admins-viewall-resources" {
  access_group_id = ibm_iam_access_group.cloud-security-admins.id
  roles = [ "Viewer" ]
    resources {
    resource_type = "resource-group"
  }
}


text:
Q: Python append() vs. + operator on lists, why do these give different results? Why do these two operations (append() resp. +) give different results?
>>> c = [1, 2, 3]
>>> c
[1, 2, 3]
>>> c += c
>>> c
[1, 2, 3, 1, 2, 3]
>>> c = [1, 2, 3]
>>> c.append(c)
>>> c
[1, 2, 3, [...]]
>>>

In the last case there's actually an infinite recursion. c[-1] and c are the same. Why is it different with the + operation?

A: Python lists are heterogeneous that is the elements in the same list can be any type of object. The expression: c.append(c) appends the object c what ever it may be to the list. In the case it makes the list itself a member of the list.
The expression c += c adds two lists together and assigns the result to the variable c. The overloaded + operator is defined on lists to create a new list whose contents are the elements in the first list and the elements in the second list.
So these are really just different expressions used to do different things by design.

A: The method you're looking for is extend(). From the Python documentation:
list.append(x)
    Add an item to the end of the list; equivalent to a[len(a):] = [x].

list.extend(L)
    Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L.

list.insert(i, x)
    Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).

A: The concatenation operator + is a binary infix operator which, when applied to lists, returns a new list containing all the elements of each of its two operands. The list.append() method is a mutator on list which appends its single object argument (in your specific example the list c) to the subject list. In your example this results in c appending a reference to itself (hence the infinite recursion).
An alternative to '+' concatenation
The list.extend() method is also a mutator method which concatenates its sequence argument with the subject list. Specifically, it appends each of the elements of sequence in iteration order.
An aside
Being an operator, + returns the result of the expression as a new value. Being a non-chaining mutator method, list.extend() modifies the subject list in-place and returns nothing.
Arrays
I've added this due to the potential confusion which the Abel's answer above may cause by mixing the discussion of lists, sequences and arrays.
Arrays were added to Python after sequences and lists, as a more efficient way of storing arrays of integral data types. Do not confuse arrays with lists. They are not the same.
From the array docs:
Arrays are sequence types and behave very much like lists, except that the type of objects stored in them is constrained. The type is specified at object creation time by using a type code, which is a single character.

A: you should use extend()
>>> c=[1,2,3]
>>> c.extend(c)
>>> c
[1, 2, 3, 1, 2, 3]

other info: append vs. extend

A: append is appending an element to a list. if you want to extend the list with the new list you need to use extend.
>>> c = [1, 2, 3]
>>> c.extend(c)
>>> c
[1, 2, 3, 1, 2, 3]

A: See the documentation:

list.append(x)

*

*Add an item to the end of the list; equivalent to a[len(a):] = [x].

  list.extend(L)
   - Extend the list by appending all the items in the given list;
  equivalent to a[len(a):] = L.

c.append(c) "appends" c to itself as an element. Since a list is a reference type, this creates a recursive data structure.
c += c is equivalent to extend(c), which appends the elements of c to c.

A: To explain "why":
The + operation adds the array elements to the original array. The array.append operation inserts the array (or any object) into the end of the original array, which results in a reference to self in that spot (hence the infinite recursion in your case with lists, though with arrays, you'd receive a type error).
The difference here is that the + operation acts specific when you add an array (it's overloaded like others, see this chapter on sequences) by concatenating the element. The append-method however does literally what you ask: append the object on the right-hand side that you give it (the array or any other object), instead of taking its elements.
An alternative
Use extend() if you want to use a function that acts similar to the + operator (as others have shown here as well). It's not wise to do the opposite: to try to mimic append with the + operator for lists (see my earlier link on why). More on lists below:
Lists
[edit] Several commenters have suggested that the question is about lists and not about arrays. The question has changed, though I should've included this earlier.
Most of the above about arrays also applies to lists:

*

*The + operator concatenates two lists together. The operator will return a new list object.

*List.append does not append one list with another, but appends a single object (which here is a list) at the end of your current list. Adding c to itself, therefore, leads to infinite recursion.

*As with arrays, you can use List.extend to add extend a list with another list (or iterable). This will change your current list in situ, as opposed to +, which returns a new list.

Little history
For fun, a little history: the birth of the array module in Python in February 1993. it might surprise you, but arrays were added way after sequences and lists came into existence.


text:
Q: Can't compile nginx with SSL support, OpenSSL not found I'm trying to compile nginx from source with the SSL module enabled. When I run this command:
./configure --with-http_ssl_module

it does its usual checks to see if everything is installed correctly, and then this pops up:

checking for OpenSSL library ... not found
./configure: error: SSL modules require the OpenSSL library. You can
  either do not enable the modules, or install the OpenSSL library into
  the system, or build the OpenSSL library statically from the source
  with nginx by using --with-openssl= option.

I know for a fact that OpenSSL is installed, because when I do openssl version I get OpenSSL 1.0.1 14 Mar 2012
So I'm pretty stumped. I thought maybe OpenSSL isn't isntalled in its default location, which is why nginx can't find it, but I have no idea where this is as it came pre-installed with the server. How can I find out where this is?
The server is running Ubuntu 12.04 LTS.
Thanks.

A: Most likely you're missing the libssl-dev package.
But why not save yourself all the trouble and just use a PPA for nginx?

A: I used the following to get openssl for nginx:
https://ethitter.com/2016/06/nginx-openssl-1-0-2-http-2-alpn/
All other attempts either did not work, or were to clunky.
Hope this helps another...

A: In case you want to check that libssl is installed in the right place, you can type which openssl and then ldd /path/to/openssl.

A: Even when OpenSSL is already installed (brew install openssl), configure itself suggests a workaround, which worked for me:
./configure --with-http_ssl_module --add-module=../nginx-rtmp-module-master--with-openssl=~/GitHub/openssl/openssl

A: If anyone still facing issue compiling nginx from source with the pcre related error, compile with "--with-pcre" attribute. And for providing pcre path, don't provide installed path. Provide pcre software path.

*

*Install pcre with

./configure
make
sudo make install

Then, provide the path of pcre source path.
./configure --prefix=/path/to/nginxToBeInstalled/mayBeInOpt/nginx-1.16.0/ --with-openssl=/path/to/installed/openssl-1.1.1b/ --with-pcre=/path/to/your/downloaded/extracted/pcre-8.42

In my case,
./configure --prefix=/opt/nginx-1.16.0/ --with-openssl=/opt/openssl-1.1.1b/ --with-pcre=/media/username/personal/Software/pcre-8.42

Thank you.

A: You have to specify the path were OpenSSL libraries set add it like this
PKG_CONFIG_PATH="/usr/lib/x86_64-linux-gnu/pkgconfig/" ./configure \

I found it path by searching for openssl.pc file  find / -name 'openssl.pc' reference


text:
Q: Q: In self-executing function, Who is assigned the number 10 I saw an interview question online:

function b() {
    b = 5
    console.log(b) // 5
}
b()
console.log(b) // 5

var a = 20
var c = (function a() {
    a = 10
    console.log(a) // f a() { a = 10; console.log(a) }
})()
console.log(a) // 20

Why does console.log(a) print function a() { a = 10; console.log(a) } instead of 10?