问:
How to have a picture randomly get chosen?
I have 4 pictures and what I want them to do is one of them, by random, is appeared and the others are not. How to do this?</p>

答:
```<code>window.onload = choosePic;
var myPix = new Array("images/lion.jpg","images/tiger.jpg","images/bear.jpg");
function choosePic() {
 var randomNum = Math.floor(Math.random() * myPix.length);
 document.getElementById("myPicture").src = myPix[randomNum];}
</code>```

To display a random image:

var myPix = new Array("images/lion.jpg", "images/tiger.jpg", "images/bear.jpg");

Here we build an array of three images, and stuff it into the variable myPix.

var randomNum = Math.floor(Math.random() * myPix.length);

The variable called randomNum gets the value of a math expression that’s best read from the inside outwards. Math.random generates a random number between 0 and 1, which is then multiplied by myPix.length, which is the number of items in the array (in this case, it’s 3). Math.floor rounds the result down to an integer, which means that the number must be between 0 and 2.

document.getElementById("myPicture").src = myPix[randomNum];

This says that the source of the image myPicture is set based on the array myPix, and the value at this moment is dependent on the value of randomNum.

Body:
window.onload = choosePic;
var myPix = new Array("images/lion.jpg","images/tiger.jpg","images/bear.jpg");
function choosePic() {
 var randomNum = Math.floor(Math.random() * myPix.length);
 document.getElementById("myPicture").src = myPix[randomNum];}

To display a random image:

var myPix = new Array("images/lion.jpg", "images/tiger.jpg", "images/bear.jpg");

Here we build an array of three images, and stuff it into the variable myPix.

var randomNum = Math.floor(Math.random() * myPix.length);

The variable called randomNum gets the value of a math expression that’s best read from the inside outwards. Math.random generates a random number between 0 and 1, which is then multiplied by myPix.length, which is the number of items in the array (in this case, it’s 3). Math.floor rounds the result down to an integer, which means that the number must be between 0 and 2.

document.getElementById("myPicture").src = myPix[randomNum];

This says that the source of the image myPicture is set based on the array myPix, and the value at this moment is dependent on the value of randomNum.


来源: stackexchange

问:
Unable to use for loop against array data in Yii2
I have a variable $data in my controller. In which I am getting the following result

```<code>Array( [0] => 99 [1] => 100 [2] => 101 [3] => 102 [4] => 103)
</code>```

Now I want to get the single entry one by one by using for loop. The main purpose of this loop is that I want to insert these values in my DB table.

```<code> if(Yii::$app->request->isAjax && Yii::$app->request->post())
    {
        $data = explode(',',$_POST['data']);

       for($i=0; $i<=count($data); $i++)
        {
            print_r($data[$i]);
        }
        //print_r($data);
    }
    else{
        echo 'no data';
    }
    exit();
</code>```

When i Run this one, I am getting the error

500 Internal Server Error
  PHP Notice 'yii\base\ErrorException' with message 'Undefined offset: 5'

Stack Trace

```<code>Stack trace:
#0 E:\xampp\htdocs\inventory-
web\backend\controllers\OgpheaderController.php(170): yii\base\ErrorHandler-
>handleError(8, 'Undefined offse...',
'E:\\xampp\\htdocs...', 170, Array)
#1 [internal function]: backend\controllers\OgpheaderController-
>actionViewsetpdf('55')
#2 E:\xampp\htdocs\inventory-
web\vendor\yiisoft\yii2\base\InlineAction.php(57):
call_user_func_array(Array, Array)
#3 E:\xampp\htdocs\inventory-
web\vendor\yiisoft\yii2\base\Controller.php(156): yii\base\InlineAction-
>runWithParams(Array)
#4 E:\xampp\htdocs\inventory-web\vendor\yiisoft\yii2\base\Module.php(523):
yii\base\Controller->runAction('viewsetpdf', Array)
#5 E:\xampp\htdocs\inventory-
web\vendor\yiisoft\yii2\web\Application.php(102): yii\base\Module-
>runAction('ogpheader/views...', Array)
#6 E:\xampp\htdocs\inventory-
web\vendor\yiisoft\yii2\base\Application.php(380): yii\web\Application-
>handleRequest(Object(yii\web\Request))
#7 E:\xampp\htdocs\inventory-web\backend\web\index.php(17):
yii\base\Application->run()
#8 {main}```
```

I have searched for this error solution but couldn't find the correct answer(s).

Any help would be highly appreciated.

答:
change your code to

```<code>for($i=0; $i<count($data); $i++)
{
  print_r($data[$i]);
}
</code>```

Array has total 5 elements which start with index 0 and end with 4 and when you compare count with <= it go to the index 5.

ContentLicense: CC BY-SA 3.0

Body:
I have a variable $data in my controller. In which I am getting the following result

Array( [0] => 99 [1] => 100 [2] => 101 [3] => 102 [4] => 103)

Now I want to get the single entry one by one by using for loop. The main purpose of this loop is that I want to insert these values in my DB table.

 if(Yii::$app->request->isAjax && Yii::$app->request->post())
    {
        $data = explode(',',$_POST['data']);

       for($i=0; $i<=count($data); $i++)
        {
            print_r($data[$i]);
        }
        //print_r($data);
    }
    else{
        echo 'no data';
    }
    exit();

When i Run this one, I am getting the error

500 Internal Server Error
  PHP Notice 'yii\base\ErrorException' with message 'Undefined offset: 5'

Stack Trace

Stack trace:
#0 E:\xampp\htdocs\inventory-
web\backend\controllers\OgpheaderController.php(170): yii\base\ErrorHandler-
>handleError(8, 'Undefined offse...',
'E:\\xampp\\htdocs...', 170, Array)
#1 [internal function]: backend\controllers\OgpheaderController-
>actionViewsetpdf('55')
#2 E:\xampp\htdocs\inventory-
web\vendor\yiisoft\yii2\base\InlineAction.php(57):
call_user_func_array(Array, Array)
#3 E:\xampp\htdocs\inventory-
web\vendor\yiisoft\yii2\base\Controller.php(156): yii\base\InlineAction-
>runWithParams(Array)
#4 E:\xampp\htdocs\inventory-web\vendor\yiisoft\yii2\base\Module.php(523):
yii\base\Controller->runAction('viewsetpdf', Array)
#5 E:\xampp\htdocs\inventory-
web\vendor\yiisoft\yii2\web\Application.php(102): yii\base\Module-
>runAction('ogpheader/views...', Array)
#6 E:\xampp\htdocs\inventory-
web\vendor\yiisoft\yii2\base\Application.php(380): yii\web\Application-
>handleRequest(Object(yii\web\Request))
#7 E:\xampp\htdocs\inventory-web\backend\web\index.php(17):
yii\base\Application->run()
#8 {main}

I have searched for this error solution but couldn't find the correct answer(s).

Any help would be highly appreciated.

Body:
change your code to

for($i=0; $i<count($data); $i++)
{
  print_r($data[$i]);
}

Array has total 5 elements which start with index 0 and end with 4 and when you compare count with <= it go to the index 5.


问:
Match string between two words in DataFrame
I have a DataFrame and one of the columns contains a text from which I want to extract some information.

I have two words: 'Type' and 'Capacity', between them is a string of numeric and non-numeric characters + white spaces are possible - I want to save that to a new column.

This is my code

```<code>df['new'] = df['text'].apply(lambda x: re.search(r'Type (\w+) Capacity', x).group(1))
print (df['new'])
</code>```

It doesn't give me errors, but prints out this:

Series([], Name: test, dtype: object)

I don't understand what is wrong. Thanks for help

答:
You can use

```<code>df['new'] = df['text'].str.extract(r'Type (\w+) Capacity')
</code>```

The pandas.Series.str.extract method will only return the captured values (those matched with parenthetical pattern parts).

You may also pass expand=True if you want to make sure a data frame only is returned (or False to get Series/Index/DataFrame), and if you have no matches on some rows, .fillna('') may be useful.

Body:
I have a DataFrame and one of the columns contains a text from which I want to extract some information.

I have two words: 'Type' and 'Capacity', between them is a string of numeric and non-numeric characters + white spaces are possible - I want to save that to a new column.

This is my code

df['new'] = df['text'].apply(lambda x: re.search(r'Type (\w+) Capacity', x).group(1))
print (df['new'])

It doesn't give me errors, but prints out this:

Series([], Name: test, dtype: object)

I don't understand what is wrong. Thanks for help

Body:
You can use

df['new'] = df['text'].str.extract(r'Type (\w+) Capacity')

The pandas.Series.str.extract method will only return the captured values (those matched with parenthetical pattern parts).

You may also pass expand=True if you want to make sure a data frame only is returned (or False to get Series/Index/DataFrame), and if you have no matches on some rows, .fillna('') may be useful.


问:
WPF Custom Buttons below ListBox Items
WPF Experts -

I am trying to add buttons below my custom listbox and also have the scroll bar go to the bottom of the control.  Only the items should move and not the buttons.  I was hoping for some guidance on the best way to achieve this.  I was thinking the ItemsPanelTemplate needed to be modified but was not certain.

Thanks

My code is below

```<code>   <!-- List Item Selected -->
    <LinearGradientBrush x:Key="GotFocusStyle"  EndPoint="0.5,1" StartPoint="0.5,0">
        <LinearGradientBrush.GradientStops>
            <GradientStop Color="Black" Offset="0.501"/>
            <GradientStop Color="#FF091F34"/>
            <GradientStop Color="#FF002F5C" Offset="0.5"/>
        </LinearGradientBrush.GradientStops>
    </LinearGradientBrush>

    <!-- List Item Hover -->
    <LinearGradientBrush x:Key="MouseOverFocusStyle" StartPoint="0,0" EndPoint="0,1">
        <LinearGradientBrush.GradientStops>
            <GradientStop Color="#FF013B73" Offset="0.501"/>
            <GradientStop Color="#FF091F34"/>
            <GradientStop Color="#FF014A8F" Offset="0.5"/>
            <GradientStop Color="#FF003363" Offset="1"/>
        </LinearGradientBrush.GradientStops>
    </LinearGradientBrush>

    <!-- List Item Selected -->
    <LinearGradientBrush x:Key="LostFocusStyle" EndPoint="0.5,1" StartPoint="0.5,0">
        <LinearGradientBrush.RelativeTransform>
            <TransformGroup>
                <ScaleTransform CenterX="0.5" CenterY="0.5"/>
                <SkewTransform CenterX="0.5" CenterY="0.5"/>
                <RotateTransform CenterX="0.5" CenterY="0.5"/>
                <TranslateTransform/>
            </TransformGroup>
        </LinearGradientBrush.RelativeTransform>
        <GradientStop Color="#FF091F34" Offset="1"/>
        <GradientStop Color="#FF002F5C" Offset="0.4"/>
    </LinearGradientBrush>

    <!-- List Item Highlight -->
    <SolidColorBrush x:Key="ListItemHighlight" Color="#FFE38E27" />

    <!-- List Item UnHighlight -->
    <SolidColorBrush x:Key="ListItemUnHighlight" Color="#FF6FB8FD" />

    <Style TargetType="ListBoxItem">
        <EventSetter Event="GotFocus" Handler="ListItem_GotFocus"></EventSetter>
        <EventSetter Event="LostFocus" Handler="ListItem_LostFocus"></EventSetter>
    </Style>

    <DataTemplate x:Key="CustomListData" DataType="{x:Type ListBoxItem}">
        <Border BorderBrush="Black" BorderThickness="1"  Margin="-2,0,0,-1">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBoxItem}}, Path=ActualWidth}" />
                </Grid.ColumnDefinitions>
                <Label
                        VerticalContentAlignment="Center" BorderThickness="0" BorderBrush="Transparent"
                        Foreground="{StaticResource ListItemUnHighlight}"
                        FontSize="24"
                        Tag="{Binding .}"
                        Grid.Column="0"
                        MinHeight="55"
                        Cursor="Hand"
                        FontFamily="Arial"
                        FocusVisualStyle="{x:Null}"
                        KeyboardNavigation.TabNavigation="None"
                        Background="{StaticResource LostFocusStyle}"
                        MouseMove="ListItem_MouseOver"
                        >
                    <Label.ContextMenu>
                        <ContextMenu Name="editMenu">
                            <MenuItem Header="Edit"/>
                        </ContextMenu>
                    </Label.ContextMenu>
                    <TextBlock Text="{Binding .}" Margin="15,0,40,0" TextWrapping="Wrap"></TextBlock>
                </Label>
                <Image
                    Tag="{Binding .}"
                    Source="{Binding}"
                    Margin="260,0,0,0"
                    Grid.Column="1"
                    Stretch="None"
                    Width="16"
                    Height="22"
                    HorizontalAlignment="Center"
                    VerticalAlignment="Center"
                    />
            </Grid>
        </Border>
    </DataTemplate>

</Window.Resources>

<Window.DataContext>
    <ObjectDataProvider ObjectType="{x:Type local:ImageLoader}"  MethodName="LoadImages"  />
</Window.DataContext>

<ListBox ItemsSource="{Binding}" Width="320" Background="#FF021422" BorderBrush="#FF1C4B79" >

    <ListBox.Resources>
        <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}">Transparent</SolidColorBrush>

        <Style TargetType="{x:Type ListBox}">
            <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled" />
            <Setter Property="ItemTemplate" Value="{StaticResource CustomListData }" />
        </Style>

    </ListBox.Resources>

</ListBox>
</code>```

答:
I know I'm joing the party rather late, but you should be able to accomplish this by applying a custom ScrollViewier control template to be used by the ListBox. I have not tested this, but it should work (or at least offer a starting point):</p>

```<code>    <ListBox ...>
    <ListBox.Resources>
        <Style TargetType="ScrollViewer">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="ScrollViewer">
                        <Grid>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition />
                                <ColumnDefinition Width="Auto" />
                            </Grid.ColumnDefinitions>
                            <Grid.RowDefinitions>
                                <RowDefinition />
                                <RowDefinition Height="Auto" />
                                <RowDefinition Height="Auto" />
                            </Grid.RowDefinitions>

                            <!-- Items Go Here -->
                            <ScrollContentPresenter Grid.Column="0" />

                            <!-- Buttons Go Here -->
                            <Grid Grid.Column="0"
                                  Grid.Row="1"
                                  >
                                  ...
                            </Grid>

                            <!-- ScrollBar spans all three rows but should only affect the presenter -->
                            <ScrollBar x:Name="PART_VerticalScrollBar"
                                        Grid.Column="1"
                                        Grid.Row="0"
                                        Grid.RowSpan="3"
                                        Value="{TemplateBinding VerticalOffset}"
                                        Maximum="{TemplateBinding ScrollableHeight}"
                                        ViewportSize="{TemplateBinding ViewportHeight}"
                                        Visibility="{TemplateBinding ComputedVerticalScrollBarVisibility}"
                                        />

                            <ScrollBar x:Name="PART_HorizontalScrollBar"
                                        Grid.Column="0"
                                        Grid.Row="1"
                                        Orientation="Horizontal"
                                        Value="{TemplateBinding HorizontalOffset}"
                                        Maximum="{TemplateBinding ScrollableWidth}"
                                        ViewportSize="{TemplateBinding ViewportWidth}"
                                        Visibility="{TemplateBinding ComputedHorizontalScrollBarVisibility}"
                                        />
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </ListBox.Resources>
</ListBox>
</code>```

ContentLicense: CC BY-SA 4.0

Title: WPF Custom Buttons below ListBox Items

Body:
WPF Experts -

I am trying to add buttons below my custom listbox and also have the scroll bar go to the bottom of the control.  Only the items should move and not the buttons.  I was hoping for some guidance on the best way to achieve this.  I was thinking the ItemsPanelTemplate needed to be modified but was not certain.

Thanks

My code is below

    <LinearGradientBrush x:Key="GotFocusStyle"  EndPoint="0.5,1" StartPoint="0.5,0">
        <LinearGradientBrush.GradientStops>
            <GradientStop Color="Black" Offset="0.501"/>
            <GradientStop Color="#FF091F34"/>
            <GradientStop Color="#FF002F5C" Offset="0.5"/>
        </LinearGradientBrush.GradientStops>
    </LinearGradientBrush>

    <LinearGradientBrush x:Key="MouseOverFocusStyle" StartPoint="0,0" EndPoint="0,1">
        <LinearGradientBrush.GradientStops>
            <GradientStop Color="#FF013B73" Offset="0.501"/>
            <GradientStop Color="#FF091F34"/>
            <GradientStop Color="#FF014A8F" Offset="0.5"/>
            <GradientStop Color="#FF003363" Offset="1"/>
        </LinearGradientBrush.GradientStops>
    </LinearGradientBrush>

    <LinearGradientBrush x:Key="LostFocusStyle" EndPoint="0.5,1" StartPoint="0.5,0">
        <LinearGradientBrush.RelativeTransform>
            <TransformGroup>
                <ScaleTransform CenterX="0.5" CenterY="0.5"/>
                <SkewTransform CenterX="0.5" CenterY="0.5"/>
                <RotateTransform CenterX="0.5" CenterY="0.5"/>
                <TranslateTransform/>
            </TransformGroup>
        </LinearGradientBrush.RelativeTransform>
        <GradientStop Color="#FF091F34" Offset="1"/>
        <GradientStop Color="#FF002F5C" Offset="0.4"/>
    </LinearGradientBrush>

    <SolidColorBrush x:Key="ListItemHighlight" Color="#FFE38E27" />

    <SolidColorBrush x:Key="ListItemUnHighlight" Color="#FF6FB8FD" />

    <DataTemplate x:Key="CustomListData" DataType="{x:Type ListBoxItem}">
        <Border BorderBrush="Black" BorderThickness="1"  Margin="-2,0,0,-1">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBoxItem}}, Path=ActualWidth}" />
                </Grid.ColumnDefinitions>
                <Label
                        VerticalContentAlignment="Center" BorderThickness="0" BorderBrush="Transparent"
                        Foreground="{StaticResource ListItemUnHighlight}"
                        FontSize="24"
                        Tag="{Binding .}"
                        Grid.Column="0"
                        MinHeight="55"
                        Cursor="Hand"
                        FontFamily="Arial"
                        FocusVisualStyle="{x:Null}"
                        KeyboardNavigation.TabNavigation="None"
                        Background="{StaticResource LostFocusStyle}"
                        MouseMove="ListItem_MouseOver"
                        >

                        <ContextMenu Name="editMenu">
                            <MenuItem Header="Edit"/>
                        </ContextMenu>

                    <TextBlock Text="{Binding .}" Margin="15,0,40,0" TextWrapping="Wrap"></TextBlock>

                <Image
                    Tag="{Binding .}"
                    Source="{Binding}"
                    Margin="260,0,0,0"
                    Grid.Column="1"
                    Stretch="None"
                    Width="16"
                    Height="22"
                    HorizontalAlignment="Center"
                    VerticalAlignment="Center"
                    />
            </Grid>
        </Border>
    </DataTemplate>

</Window.Resources>

<Window.DataContext>
    <ObjectDataProvider ObjectType="{x:Type local:ImageLoader}"  MethodName="LoadImages"  />
</Window.DataContext>

<ListBox ItemsSource="{Binding}" Width="320" Background="#FF021422" BorderBrush="#FF1C4B79" >

    <ListBox.Resources>
        <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}">Transparent</SolidColorBrush>

    </ListBox.Resources>

</ListBox>

Body:
I know I'm joing the party rather late, but you should be able to accomplish this by applying a custom ScrollViewier control template to be used by the ListBox. I have not tested this, but it should work (or at least offer a starting point):

    <ListBox ...>
    <ListBox.Resources>
        <Style TargetType="ScrollViewer">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="ScrollViewer">
                        <Grid>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition />
                                <ColumnDefinition Width="Auto" />
                            </Grid.ColumnDefinitions>
                            <Grid.RowDefinitions>
                                <RowDefinition />
                                <RowDefinition Height="Auto" />
                                <RowDefinition Height="Auto" />
                            </Grid.RowDefinitions>

                            <!-- Items Go Here -->
                            <ScrollContentPresenter Grid.Column="0" />

                            <!-- Buttons Go Here -->
                            <Grid Grid.Column="0"
                                  Grid.Row="1"
                                  >
                                  ...
                            </Grid>

                            <!-- ScrollBar spans all three rows but should only affect the presenter -->
                            <ScrollBar x:Name="PART_VerticalScrollBar"
                                        Grid.Column="1"
                                        Grid.Row="0"
                                        Grid.RowSpan="3"
                                        Value="{TemplateBinding VerticalOffset}"
                                        Maximum="{TemplateBinding ScrollableHeight}"
                                        ViewportSize="{TemplateBinding ViewportHeight}"
                                        Visibility="{TemplateBinding ComputedVerticalScrollBarVisibility}"
                                        />

                            <ScrollBar x:Name="PART_HorizontalScrollBar"
                                        Grid.Column="0"
                                        Grid.Row="1"
                                        Orientation="Horizontal"
                                        Value="{TemplateBinding HorizontalOffset}"
                                        Maximum="{TemplateBinding ScrollableWidth}"
                                        ViewportSize="{TemplateBinding ViewportWidth}"
                                        Visibility="{TemplateBinding ComputedHorizontalScrollBarVisibility}"
                                        />
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </ListBox.Resources>
</ListBox>

ContentLicense: CC BY-SA 2.5


问:
Do entry components need selectors in Angular?
Do entry components (those components which are loaded imperatively by the router and never declaratively by their selectors) need selectors?

For example:

```<code>@Component(
    selector: 'app-example', // <-- is this needed?
    // ...
)
export class ExampleComponent {}
</code>```

答:
No It's not required to provide selector

Here is the working example of routes without selector :

https://stackblitz.com/edit/angular-routes-noname

Reason for selector :

Angular2 / + is fully component based, reason behind the selector is just modularity, so you can use the same component at multiple places.

But if the component will not be used anywhere except the routes, it will work.

Body:
Do entry components (those components which are loaded imperatively by the router and never declaratively by their selectors) need selectors?

For example:

@Component(
    selector: 'app-example', // <-- is this needed?
    // ...
)
export class ExampleComponent {}


问:
How to make Stream Of Objects from a Dynamic Source in Java?
I am trying to solve a problem, looks like its not possible with Java.

I have some code that calls a processObject(SomeObject someObject) and the method process it. I am trying to encapsulate this whole thing and want to get a stream of someObjects.

Below is my sample program:

```<code>import java.util.stream.Stream;

public class ProcessObject {

    public static void main(String[] args) {
        int i = 0;
        ProcessObject processObject = new ProcessObject();
        while (true) {
            processObject.processObject(new SomeObject("Hello " + i++));
        }
    }

    public void processObject(SomeObject someObject) {
        System.out.println(someObject);

    }
    //TODO
    public Stream<SomeObject> getStream(){
        //Producer here should wait and produce Objects as soon as
        //they become available like "processObject" method.
        return Stream.generate(() -> new SomeObject("Hello "));
    }
}

class SomeObject {
    public String name;

    public SomeObject(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return name;
    }
}
</code>```

The static main method keeps on generating SomeObjects and call method processObject to process them and it prints them. So, all is good.

I want to create a stream of SomeObject so that instead of calling the method to process them, I will just use streams to process them, something like this:

public Stream getStream();

Now with Java 8 or Java 9, there are Streams available. But put the condition of IMMUTABLE characteristics from the sources they are being generated.

How to create a stream and then add elements to stream as soon as they become available like a true pipeline?

I thought to use a BlockingQueue and use it in Stream Generate method as Producer like blockingQueue.take() but it never compiles.

答:
To use a BlockingQueue to feed the Stream you will need the producer and the consumer running on different threads.

Here I am using my main thread to consume the stream and a new thread to feed it through a BlockingQueue to demonstrate.

```<code>public void test(String[] args) {
    // My queue
    BlockingQueue<BigInteger> queue = new ArrayBlockingQueue<>(10);

    // A Stream of it's contents.
    Stream<BigInteger> biStream = Stream.generate(() -> {
        try {
            return queue.take();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    });

    // Feed the queue from a thread.
    new Thread(new Runnable() {
        // Must be final to be accessible inside `run`.
        final AtomicInteger i = new AtomicInteger();

        @Override
        public void run() {
            // Slow feed to the queue.
            while (true) {
                // Add a new number to the queue.
                queue.add(BigInteger.valueOf(i.getAndIncrement()));
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }).start();

    // DEMO - Consumes the queue printing contents as they arrive.
    biStream.filter(x -> x.testBit(2))
            .limit(20)
            .forEach(x -> System.out.println(x));
}
</code>```

Body:
I am trying to solve a problem, looks like its not possible with Java.

I have some code that calls a processObject(SomeObject someObject) and the method process it. I am trying to encapsulate this whole thing and want to get a stream of someObjects.

Below is my sample program:

import java.util.stream.Stream;

public class ProcessObject {

    public static void main(String[] args) {
        int i = 0;
        ProcessObject processObject = new ProcessObject();
        while (true) {
            processObject.processObject(new SomeObject("Hello " + i++));
        }
    }

    public void processObject(SomeObject someObject) {
        System.out.println(someObject);

    }
    //TODO
    public Stream<SomeObject> getStream(){
        //Producer here should wait and produce Objects as soon as
        //they become available like "processObject" method.
        return Stream.generate(() -> new SomeObject("Hello "));
    }
}

class SomeObject {
    public String name;

    public SomeObject(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return name;
    }
}

The static main method keeps on generating SomeObjects and call method processObject to process them and it prints them. So, all is good.

I want to create a stream of SomeObject so that instead of calling the method to process them, I will just use streams to process them, something like this:

public Stream getStream();

Now with Java 8 or Java 9, there are Streams available. But put the condition of IMMUTABLE characteristics from the sources they are being generated.

How to create a stream and then add elements to stream as soon as they become available like a true pipeline?

I thought to use a BlockingQueue and use it in Stream Generate method as Producer like blockingQueue.take() but it never compiles.

Body:
To use a BlockingQueue to feed the Stream you will need the producer and the consumer running on different threads.

Here I am using my main thread to consume the stream and a new thread to feed it through a BlockingQueue to demonstrate.

public void test(String[] args) {
    // My queue
    BlockingQueue<BigInteger> queue = new ArrayBlockingQueue<>(10);

    // A Stream of it's contents.
    Stream<BigInteger> biStream = Stream.generate(() -> {
        try {
            return queue.take();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    });

    // Feed the queue from a thread.
    new Thread(new Runnable() {
        // Must be final to be accessible inside `run`.
        final AtomicInteger i = new AtomicInteger();

        @Override
        public void run() {
            // Slow feed to the queue.
            while (true) {
                // Add a new number to the queue.
                queue.add(BigInteger.valueOf(i.getAndIncrement()));
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }).start();

    // DEMO - Consumes the queue printing contents as they arrive.
    biStream.filter(x -> x.testBit(2))
            .limit(20)
            .forEach(x -> System.out.println(x));
}


问:
Error: must return a plain object, instead received undefined
My console output is producing the correct objects then crashing at the end of the array map and I can't figure out what's undefined. Here is my reducer, action, and list implement.

reducer:

```<code>export default (state = INITIAL_STATE, action) => {
  switch (action.type) {
      case LOCATION_FETCH_SUCCESS:
          return action.payload;
      case POSTS_FETCH_FAIL:
        return state;
    default:
      return state;
  }
};
</code>```

action creator:

```<code> export const locationFetch = () => {
   const geoFire = new GeoFire(firebase.database().ref('/geoLocations'));
  var keys = [];
  var snaps = [];
  return (dispatch) => {
    navigator.geolocation.getCurrentPosition(
        (position) => {
          const currentLocation = [position.coords.latitude, position.coords.longitude];
          const radius = 0.5;
          const geoQuery = geoFire.query({ center: currentLocation, radius });
        var onKeyEntered = geoQuery.on("key_entered", (key) => {
            keys.push(key);
            console.log(key);
          });
        var onKeyReady = geoQuery.on('ready', () => {

          keys.map((key) => {

            firebase.database().ref('/posts').child(key).
                  once('value').then((snapshot) => {

                    snaps.push(snapshot.val());
                  //  console.log(snaps);
                    dispatch({ type: LOCATION_FETCH_SUCCESS, payload: snaps });

               });//.catch(() => postsFetchFail(dispatch));

             });
        });
   });
};
};
</code>```

mapstatetoprops:

```<code>const mapStateToProps = state => {

var objectArray = _.values(state.posts)
objectArray = _.flatten(objectArray);
//console.log(objectArray);
  objectArray.map((post) => {
    const { dishname,
      restaurant,
      category,
      likesCount
      } = post;
      console.log({ dishname , restaurant });
    return { dishname, restaurant };
});
};

export default connect(mapStateToProps, {locationFetch})(DshdList);
</code>```

The last output to the console and the error message I am getting are as follows:

```<code>10:43:33 PM
Object {
  "dishname": "shrimp bun",
  "restaurant": "momofuku ",
}
10:43:38 PM
▼mapStateToProps() in Connect(DshdList) must return a plain object. Instead received undefined
</code>```

I do not get where this is going wrong.

答:
You must return object from mapStateToProps function, which you are missing. Place a return statement like below

return objectArray.map(...);

Hope this will help.

Body:
My console output is producing the correct objects then crashing at the end of the array map and I can't figure out what's undefined. Here is my reducer, action, and list implement.

reducer:

export default (state = INITIAL_STATE, action) => {
  switch (action.type) {
      case LOCATION_FETCH_SUCCESS:
          return action.payload;
      case POSTS_FETCH_FAIL:
        return state;
    default:
      return state;
  }
};

action creator:

 export const locationFetch = () => {
   const geoFire = new GeoFire(firebase.database().ref('/geoLocations'));
  var keys = [];
  var snaps = [];
  return (dispatch) => {
    navigator.geolocation.getCurrentPosition(
        (position) => {
          const currentLocation = [position.coords.latitude, position.coords.longitude];
          const radius = 0.5;
          const geoQuery = geoFire.query({ center: currentLocation, radius });
        var onKeyEntered = geoQuery.on("key_entered", (key) => {
            keys.push(key);
            console.log(key);
          });
        var onKeyReady = geoQuery.on('ready', () => {

          keys.map((key) => {

            firebase.database().ref('/posts').child(key).
                  once('value').then((snapshot) => {

                    snaps.push(snapshot.val());
                  //  console.log(snaps);
                    dispatch({ type: LOCATION_FETCH_SUCCESS, payload: snaps });

               });//.catch(() => postsFetchFail(dispatch));

             });
        });
   });
};
};

mapstatetoprops:

const mapStateToProps = state => {

var objectArray = _.values(state.posts)
objectArray = _.flatten(objectArray);
//console.log(objectArray);
  objectArray.map((post) => {
    const { dishname,
      restaurant,
      category,
      likesCount
      } = post;
      console.log({ dishname , restaurant });
    return { dishname, restaurant };
});
};

export default connect(mapStateToProps, {locationFetch})(DshdList);

The last output to the console and the error message I am getting are as follows:

10:43:33 PM
Object {
  "dishname": "shrimp bun",
  "restaurant": "momofuku ",
}
10:43:38 PM
▼mapStateToProps() in Connect(DshdList) must return a plain object. Instead received undefined

I do not get where this is going wrong.


问:
sql developer hangs on startup - what can I do?
At present I cannot run it (SQL Developer 4.1) because it hangs on "Restoring Editors" while starting. I suppose I've done it by exiting it before by killing sql developer process because it was hanged on fetching objects to Schema Browser so long...
Maybe I would clean some temporary files but can't find any.
Any ideas?</p>

答: Remove folders c:\Users\USERNAME\AppData\Roaming\SQL Developer\system4.1.3.20.78\system_cache*.  SQLDeveloper will recreate it after launching. </p>


问:
Sending IPv6 multicast packets through a specific network interface
I am trying to send IPv6 UDP packets to all of the nodes on the local network segment, in python, over Windows.

I have several network interfaces in my computer, and I want to know how to specify the network interface for sending the packets.

I have tried sending the packets to the multicast address ff02::1, using socket.sendto (without binding), but the packets are sent in the wrong network interface.

Any idea how can I specify the network adapter? (I read about BINDTODEVICE, but it won't work on windows, and some methods using bind to broadcast IP address classes, but only for IPv4).

Thanks!

答:
I didn't really like the previous solution, so I kept looking for others.

The first option that worked for me is to bind the sender socket to the specific network interface address. The network interfaces addresses can be found using netifaces module, and I used this helpful answer to specify the Ethernet address.

Another option that might work is the IPV6_MULTICAST_IF option-

```<code>#x is the relevant interface index
sock.setsockopt(socket.IPPROTO_IPV6,socket.IPV6_MULTICAST_IF,x)
</code>```

In Windows, python 2.7, one should add the line

```<code>socket.IPPROTO_IPV6=41
</code>```

before this code (since the relevant enum is not well defined).

Additional information can be found here (Windows) or here (Linux).

Although it seems like a simpler solution, I didn't completely managed to make it work, and not sure what is the proper way to find the right interface index (on Windows, Linux has several options).

Body:
I didn't really like the previous solution, so I kept looking for others.

The first option that worked for me is to bind the sender socket to the specific network interface address. The network interfaces addresses can be found using netifaces module, and I used this helpful answer to specify the Ethernet address.

Another option that might work is the IPV6_MULTICAST_IF option-

#x is the relevant interface index
sock.setsockopt(socket.IPPROTO_IPV6,socket.IPV6_MULTICAST_IF,x)

In Windows, python 2.7, one should add the line

socket.IPPROTO_IPV6=41

before this code (since the relevant enum is not well defined).

Additional information can be found here (Windows) or here (Linux).

Although it seems like a simpler solution, I didn't completely managed to make it work, and not sure what is the proper way to find the right interface index (on Windows, Linux has several options).


问:
How do I format date and time on ssrs report?
on SSRS report I need to show todays date and current time

i tried this =FormatDateTime(Now,"MM/dd/yyyy hh:mm tt") but this is not working for me giving an error.

Anyone please help me for expression ?

I want output display like 4/12/2013 12:05 PM

答:
```<code>=Replace(Format(CDate(Now()),"MM.dd.yyyy"), ".", "/")
</code>```


问:
laravel 5.5 The page has expired due to inactivity. Please refresh and try again
I'm new with Laravel and I have a problem which I don't understand.
I have а log form in my project and my method is POST. When I try a request the result is:

'The page has expired due to inactivity. Please refresh and try
  again.'

But if I change the method to GET, It works fine.

Can someone tell me why is that and how to fix it? because of course I need  POST method.

答:
In my case the same problem was caused because I forgot to add > at the end of my hidden input field, like so: <input type="hidden" name="_token" value="{{ Session::token() }}"

So, I fixed it by adding it:

```<code><input type="hidden" name="_token" value="{{ Session::token() }}">
</code>```

Body:
In my case the same problem was caused because I forgot to add > at the end of my hidden input field, like so: <input type="hidden" name="_token" value="{{ Session::token() }}"

So, I fixed it by adding it:

<input type="hidden" name="_token" value="{{ Session::token() }}">


问:
Can't find variable: method
Sorry I am new to react native and es6, right now I am having a problem with my API fetch function.

```<code>componentDidMount() {
      console.log("here");
      this._onPressButtonGET(0)
    }

  renderList = (data) =>{
    if(data){
      return data.map((item) => {
        return(
          {
            rOrder: item.rOrder,
            title: item.title,
            intro: item.intro,
            url: item.url,
            img: item.img,
          }
        )
      }
    )
  }
}

  async _onPressButtonGET(data) {
    console.log("here1");
    try {
        let response = await fetch(api.novel, method:"GET")
        let json = await response.json()
        console.log("here2");

        let dataList = this.renderList(responseData.data.carousel);

        for (  data = 0 ; data < 5; data++){
          if (dataList[data] == null) break;
          console.log(dataList[i]);
        };

        this.setState({ pValue:data })

      } catch (error) {
        console.log("here3");
        this.setState({ refreshing: false })
        alert(error)
      }
  }
</code>```

alert above give me ReferenceError:Can't find variable: method. The console.log "here 2" is not working. I can successfully fetch data without async/await mehtod, but currently, I kinda need async/await. Please help me with these functions.

```<code> _onPressButtonGET(data) {
          fetch(api.novel, {method: "GET"})
          .then((response) => response.json())
          .then((responseData) => {
               let dataList = this.renderList(responseData.data.carousel);
               //console.log(dataList);
               //console.log(dataList[1]);
               //let i = 0;
               for (  data = 0 ; data < 5; data++){
                 if (dataList[data] == null) break;
                 //console.log(dataList[i]);
               };
               console.log("outloop" +data);
               this.setState({ pValue:data })
          })
          .done();

      }
</code>```

I use another function to make this fetch successful, but just not with async/await. Now I am curious how this working? And why the async/await one not work?

答:
The error is on this line:

```<code>let response = await fetch(api.novel, method:"GET")
//                                    ^
</code>```

method is outside of the quotes, as a variable name, but it was never declared anywhere.

You probably meant to pass an init object to the fetch API:

```<code>let response = await fetch(api.novel, { method: "GET" })
//                                    ^ passing an object, notice the { }
</code>```

You can also omit the method type (default is "GET"):

```<code>let response = await fetch(api.novel)
</code>```

Title: Can't find variable: method

Body:
Sorry I am new to react native and es6, right now I am having a problem with my API fetch function.

componentDidMount() {
      console.log("here");
      this._onPressButtonGET(0)
    }

  renderList = (data) =>{
    if(data){
      return data.map((item) => {
        return(
          {
            rOrder: item.rOrder,
            title: item.title,
            intro: item.intro,
            url: item.url,
            img: item.img,
          }
        )
      }
    )
  }
}

  async _onPressButtonGET(data) {
    console.log("here1");
    try {
        let response = await fetch(api.novel, method:"GET")
        let json = await response.json()
        console.log("here2");

        let dataList = this.renderList(responseData.data.carousel);

        for (  data = 0 ; data < 5; data++){
          if (dataList[data] == null) break;
          console.log(dataList[i]);
        };

        this.setState({ pValue:data })

      } catch (error) {
        console.log("here3");
        this.setState({ refreshing: false })
        alert(error)
      }
  }

alert above give me ReferenceError:Can't find variable: method. The console.log "here 2" is not working. I can successfully fetch data without async/await mehtod, but currently, I kinda need async/await. Please help me with these functions.

 _onPressButtonGET(data) {
          fetch(api.novel, {method: "GET"})
          .then((response) => response.json())
          .then((responseData) => {
               let dataList = this.renderList(responseData.data.carousel);
               //console.log(dataList);
               //console.log(dataList[1]);
               //let i = 0;
               for (  data = 0 ; data < 5; data++){
                 if (dataList[data] == null) break;
                 //console.log(dataList[i]);
               };
               console.log("outloop" +data);
               this.setState({ pValue:data })
          })
          .done();

      }

I use another function to make this fetch successful, but just not with async/await. Now I am curious how this working? And why the async/await one not work?

Body:
The error is on this line:

let response = await fetch(api.novel, method:"GET")
//                                    ^

method is outside of the quotes, as a variable name, but it was never declared anywhere.

You probably meant to pass an init object to the fetch API:

let response = await fetch(api.novel, { method: "GET" })
//                                    ^ passing an object, notice the { }

You can also omit the method type (default is "GET"):

let response = await fetch(api.novel)


问:
Get latest records in a data frame based on time stamp with condition
My Question heading might not be accurate but i hope i will be able to explain my question
So i have a data frame like below

```<code>DataPartition_1|^|PartitionYear_1|^|TimeStamp|^|OrganizationId|^|AnnualPeriodId|^|InterimPeriodId|^|InterimNumber_1|^|FFAction_1
SelfSourcedPublic|^|2001|^|1510044629598|^|4295858941|^|5|^|21|^|2|^|I|!|
SelfSourcedPublic|^|2002|^|1510044629599|^|4295858941|^|1|^|22|^|2|^|I|!|
SelfSourcedPublic|^|2002|^|1510044629600|^|4295858941|^|1|^|23|^|2|^|I|!|
SelfSourcedPublic|^|2016|^|1510044629601|^|4295858941|^|35|^|36|^|1|^|I|!|
SelfSourcedPublic|^|2016|^|1510044629624|^|4295858941|^|null|^|35|^|null|^|D|!|
SelfSourcedPublic|^|2016|^|1510044629625|^|4295858941|^|null|^|36|^|null|^|D|!|
SelfSourcedPublic|^|2016|^|1510044629626|^|4295858941|^|null|^|37|^|null|^|D|!|
SelfSourcedPublic|^|2001|^|1510044629596|^|4295858941|^|19|^|5|^|1|^|I|!|
SelfSourcedPublic|^|2001|^|1510044629597|^|4295858941|^|20|^|5|^|2|^|I|!|
SelfSourcedPublic|^|2001|^|1510044629598|^|4295858941|^|21|^|5|^|2|^|I|!|
</code>```

So the primary key for my data frame is

```<code>OrganizationId", "AnnualPeriodId","InterimPeriodId"
</code>```

below is my code to get the latest records based on time stamp and arranged by seq of primary key .

```<code>import org.apache.spark.sql.expressions._
val windowSpec = Window.partitionBy("OrganizationId", "AnnualPeriodId","InterimPeriodId").orderBy($"TimeStamp".cast(LongType).desc)
val latestForEachKey = df2result.withColumn("rank", rank().over(windowSpec)).filter($"rank" === 1).drop("rank", "TimeStamp")
</code>```

Now my issue is some time i get null in some of the primary key column like record with time stamp 1510044629624.

Now my requirement is that below records have same primary key except first one has null .In this case i still need only one records with latest time stamp

```<code>    SelfSourcedPublic|^|2016|^|1510044629601|^|4295858941|^|35|^|36|^|1|^|I|!|
SelfSourcedPublic|^|2016|^|1510044629625|^|4295858941|^|null|^|36|^|null|^|D|!|
</code>```

I should get SelfSourcedPublic|^|2016|^|1510044629625|^|4295858941|^|null|^|36|^|null|^|D|!|

My current code gives output with both records because of the null ..

I hope my question is clear.

答:
From what I understood from your question and problem is that you are using an extra column as primary key.

AnnualPeriodId column is getting null and since you are using that field in partitionBy, it is causing the null to be separate group and thus separate row

```<code>val windowSpec = Window.partitionBy("OrganizationId", "AnnualPeriodId","InterimPeriodId").orderBy($"TimeStamp".cast(LongType).desc)
</code>```

So the solution is to remove it from the partitionBy so that the above line becomes

```<code>val windowSpec = Window.partitionBy("OrganizationId", "InterimPeriodId").orderBy($"TimeStamp".cast(LongType).desc)
</code>```

I hope this should solve the issue you are having.

Body:
My Question heading might not be accurate but i hope i will be able to explain my question
So i have a data frame like below

DataPartition_1|^|PartitionYear_1|^|TimeStamp|^|OrganizationId|^|AnnualPeriodId|^|InterimPeriodId|^|InterimNumber_1|^|FFAction_1
SelfSourcedPublic|^|2001|^|1510044629598|^|4295858941|^|5|^|21|^|2|^|I|!|
SelfSourcedPublic|^|2002|^|1510044629599|^|4295858941|^|1|^|22|^|2|^|I|!|
SelfSourcedPublic|^|2002|^|1510044629600|^|4295858941|^|1|^|23|^|2|^|I|!|
SelfSourcedPublic|^|2016|^|1510044629601|^|4295858941|^|35|^|36|^|1|^|I|!|
SelfSourcedPublic|^|2016|^|1510044629624|^|4295858941|^|null|^|35|^|null|^|D|!|
SelfSourcedPublic|^|2016|^|1510044629625|^|4295858941|^|null|^|36|^|null|^|D|!|
SelfSourcedPublic|^|2016|^|1510044629626|^|4295858941|^|null|^|37|^|null|^|D|!|
SelfSourcedPublic|^|2001|^|1510044629596|^|4295858941|^|19|^|5|^|1|^|I|!|
SelfSourcedPublic|^|2001|^|1510044629597|^|4295858941|^|20|^|5|^|2|^|I|!|
SelfSourcedPublic|^|2001|^|1510044629598|^|4295858941|^|21|^|5|^|2|^|I|!|

So the primary key for my data frame is

OrganizationId", "AnnualPeriodId","InterimPeriodId"

below is my code to get the latest records based on time stamp and arranged by seq of primary key .

import org.apache.spark.sql.expressions._
val windowSpec = Window.partitionBy("OrganizationId", "AnnualPeriodId","InterimPeriodId").orderBy($"TimeStamp".cast(LongType).desc)
val latestForEachKey = df2result.withColumn("rank", rank().over(windowSpec)).filter($"rank" === 1).drop("rank", "TimeStamp")

Now my issue is some time i get null in some of the primary key column like record with time stamp 1510044629624.

Now my requirement is that below records have same primary key except first one has null .In this case i still need only one records with latest time stamp

    SelfSourcedPublic|^|2016|^|1510044629601|^|4295858941|^|35|^|36|^|1|^|I|!|
SelfSourcedPublic|^|2016|^|1510044629625|^|4295858941|^|null|^|36|^|null|^|D|!|

I should get SelfSourcedPublic|^|2016|^|1510044629625|^|4295858941|^|null|^|36|^|null|^|D|!|

My current code gives output with both records because of the null ..

I hope my question is clear.

Body:
From what I understood from your question and problem is that you are using an extra column as primary key.

AnnualPeriodId column is getting null and since you are using that field in partitionBy, it is causing the null to be separate group and thus separate row

val windowSpec = Window.partitionBy("OrganizationId", "AnnualPeriodId","InterimPeriodId").orderBy($"TimeStamp".cast(LongType).desc)

So the solution is to remove it from the partitionBy so that the above line becomes

val windowSpec = Window.partitionBy("OrganizationId", "InterimPeriodId").orderBy($"TimeStamp".cast(LongType).desc)

I hope this should solve the issue you are having.


问:
Eclipse - how to handle custom projects creation
I want to develop capability in my own Eclipse feature to create projects of  my own DSL languages - in other words, I want have wizard so I can click New > My Custom Project, then fill in all necessary fields in wizard pages and then, after perform Finish I want basic folders hierarchy and template files to be created and my DSL nature to be added. I know how to create plugins/features, as good as Wizard. I can create everything in "hard-code", I mean create folders and files, but maybe there is some build-in solution to facilitate it? I found IProject interface with its stuff, is it a good clue?

答:
I have found interesting implementation of org.eclipse.core.resources.* library on Eclipse FAQ site, and it seems to work.

    IWorkspace workspace = ResourcesPlugin.getWorkspace();
    IWorkspaceRoot root = workspace.getRoot();
    IProject project  = root.getProject("MyProject");
    IFolder folder = project.getFolder("Folder1");
    IFile file = folder.getFile("hello.txt");
    //at this point, no resources have been created
    if (!project.exists()) project.create(null);
    if (!project.isOpen()) project.open(null);
    if (!folder.exists())
        folder.create(IResource.NONE, true, null);
    if (!file.exists()) {
        byte[] bytes = "File contents".getBytes();
        InputStream source = new ByteArrayInputStream(bytes);
        file.create(source, IResource.NONE, null);
    }
```

It is very simple and do its job well, makes possible to easily initialize project's content

Body:
I have found interesting implementation of org.eclipse.core.resources.* library on Eclipse FAQ site, and it seems to work.

    IWorkspace workspace = ResourcesPlugin.getWorkspace();
    IWorkspaceRoot root = workspace.getRoot();
    IProject project  = root.getProject("MyProject");
    IFolder folder = project.getFolder("Folder1");
    IFile file = folder.getFile("hello.txt");
    //at this point, no resources have been created
    if (!project.exists()) project.create(null);
    if (!project.isOpen()) project.open(null);
    if (!folder.exists())
        folder.create(IResource.NONE, true, null);
    if (!file.exists()) {
        byte[] bytes = "File contents".getBytes();
        InputStream source = new ByteArrayInputStream(bytes);
        file.create(source, IResource.NONE, null);
    }

It is very simple and do its job well, makes possible to easily initialize project's content


问:
Java array of constants
How is it possible to declare and initialize an array of constants in Java, without using enums ?

```<code>static final Type[] arrayOfConstants = new Type[10]; // not an array of constants
</code>```

答:
Its'been a while this post is open
I am surprised, why any one would not think of

```<code>public static final List<LanguageModel> GenderDataSource = new ArrayList<GenderModel>(){{
    add(new LanguageModel("0", "English"));
    add(new LanguageModel("1", "Hindi"));
    add(new LanguageModel("1", "Tamil"));
};};
</code>```

Where LanguageModel simply contains two properties Id and Title or use whatever your model class of generic Type could be.

Should work great as constant.

-- N Baua

Title: Java array of constants

Body:
How is it possible to declare and initialize an array of constants in Java, without using enums ?

static final Type[] arrayOfConstants = new Type[10]; // not an array of constants

Body:
Its'been a while this post is open
I am surprised, why any one would not think of

public static final List<LanguageModel> GenderDataSource = new ArrayList<GenderModel>(){{
    add(new LanguageModel("0", "English"));
    add(new LanguageModel("1", "Hindi"));
    add(new LanguageModel("1", "Tamil"));
};};

Where LanguageModel simply contains two properties Id and Title or use whatever your model class of generic Type could be.

Should work great as constant.

-- N Baua


问:
Is there a way to bold text in Intellisense comments in Visual Studio 2010?
Is there a way to bold text in Intellisense comments?

My idea:

```<code>/// <summary>
/// <para><bold>Paramater1:</bold>: blah blah
...
</code>```

答:
You can use "Better Comments" visual studio plugin.
This tool allows you to customize your comments as follows:

Use '!' for Important.

Use '?' for Question.

Use "Todo" (Case ignored) for Task.

Use 'x', 'X', or double comment for strikethrough (Crossed).

You can find more options in the link.

Body:
Is there a way to bold text in Intellisense comments?

My idea:

///
/// <para><bold>Paramater1:</bold>: blah blah
...


问:
R - assigning value to one column based on a comparison of two other columns
Let's say I have the following data:

```<code>SNP eff_allele A1 A2
rs1000000 A A G
rs10000010 C C T
rs1000002 T T C
rs10000023 G T G
</code>```

I want to create a new variable, alt_allele, that takes on the value of either column A1 or A2, depending on the value of the column eff_allele. If eff_allele equals A1, then alt_allele should get the value of A2, and if eff_allele equals A2, then alt_allele should get the value of A1. I did two attempts:

Attempt 1:

```<code>if (myData$eff_allele == myData$A1) {
myData$alt_allele <- myData$A2
}
if (myData$eff_allele == myData$A2) {
myData$alt_allele <- myData$A1
}
</code>```

Attempt 2:

```<code>height_fam$alt_allele[height_fam$eff_allele == height_fam$A1] <- height_fam$A2
height_fam$alt_allele[height_fam$eff_allele == height_fam$A2] <- height_fam$A1
</code>```

Both of these don't work... What am I doing wrong? How can I achieve the following update to my data:

```<code>SNP eff_allele A1 A2 alt_allele
rs1000000 A A G G
rs10000010 C C T T
rs1000002 T T C C
rs10000023 G T G T
</code>```

答:
In R and matlab try not too use loops, They are slow. try solve your problem by vectors.

Edit: Oh, I read your question wrong, You didn't use vectors anyway :)

```<code>a=read.table("a.csv", sep = " ", header = T)
row = dim(a)
# Number of rows
row = row[2]
newcol = rep("",row)
A1 = as.character(a$A1)
A2 = as.character(a$A2)
eff_allele = as.character(a$eff_allele)
# a1_ind is FALSE for index that should be equal to A1
a1_ind = eff_allele!= A1
newcol[a1_ind] = A1[a1_ind]
newcol[!a1_ind] = A2[!a1_ind]
a = cbind(a,newcol)
</code>```

and the output will be:

```<code>         SNP eff_allele A1 A2 newcol
1  rs1000000          A  A  G      G
2 rs10000010          C  C  T      T
3  rs1000002          T  T  C      C
4 rs10000023          G  T  G      T
</code>```

Body:
Let's say I have the following data:

SNP eff_allele A1 A2
rs1000000 A A G
rs10000010 C C T
rs1000002 T T C
rs10000023 G T G

I want to create a new variable, alt_allele, that takes on the value of either column A1 or A2, depending on the value of the column eff_allele. If eff_allele equals A1, then alt_allele should get the value of A2, and if eff_allele equals A2, then alt_allele should get the value of A1. I did two attempts:

Attempt 1:

if (myData$eff_allele == myData$A1) {
myData$alt_allele <- myData$A2
}
if (myData$eff_allele == myData$A2) {
myData$alt_allele <- myData$A1
}

Attempt 2:

height_fam$alt_allele[height_fam$eff_allele == height_fam$A1] <- height_fam$A2
height_fam$alt_allele[height_fam$eff_allele == height_fam$A2] <- height_fam$A1

Both of these don't work... What am I doing wrong? How can I achieve the following update to my data:

SNP eff_allele A1 A2 alt_allele
rs1000000 A A G G
rs10000010 C C T T
rs1000002 T T C C
rs10000023 G T G T

Body:
In R and matlab try not too use loops, They are slow. try solve your problem by vectors.

Edit: Oh, I read your question wrong, You didn't use vectors anyway :)

a=read.table("a.csv", sep = " ", header = T)
row = dim(a)
# Number of rows
row = row[2]
newcol = rep("",row)
A1 = as.character(a$A1)
A2 = as.character(a$A2)
eff_allele = as.character(a$eff_allele)
# a1_ind is FALSE for index that should be equal to A1
a1_ind = eff_allele!= A1
newcol[a1_ind] = A1[a1_ind]
newcol[!a1_ind] = A2[!a1_ind]
a = cbind(a,newcol)

and the output will be:

         SNP eff_allele A1 A2 newcol
1  rs1000000          A  A  G      G
2 rs10000010          C  C  T      T
3  rs1000002          T  T  C      C
4 rs10000023          G  T  G      T


问:
Always getting "Application in break mode" error when trying to debug xamarin.android application
I am developing a Xamarin.Android Application in Visual studio 2017 (V:15.4.1). MY application has few pages like.
1) Splash
2) Login
3) Dash Board
........ Other Pages.
When i run the app in debug mode. It shows the login page and after entering credential it shows process-bar and check user credential from external Service Using "HttpClient" in Async.

Then main issues arise after this operation.

* If i run the app in debug mode. it shows **Application in break mode
*** If i run normally this app in android device. it works fine.

Is there any solution for this issue?

答:
```<code>if (sFirstCharacter == "1")
            {
                var MainActivity = new Intent(this, typeof(MainActivity));
                MainActivity.PutExtra("Value", txtusername.Text);
                StartActivity(typeof(MainActivity));
                //Toast.MakeText(this, "Login Succesfull", ToastLength.Long).Show();
                RunOnUiThread(() =>
                {
                    progress.Dismiss();
                });
            }
</code>```

<p>After commenting Toast from IF condition it working fine :) </p>

Body:
if (sFirstCharacter == "1")
            {
                var MainActivity = new Intent(this, typeof(MainActivity));
                MainActivity.PutExtra("Value", txtusername.Text);
                StartActivity(typeof(MainActivity));
                //Toast.MakeText(this, "Login Succesfull", ToastLength.Long).Show();
                RunOnUiThread(() =>
                {
                    progress.Dismiss();
                });
            }

After commenting Toast from IF condition it working fine :)


问:
ASP.NET: HTTP Error 500.19 – Internal Server Error 0x8007000d
I am replicating web application deployment and found several issues related to HTTP Error 500.19. My machine is running Windows 7 while the working development is using Windows 8. We're developing our Web Application using Visual Studio 2010.

First, I got error code 0x80070021, similar as posted  here.
I update my web.config according to the accepted answer and then I got following error code (which is similar as posted here).

```<code>HTTP Error 500.19 - Internal Server Error
Error Code 0x8007000d
Config Source -1: 0:
</code>```

I have read the symptoms definition in Microsoft support page and cause of the error is:

This problem occurs because the ApplicationHost.config file or the Web.config file contains a malformed XML element.

and the solution is

Delete the malformed XML element from the ApplicationHost.config file or from the Web.config file.

However, the web.config that I used is working perfectly in the original development environment.

Here is what I have checked and tried so far:

Install ASP.NET by calling aspnet_regiis -i

Set my application to use different application pool (ASP.NET v4.0, .NET v4, etc)

ApplicationHost.config file is still using default from Windows 7.

This is part of my Web.Config

```<code><system.webServer>
    <section name="handlers" overrideModeDefault="Allow" />
    <section name="modules" allowDefinition="MachineToApplication" overrideModeDefault="Allow" />
    <validation validateIntegratedModeConfiguration="false" />
    <modules runAllManagedModulesForAllRequests="true">
    </modules>
    <handlers>
        <remove name="UrlRoutingHandler" />
        <add name="ReportViewerWebControlHandler" preCondition="integratedMode" verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
    </handlers>
    <urlCompression doStaticCompression="true" doDynamicCompression="false"></urlCompression>
    <directoryBrowse enabled="true" />
    <defaultDocument>
        <files>
            <add value="Logon.aspx" />
        </files>
    </defaultDocument>
</system.webServer>
</code>```

I have read similar/duplicates/closed posts (around 13) posts in stackoverflow, tried all except the answer related to Ajax (is it related) and still have no clue on what the error is.

Does anyone one how to fix this error? (And if possible, a comprehensive lists of things need to be checked so we can reduce similar posts like this.) I am ready to provide more details.

答: I turn on .Net Framework 3.5 and 4.5 Advance Service in Control Panel->Programs and Features->Turn Windows features on or off.it work for me.

Body:
I am replicating web application deployment and found several issues related to HTTP Error 500.19. My machine is running Windows 7 while the working development is using Windows 8. We're developing our Web Application using Visual Studio 2010.

First, I got error code 0x80070021, similar as posted  here.
I update my web.config according to the accepted answer and then I got following error code (which is similar as posted here).

HTTP Error 500.19 - Internal Server Error
Error Code 0x8007000d
Config Source -1: 0:

I have read the symptoms definition in Microsoft support page and cause of the error is:

This problem occurs because the ApplicationHost.config file or the Web.config file contains a malformed XML element.

and the solution is

Delete the malformed XML element from the ApplicationHost.config file or from the Web.config file.

However, the web.config that I used is working perfectly in the original development environment.

Here is what I have checked and tried so far:

Install ASP.NET by calling aspnet_regiis -i

Set my application to use different application pool (ASP.NET v4.0, .NET v4, etc)

ApplicationHost.config file is still using default from Windows 7.

This is part of my Web.Config

<system.webServer>

    <validation validateIntegratedModeConfiguration="false" />
    <modules runAllManagedModulesForAllRequests="true">
    </modules>
    <handlers>
        <remove name="UrlRoutingHandler" />
        <add name="ReportViewerWebControlHandler" preCondition="integratedMode" verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
    </handlers>
    <urlCompression doStaticCompression="true" doDynamicCompression="false"></urlCompression>
    <directoryBrowse enabled="true" />
    <defaultDocument>
        <files>
            <add value="Logon.aspx" />
        </files>
    </defaultDocument>
</system.webServer>

I have read similar/duplicates/closed posts (around 13) posts in stackoverflow, tried all except the answer related to Ajax (is it related) and still have no clue on what the error is.

Does anyone one how to fix this error? (And if possible, a comprehensive lists of things need to be checked so we can reduce similar posts like this.) I am ready to provide more details.


问:
How can I declare a multi line string in swift 3 which also has html content in it
I want to declare a multi line string which also has html content in it and I am passing it as a parameter to compose a mail using MFMailComposeViewDelegate functionality.

How can achieve the same?

答:
Seeing the swift 3 tag, I assume you can't use the new triple quotes in swift 4.

First method: Concatenation:

You'll have to do it the old-fashioned way:

```<code>let html =
    "This is some html\n" +
    "<strong>second line</strong>\n"
</code>```

Second method: write the HTML into a file.

Just create a file called xxx.html in your project and write your html in that file. Then, at the start of the app, you can read that file into a string and then you can use it later.

```<code>let htmlString = try! String(contentsOfFile: Bundle.main.path(forResources: "xxx", ofType: "html"!))
</code>```

Body:
Seeing the swift 3 tag, I assume you can't use the new triple quotes in swift 4.

First method: Concatenation:

You'll have to do it the old-fashioned way:

let html =
    "This is some html\n" +
    "<strong>second line</strong>\n"

Second method: write the HTML into a file.

Just create a file called xxx.html in your project and write your html in that file. Then, at the start of the app, you can read that file into a string and then you can use it later.

let htmlString = try! String(contentsOfFile: Bundle.main.path(forResources: "xxx", ofType: "html"!))


问:
Unable to use for loop against array data in Yii2
I have a variable $data in my controller. In which I am getting the following result

```<code>Array( [0] => 99 [1] => 100 [2] => 101 [3] => 102 [4] => 103)
</code>```

Now I want to get the single entry one by one by using for loop. The main purpose of this loop is that I want to insert these values in my DB table.

```<code> if(Yii::$app->request->isAjax && Yii::$app->request->post())
    {
        $data = explode(',',$_POST['data']);

       for($i=0; $i<=count($data); $i++)
        {
            print_r($data[$i]);
        }
        //print_r($data);
    }
    else{
        echo 'no data';
    }
    exit();
</code>```

When i Run this one, I am getting the error

500 Internal Server Error
  PHP Notice 'yii\base\ErrorException' with message 'Undefined offset: 5'

Stack Trace

```<code>Stack trace:
#0 E:\xampp\htdocs\inventory-
web\backend\controllers\OgpheaderController.php(170): yii\base\ErrorHandler-
>handleError(8, 'Undefined offse...',
'E:\\xampp\\htdocs...', 170, Array)
#1 [internal function]: backend\controllers\OgpheaderController-
>actionViewsetpdf('55')
#2 E:\xampp\htdocs\inventory-
web\vendor\yiisoft\yii2\base\InlineAction.php(57):
call_user_func_array(Array, Array)
#3 E:\xampp\htdocs\inventory-
web\vendor\yiisoft\yii2\base\Controller.php(156): yii\base\InlineAction-
>runWithParams(Array)
#4 E:\xampp\htdocs\inventory-web\vendor\yiisoft\yii2\base\Module.php(523):
yii\base\Controller->runAction('viewsetpdf', Array)
#5 E:\xampp\htdocs\inventory-
web\vendor\yiisoft\yii2\web\Application.php(102): yii\base\Module-
>runAction('ogpheader/views...', Array)
#6 E:\xampp\htdocs\inventory-
web\vendor\yiisoft\yii2\base\Application.php(380): yii\web\Application-
>handleRequest(Object(yii\web\Request))
#7 E:\xampp\htdocs\inventory-web\backend\web\index.php(17):
yii\base\Application->run()
#8 {main}```
```

I have searched for this error solution but couldn't find the correct answer(s).

Any help would be highly appreciated.

答:
```<code> for($i=0; $i<count($data); $i++)
    {
        print_r($data[$i]);
    }
</code>```

or

```<code> for($i=0; $i<=count($data)-1; $i++)
    {
        print_r($data[$i]);
    }
</code>```

or

```<code>foreach($data as $value)
{
print_r($value);
}
</code>```

any of these will work

Body:
I have a variable $data in my controller. In which I am getting the following result

Array( [0] => 99 [1] => 100 [2] => 101 [3] => 102 [4] => 103)

Now I want to get the single entry one by one by using for loop. The main purpose of this loop is that I want to insert these values in my DB table.

 if(Yii::$app->request->isAjax && Yii::$app->request->post())
    {
        $data = explode(',',$_POST['data']);

       for($i=0; $i<=count($data); $i++)
        {
            print_r($data[$i]);
        }
        //print_r($data);
    }
    else{
        echo 'no data';
    }
    exit();

When i Run this one, I am getting the error

500 Internal Server Error
  PHP Notice 'yii\base\ErrorException' with message 'Undefined offset: 5'

Stack Trace

Stack trace:
#0 E:\xampp\htdocs\inventory-
web\backend\controllers\OgpheaderController.php(170): yii\base\ErrorHandler-
>handleError(8, 'Undefined offse...',
'E:\\xampp\\htdocs...', 170, Array)
#1 [internal function]: backend\controllers\OgpheaderController-
>actionViewsetpdf('55')
#2 E:\xampp\htdocs\inventory-
web\vendor\yiisoft\yii2\base\InlineAction.php(57):
call_user_func_array(Array, Array)
#3 E:\xampp\htdocs\inventory-
web\vendor\yiisoft\yii2\base\Controller.php(156): yii\base\InlineAction-
>runWithParams(Array)
#4 E:\xampp\htdocs\inventory-web\vendor\yiisoft\yii2\base\Module.php(523):
yii\base\Controller->runAction('viewsetpdf', Array)
#5 E:\xampp\htdocs\inventory-
web\vendor\yiisoft\yii2\web\Application.php(102): yii\base\Module-
>runAction('ogpheader/views...', Array)
#6 E:\xampp\htdocs\inventory-
web\vendor\yiisoft\yii2\base\Application.php(380): yii\web\Application-
>handleRequest(Object(yii\web\Request))
#7 E:\xampp\htdocs\inventory-web\backend\web\index.php(17):
yii\base\Application->run()
#8 {main}

I have searched for this error solution but couldn't find the correct answer(s).

Any help would be highly appreciated.

Body:
 for($i=0; $i<count($data); $i++)
    {
        print_r($data[$i]);
    }

or

 for($i=0; $i<=count($data)-1; $i++)
    {
        print_r($data[$i]);
    }

or

foreach($data as $value)
{
print_r($value);
}

any of these will work


问:
how to POST/Submit an Input Checkbox that is disabled?
I have a checkbox that, given certain conditions, needs to be disabled. Turns out HTTP doesn't post disabled inputs.

How can I get around that? submitting the input even if it's disabled and keeping the input disabled?

答:
You could handle it this way... For each checkbox, create a hidden field with the same name attribute. But set the value of that hidden field with some default value that you could test against. For example..

```<code><input type="checkbox" name="myCheckbox" value="agree" />
<input type="hidden" name="myCheckbox" value="false" />
</code>```

If the checkbox is "checked" when the form is submitted, then the value of that form parameter will be

```<code>"agree,false"
</code>```

If the checkbox is not checked, then the value would be

```<code>"false"
</code>```

You could use any value instead of "false", but you get the idea.

Body:
You could handle it this way... For each checkbox, create a hidden field with the same name attribute. But set the value of that hidden field with some default value that you could test against. For example..

<input type="checkbox" name="myCheckbox" value="agree" />
<input type="hidden" name="myCheckbox" value="false" />

If the checkbox is "checked" when the form is submitted, then the value of that form parameter will be

"agree,false"

If the checkbox is not checked, then the value would be

"false"

You could use any value instead of "false", but you get the idea.


问:
Java mail without ssl - PKIX path building failed:
I am using java mail to send emails over smtp. The smtp settings given below:

```<code>        Properties props = new Properties();
        Object put = props.put("mail.smtp.host", smtpHost);
        props.put("mail.smtp.user", smtpUser);
        props.put("mail.smtp.auth", true);
        props.put("mail.debug", mailDebug);
        props.put("mail.smtp.port", port);
</code>```

The smtp credentials have been verified by telnetting to my smtpHost with the above details. However, I get the  following exception when I use the above settings in java mail.

```<code>        250-AUTH PLAIN LOGIN
        250-STARTTLS
        250 HELP
        DEBUG SMTP: Found extension "SIZE", arg "52428800"
        DEBUG SMTP: Found extension "8BITMIME", arg ""
        DEBUG SMTP: Found extension "PIPELINING", arg ""
        DEBUG SMTP: Found extension "AUTH", arg "PLAIN LOGIN"
        DEBUG SMTP: Found extension "STARTTLS", arg ""
        DEBUG SMTP: Found extension "HELP", arg ""
        DEBUG SMTP: Attempt to authenticate
        DEBUG SMTP: check mechanisms: LOGIN PLAIN DIGEST-MD5 NTLM
        DEBUG SMTP: AUTH LOGIN command trace suppressed
        DEBUG SMTP: AUTH LOGIN failed
        Nov 29, 2012 11:54:40 AM com.Test main
        SEVERE: null
        javax.mail.AuthenticationFailedException: 535 Incorrect authentication data
</code>```

When I add the line :

```<code>        props.put("mail.smtp.starttls.enable", false);
</code>```

It again generates the same authentication failed exception.

If I set mail.smtp.starttls.enable to true, the authentication succeeds, but I get the following exception:

```<code>     220 TLS go ahead
     Nov 28, 2012 5:32:36 PM com.Test main
     SEVERE: null
     javax.mail.MessagingException: Could not convert socket to TLS;
     nested exception is:
    javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at com.sun.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:1918)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:652)
    at javax.mail.Service.connect(Service.java:317)
</code>```

After going through various forum threads regarding the second exception, I ran the InstallCert program to fetch the server's self-signed certificate. The InstallCert throws the following exception:

```<code>            Opening connection to mydomain.com.au:443...
            Starting SSL handshake...
            javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
                    at sun.security.ssl.InputRecord.handleUnknownRecord(InputRecord.java:542)
                    at sun.security.ssl.InputRecord.read(InputRecord.java:374)
                    at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:850)
                    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1190)
                    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1217)
                    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1201)
                    at InstallCert.main(InstallCert.java:100)
            Could not obtain server certificate chain
</code>```

So, looks like my server does not have ssl, but starttls is enabled. What are the correct parameters for sending mail with STARTTLS on, to a server with no ssl?

答:
I had this problem with java 8. After updating this property problem solved

```<code>props.put("mail.smtp.ssl.trust", "smtp.gmail.com")

if used spring boot in application.property

spring.mail.properties.mail.smtp.ssl.trust = smtp.gmail.com
</code>```

I think this will help.

Body:
I am using java mail to send emails over smtp. The smtp settings given below:

        Properties props = new Properties();
        Object put = props.put("mail.smtp.host", smtpHost);
        props.put("mail.smtp.user", smtpUser);
        props.put("mail.smtp.auth", true);
        props.put("mail.debug", mailDebug);
        props.put("mail.smtp.port", port);

The smtp credentials have been verified by telnetting to my smtpHost with the above details. However, I get the  following exception when I use the above settings in java mail.

        250-AUTH PLAIN LOGIN
        250-STARTTLS
        250 HELP
        DEBUG SMTP: Found extension "SIZE", arg "52428800"
        DEBUG SMTP: Found extension "8BITMIME", arg ""
        DEBUG SMTP: Found extension "PIPELINING", arg ""
        DEBUG SMTP: Found extension "AUTH", arg "PLAIN LOGIN"
        DEBUG SMTP: Found extension "STARTTLS", arg ""
        DEBUG SMTP: Found extension "HELP", arg ""
        DEBUG SMTP: Attempt to authenticate
        DEBUG SMTP: check mechanisms: LOGIN PLAIN DIGEST-MD5 NTLM
        DEBUG SMTP: AUTH LOGIN command trace suppressed
        DEBUG SMTP: AUTH LOGIN failed
        Nov 29, 2012 11:54:40 AM com.Test main
        SEVERE: null
        javax.mail.AuthenticationFailedException: 535 Incorrect authentication data

When I add the line :

        props.put("mail.smtp.starttls.enable", false);

It again generates the same authentication failed exception.

If I set mail.smtp.starttls.enable to true, the authentication succeeds, but I get the following exception:

     220 TLS go ahead
     Nov 28, 2012 5:32:36 PM com.Test main
     SEVERE: null
     javax.mail.MessagingException: Could not convert socket to TLS;
     nested exception is:
    javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at com.sun.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:1918)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:652)
    at javax.mail.Service.connect(Service.java:317)

After going through various forum threads regarding the second exception, I ran the InstallCert program to fetch the server's self-signed certificate. The InstallCert throws the following exception:

            Opening connection to mydomain.com.au:443...
            Starting SSL handshake...
            javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
                    at sun.security.ssl.InputRecord.handleUnknownRecord(InputRecord.java:542)
                    at sun.security.ssl.InputRecord.read(InputRecord.java:374)
                    at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:850)
                    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1190)
                    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1217)
                    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1201)
                    at InstallCert.main(InstallCert.java:100)
            Could not obtain server certificate chain

So, looks like my server does not have ssl, but starttls is enabled. What are the correct parameters for sending mail with STARTTLS on, to a server with no ssl?

Body:
I had this problem with java 8. After updating this property problem solved

props.put("mail.smtp.ssl.trust", "smtp.gmail.com")

if used spring boot in application.property

spring.mail.properties.mail.smtp.ssl.trust = smtp.gmail.com

I think this will help.


问:
Allow only 3 rows to be added to a table for a specific value
I have a question in hand where i need to restrict the number of projects assigned to a manager to only 3. The tables are:

```<code>Manager:
Manager_employee_id(PK)
Manager_Bonus

Project:
project_number(PK)
Project_cost
Project_manager_employee_id(FK)
</code>```

Can anyone suggest what approach to take to implement this?

答:
I would do the following:

Create new column projects_taken (tinyint) (1) (takes values of 1,2 or 3) with default value of 0.

When manager takes project, the field will increment by 1

Do simple checks (through the UI) to see if the field projects_taken is equal or smaller than 3.

Body:
I have a question in hand where i need to restrict the number of projects assigned to a manager to only 3. The tables are:

Manager:
Manager_employee_id(PK)
Manager_Bonus

Project:
project_number(PK)
Project_cost
Project_manager_employee_id(FK)

Can anyone suggest what approach to take to implement this?


问:
How to insert color lines to StringBuilder object
Is it possible to add lines with color to StringBuilder object ?

I know how to add colors with Write-Host:

```<code>Write-Host "Line without a color"
Write-Host "Line with red color" -ForegroundColor Red
</code>```

But not with StringBuilder:

```<code>$sb = New-Object -TypeName "System.Text.StringBuilder"
$sb.AppendLine("Line without a color") | Out-Null
$sb.AppendLine("Line with red color") | Out-Null
$sb.ToString()
</code>```

I prefer to grab all the lines together and print them all.

StringBuilder is a good a way but I want also that some of the lines with be with color.

Is it possible ?

This the output I want to get with StringBuilder:

I read something here about RTFString builder but it didn't work for me as expected.

答:
Workaround:

```<code>$sb = New-Object -TypeName "System.Text.StringBuilder"
$sb.AppendLine("Line without a color") | Out-Null
$sb.AppendLine("#color:red#Line with red color") | Out-Null

$delim =@([Environment]::NewLine, "\n")
$sbLines = $sb.ToString().Split($delim, [System.StringSplitOptions]::None)
foreach($line in $sbLines){

    if($line.StartsWith("#color:red#")){
        Write-Host $line.Split("#")[2] -ForegroundColor Red
    }
    else{
        Write-Host $line
    }
}
</code>```

More generic solution:

```<code><#
.SYNOPSIS
A wrapper around Write-Host that supports selective coloring of
substrings via embedded coloring specifications.

.DESCRIPTION
In addition to accepting a default foreground and background color,
you can embed one or more color specifications in the string to write,
using the following syntax:
#<fgcolor>[:<bgcolor>]#<text>#

<fgcolor> and <bgcolor> must be valid [ConsoleColor] values, such as 'green' or 'white' (case does not matter).
Everything following the color specification up to the next '#', or impliclitly to the end of the string,
is written in that color.

Note that nesting of color specifications is not supported.
As a corollary, any token that immediately follows a color specification is treated
as text to write, even if it happens to be a technically valid color spec too.
This allows you to use, e.g., 'The next word is #green#green#.', without fear
of having the second '#green' be interpreted as a color specification as well.

.PARAMETER ForegroundColor
Specifies the default text color for all text portions
for which no embedded foreground color is specified.

.PARAMETER BackgroundColor
Specifies the default background color for all text portions
for which no embedded background color is specified.

.PARAMETER NoNewline
Output the specified string withpout a trailing newline.

.NOTES
While this function is convenient, it will be slow with many embedded colors, because,
behind the scenes, Write-Host must be called for every colored span.

.EXAMPLE
Write-HostColored "#green#Green foreground.# Default colors. #blue:white#Blue on white."

.EXAMPLE
'#black#Black on white (by default).#Blue# Blue on white.' | Write-HostColored -BackgroundColor White

#>
function Write-HostColored() {
    [CmdletBinding()]
    param(
        [parameter(Position=0, ValueFromPipeline=$true)]
        [string[]] $Text
        ,
        [switch] $NoNewline
        ,
        [ConsoleColor] $BackgroundColor = $host.UI.RawUI.BackgroundColor
        ,
        [ConsoleColor] $ForegroundColor = $host.UI.RawUI.ForegroundColor
    )

    begin {
        # If text was given as a parameter value, it'll be an array.
        # Like Write-Host, we flatten the array into a single string
        # using simple string interpolation (which defaults to separating elements with a space,
        # which can be changed by setting $OFS).
        if ($Text -ne $null) {
            $Text = "$Text"
        }
    }

    process {
        if ($Text) {

            # Start with the foreground and background color specified via
            # -ForegroundColor / -BackgroundColor, or the current defaults.
            $curFgColor = $ForegroundColor
            $curBgColor = $BackgroundColor

            # Split message into tokens by '#'.
            # A token between to '#' instances is either the name of a color or text to write (in the color set by the previous token).
            $tokens = $Text.split("#")

            # Iterate over tokens.
            $prevWasColorSpec = $false
            foreach($token in $tokens) {

                if (-not $prevWasColorSpec -and $token -match '^([a-z]*)(:([a-z]+))?$') { # a potential color spec.
                    # If a token is a color spec, set the color for the next token to write.
                    # Color spec can be a foreground color only (e.g., 'green'), or a foreground-background color pair (e.g., 'green:white'), or just a background color (e.g., ':white')
                    try {
                        $curFgColor = [ConsoleColor] $matches[1]
                        $prevWasColorSpec = $true
                    } catch {}
                    if ($matches[3]) {
                        try {
                            $curBgColor = [ConsoleColor] $matches[3]
                            $prevWasColorSpec = $true
                        } catch {}
                    }
                    if ($prevWasColorSpec) {
                        continue
                    }
                }

                $prevWasColorSpec = $false

                if ($token) {
                    # A text token: write with (with no trailing line break).
                    # !! In the ISE - as opposed to a regular PowerShell console window,
                    # !! $host.UI.RawUI.ForegroundColor and $host.UI.RawUI.ForegroundColor inexcplicably
                    # !! report value -1, which causes an error when passed to Write-Host.
                    # !! Thus, we only specify the -ForegroundColor and -BackgroundColor parameters
                    # !! for values other than -1.
                    # !! Similarly, PowerShell Core terminal windows on *Unix* report -1 too.
                    $argsHash = @{}
                    if ([int] $curFgColor -ne -1) { $argsHash += @{ 'ForegroundColor' = $curFgColor } }
                    if ([int] $curBgColor -ne -1) { $argsHash += @{ 'BackgroundColor' = $curBgColor } }
                    Write-Host -NoNewline @argsHash $token
                }

                # Revert to default colors.
                $curFgColor = $ForegroundColor
                $curBgColor = $BackgroundColor

            }
        }
        # Terminate with a newline, unless suppressed
        if (-not $NoNewLine) { write-host }
    }
}

# MAIN
$sb = New-Object -TypeName "System.Text.StringBuilder"
$sb.AppendLine("Line without a color") | Out-Null
$sb.AppendLine("#red#Line with red color") | Out-Null

$delim =@([Environment]::NewLine, "\n")
$sbLines = $sb.ToString().Split($delim, [System.StringSplitOptions]::None)
foreach($line in $sbLines){
    Write-HostColored $line
}
</code>```

Body:
Is it possible to add lines with color to StringBuilder object ?

I know how to add colors with Write-Host:

Write-Host "Line without a color"
Write-Host "Line with red color" -ForegroundColor Red

But not with StringBuilder:

$sb = New-Object -TypeName "System.Text.StringBuilder"
$sb.AppendLine("Line without a color") | Out-Null
$sb.AppendLine("Line with red color") | Out-Null
$sb.ToString()

I prefer to grab all the lines together and print them all.

StringBuilder is a good a way but I want also that some of the lines with be with color.

Is it possible ?

This the output I want to get with StringBuilder:

I read something here about RTFString builder but it didn't work for me as expected.

Body:
Workaround:

$sb = New-Object -TypeName "System.Text.StringBuilder"
$sb.AppendLine("Line without a color") | Out-Null
$sb.AppendLine("#color:red#Line with red color") | Out-Null

$delim =@([Environment]::NewLine, "\n")
$sbLines = $sb.ToString().Split($delim, [System.StringSplitOptions]::None)
foreach($line in $sbLines){

    if($line.StartsWith("#color:red#")){
        Write-Host $line.Split("#")[2] -ForegroundColor Red
    }
    else{
        Write-Host $line
    }
}

More generic solution:

<#
.SYNOPSIS
A wrapper around Write-Host that supports selective coloring of
substrings via embedded coloring specifications.

.DESCRIPTION
In addition to accepting a default foreground and background color,
you can embed one or more color specifications in the string to write,
using the following syntax:
#<fgcolor>[:<bgcolor>]#<text>#

<fgcolor> and <bgcolor> must be valid [ConsoleColor] values, such as 'green' or 'white' (case does not matter).
Everything following the color specification up to the next '#', or impliclitly to the end of the string,
is written in that color.

Note that nesting of color specifications is not supported.
As a corollary, any token that immediately follows a color specification is treated
as text to write, even if it happens to be a technically valid color spec too.
This allows you to use, e.g., 'The next word is #green#green#.', without fear
of having the second '#green' be interpreted as a color specification as well.

.PARAMETER ForegroundColor
Specifies the default text color for all text portions
for which no embedded foreground color is specified.

.PARAMETER BackgroundColor
Specifies the default background color for all text portions
for which no embedded background color is specified.

.PARAMETER NoNewline
Output the specified string withpout a trailing newline.

.NOTES
While this function is convenient, it will be slow with many embedded colors, because,
behind the scenes, Write-Host must be called for every colored span.

.EXAMPLE
Write-HostColored "#green#Green foreground.# Default colors. #blue:white#Blue on white."

.EXAMPLE
'#black#Black on white (by default).#Blue# Blue on white.' | Write-HostColored -BackgroundColor White

#>
function Write-HostColored() {
    [CmdletBinding()]
    param(
        [parameter(Position=0, ValueFromPipeline=$true)]
        [string[]] $Text
        ,
        [switch] $NoNewline
        ,
        [ConsoleColor] $BackgroundColor = $host.UI.RawUI.BackgroundColor
        ,
        [ConsoleColor] $ForegroundColor = $host.UI.RawUI.ForegroundColor
    )

    begin {
        # If text was given as a parameter value, it'll be an array.
        # Like Write-Host, we flatten the array into a single string
        # using simple string interpolation (which defaults to separating elements with a space,
        # which can be changed by setting $OFS).
        if ($Text -ne $null) {
            $Text = "$Text"
        }
    }

    process {
        if ($Text) {

            # Start with the foreground and background color specified via
            # -ForegroundColor / -BackgroundColor, or the current defaults.
            $curFgColor = $ForegroundColor
            $curBgColor = $BackgroundColor

            # Split message into tokens by '#'.
            # A token between to '#' instances is either the name of a color or text to write (in the color set by the previous token).
            $tokens = $Text.split("#")

            # Iterate over tokens.
            $prevWasColorSpec = $false
            foreach($token in $tokens) {

                if (-not $prevWasColorSpec -and $token -match '^([a-z]*)(:([a-z]+))?$') { # a potential color spec.
                    # If a token is a color spec, set the color for the next token to write.
                    # Color spec can be a foreground color only (e.g., 'green'), or a foreground-background color pair (e.g., 'green:white'), or just a background color (e.g., ':white')
                    try {
                        $curFgColor = [ConsoleColor] $matches[1]
                        $prevWasColorSpec = $true
                    } catch {}
                    if ($matches[3]) {
                        try {
                            $curBgColor = [ConsoleColor] $matches[3]
                            $prevWasColorSpec = $true
                        } catch {}
                    }
                    if ($prevWasColorSpec) {
                        continue
                    }
                }

                $prevWasColorSpec = $false

                if ($token) {
                    # A text token: write with (with no trailing line break).
                    # !! In the ISE - as opposed to a regular PowerShell console window,
                    # !! $host.UI.RawUI.ForegroundColor and $host.UI.RawUI.ForegroundColor inexcplicably
                    # !! report value -1, which causes an error when passed to Write-Host.
                    # !! Thus, we only specify the -ForegroundColor and -BackgroundColor parameters
                    # !! for values other than -1.
                    # !! Similarly, PowerShell Core terminal windows on *Unix* report -1 too.
                    $argsHash = @{}
                    if ([int] $curFgColor -ne -1) { $argsHash += @{ 'ForegroundColor' = $curFgColor } }
                    if ([int] $curBgColor -ne -1) { $argsHash += @{ 'BackgroundColor' = $curBgColor } }
                    Write-Host -NoNewline @argsHash $token
                }

                # Revert to default colors.
                $curFgColor = $ForegroundColor
                $curBgColor = $BackgroundColor

            }
        }
        # Terminate with a newline, unless suppressed
        if (-not $NoNewLine) { write-host }
    }
}

# MAIN
$sb = New-Object -TypeName "System.Text.StringBuilder"
$sb.AppendLine("Line without a color") | Out-Null
$sb.AppendLine("#red#Line with red color") | Out-Null

$delim =@([Environment]::NewLine, "\n")
$sbLines = $sb.ToString().Split($delim, [System.StringSplitOptions]::None)
foreach($line in $sbLines){
    Write-HostColored $line
}