问:
Xamarin Forms Binding Context
I am creating an app similar to Youtube. When the user clicks an viewcell on the homepage, it will open another page with the video and details about the video. I cannot figure out how to pass the details data of the viewcell to the next page! (I want the details to be specific to the video)

Homepage:

Homepage.xaml.cs:

```<code>public partial class Homepage : ContentPage
{
    List<Video> Videos = new List<Video>
        {
            new Video
            {
                Title = "apples",
                Author = "connor",
                Views = 322,
                Upload_DateTime = new DateTime(1996, 8, 26),
                ImageURL = "icon.png",

            },
            new Video
            {
                Title = "Video 2",
                Author = "FedEx",
                Views = 554,
                Upload_DateTime = new DateTime(2017, 1, 23),
                ImageURL = "icon.png",
            },
            new Video
            {
                Title = "bananas",
                Author = "meeks",
                Views = 23,
                Upload_DateTime = new DateTime(2012, 3, 11),
                ImageURL = "icon.png",
            },
            new Video
            {
                Title = "grapes",
                Author = "fedex",
                Views = 211,
                Upload_DateTime = new DateTime(2013, 4, 13),
                ImageURL = "icon.png",
            },
            new Video
            {
                Title = "Video 5",
                Author = "Mike",
                Views = 12,
                Upload_DateTime = new DateTime(2010, 7, 11),
                ImageURL = "icon.png",
            },
            new Video
            {
                Title = "PeARs",
                Author = "JJEORF",
                Views = 2231,
                Upload_DateTime = new DateTime(2009, 5, 14),
                ImageURL = "icon.png",
            },
            new Video
            {
                Title = "pears",
                Author = "FedEx",
                Views = 12345,
                Upload_DateTime = new DateTime(2000, 1, 23),
                ImageURL = "icon.png",
            },
        };

    public Homepage()
    {
        InitializeComponent();

        VideoListView.ItemsSource = Videos; //allows for binding
    }

        private void ViewCellItem_Clicked(object sender, EventArgs e) //this is for when items in the view cells are clicked
    {

        var Video_Play_Page = new Video_Play_Page();
        NavigationPage.SetHasNavigationBar(Video_Play_Page, false); //removes the Navigation bar at top of page
        Navigation.PushAsync(Video_Play_Page);

    }
</code>```

Homepage.xaml:

```<code><ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="App2.Homepage"
         Title="Homepage">

<ListView x:Name="VideoListView" HasUnevenRows="True" ItemTapped="ViewCellItem_Clicked">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <ViewCell.View>
                        <Grid RowSpacing="0" ColumnSpacing="10" Padding="10, 10, 10, 10"> <!-- "left, top, right, bottom" -->
                            <Grid.RowDefinitions>
                                <RowDefinition Height="auto"/>
                                <RowDefinition Height="auto"/>
                                <RowDefinition Height="auto"/>
                            </Grid.RowDefinitions>

                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="1*"/> <!-- 1/3 of total column width -->
                                <ColumnDefinition Width="2*"/> <!-- 2/3 of total column width -->
                            </Grid.ColumnDefinitions>

                            <Image
                                Source="{Binding ImageURL}"
                                Grid.Row="0" Grid.Column="0" Grid.RowSpan="3"
                                Aspect="AspectFill"/>
                            <Label
                                Text="{Binding Title}"
                                Font="Bold"
                                Grid.Row="0" Grid.Column="1"
                                VerticalTextAlignment="Center"
                                x:Name="Bind_Title"/>
                            <Label
                                Text="{Binding Author_Views}"
                                TextColor="LightGray"
                                Grid.Row="1" Grid.Column="1"
                                VerticalTextAlignment="Center"/>
                            <Label
                                Text="{Binding Uploaded}"
                                TextColor="LightGray"
                                Grid.Row="2" Grid.Column="1"
                                VerticalTextAlignment="Center"/>
                        </Grid>
                    </ViewCell.View>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</ContentPage>
</code>```

Detail Page:

Video_Play_Page.xaml.cs:

```<code>public partial class Video_Play_Page : ContentPage
{

    List<Video> Videos = new List<Video>
        {
            new Video
            {
                Title = "apples",
                Author = "connor",
                Views = 322,
                Upload_DateTime = new DateTime(1996, 8, 26),
                ImageURL = "icon.png",

            },
            new Video
            {
                Title = "Video 2",
                Author = "FedEx",
                Views = 554,
                Upload_DateTime = new DateTime(2017, 1, 23),
                ImageURL = "icon.png",
            },
            new Video
            {
                Title = "bananas",
                Author = "meeks",
                Views = 23,
                Upload_DateTime = new DateTime(2012, 3, 11),
                ImageURL = "icon.png",
            },
            new Video
            {
                Title = "grapes",
                Author = "fedex",
                Views = 211,
                Upload_DateTime = new DateTime(2013, 4, 13),
                ImageURL = "icon.png",
            },
            new Video
            {
                Title = "Video 5",
                Author = "Mike",
                Views = 12,
                Upload_DateTime = new DateTime(2010, 7, 11),
                ImageURL = "icon.png",
            },
            new Video
            {
                Title = "PeARs",
                Author = "JJEORF",
                Views = 2231,
                Upload_DateTime = new DateTime(2009, 5, 14),
                ImageURL = "icon.png",
            },
            new Video
            {
                Title = "pears",
                Author = "FedEx",
                Views = 12345,
                Upload_DateTime = new DateTime(2000, 1, 23),
                ImageURL = "icon.png",
            },
        };

    public Video_Play_Page()
    {
        InitializeComponent();

        VideoListView.ItemsSource = Videos;

    }

    private void VideoBackButton_Clicked(object sender, EventArgs e)
    {

        var Homepage = new Homepage();
        NavigationPage.SetHasNavigationBar(Homepage, false); //removes the Navigation bar at top of page
        Navigation.PushAsync(Homepage);
    }

    private void ViewCellItem_Clicked(object sender, EventArgs e) //this is for when items in the view cells are clicked
    {

        var Video_Play_Page = new Video_Play_Page();
        NavigationPage.SetHasNavigationBar(Video_Play_Page, false); //removes the Navigation bar at top of page
        Navigation.PushAsync(Video_Play_Page);

    }

}
</code>```

Video_Play_Page.xaml:

```<code><ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="App2.Video_Play_Page"
         Title="Video_Play_Page"

         xmlns:roxv="clr-namespace:Rox;assembly=Rox.Xamarin.Video.Portable"
         BackgroundColor="#4B1388"
         >
                <!--detail -->
                <StackLayout x:Name="VideoDetail" BackgroundColor="Red" Grid.Row="0" Grid.Column="0">

                    <Label Text ="Detail goes here!"/>

                </StackLayout>

                <!--related videos listview -->
                <ListView x:Name="VideoListView" HasUnevenRows="True" ItemTapped="ViewCellItem_Clicked" BackgroundColor="Green" Grid.Row="1" Grid.Column="0">
                    <ListView.ItemTemplate>
                        <DataTemplate>
                            <ViewCell>
                                <ViewCell.View>
                                    <Grid RowSpacing="0" ColumnSpacing="10" Padding="10, 10, 10, 10">
                                        <!-- "left, top, right, bottom" -->
                                        <Grid.RowDefinitions>
                                            <RowDefinition Height="auto"/>
                                            <RowDefinition Height="auto"/>
                                            <RowDefinition Height="auto"/>
                                        </Grid.RowDefinitions>

                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition Width="1*"/>
                                            <!-- 1/3 of total column width -->
                                            <ColumnDefinition Width="2*"/>
                                            <!-- 2/3 of total column width -->
                                        </Grid.ColumnDefinitions>

                                        <Image
                                Source="{Binding ImageURL}"
                                Grid.Row="0" Grid.Column="0" Grid.RowSpan="3"
                                Aspect="AspectFill"/>
                                        <Label
                                Text="{Binding Title}"
                                Font="Bold"
                                Grid.Row="0" Grid.Column="1"
                                VerticalTextAlignment="Center"/>
                                        <Label
                                Text="{Binding Author_Views}"
                                TextColor="LightGray"
                                Grid.Row="1" Grid.Column="1"
                                VerticalTextAlignment="Center"/>
                                        <Label
                                Text="{Binding Uploaded}"
                                TextColor="LightGray"
                                Grid.Row="2" Grid.Column="1"
                                VerticalTextAlignment="Center"/>
                                    </Grid>
                                </ViewCell.View>
                            </ViewCell>
                        </DataTemplate>
                    </ListView.ItemTemplate>
                </ListView>
   </ContentPage>
</code>```

Video.cs:

```<code>class Video
{
    public string Title { get; set; }

    //possibly implement tags?

    public string Author { get; set; }
    public int Views { get; set; }
    public DateTime Upload_DateTime { get; set; }
    public string ImageURL { get; set; }

    public string Author_Views
    {

        get
        {
            return string.Format("{0} - {1} Views", Author, Views); //format for viewcell details
        }
    }

    public string Uploaded
    {

        get
        {
            return string.Format("Uploaded: {0} ", Upload_DateTime); //format for viewcell details
        }
    }

}
</code>```

答:
```<code>private void ViewCellItem_Clicked(object sender, EventArgs e) //this is for when items in the view cells are clicked
{
    var item = ((Video)VideoListView.SelectedItem);
    var Video_Play_Page = new Video_Play_Page(item);
    NavigationPage.SetHasNavigationBar(Video_Play_Page, false);
    //removes the Navigation bar at top of page
    Navigation.PushAsync(Video_Play_Page);
}
</code>```

in your page's constructor, you will need to accept an argument

```<code>public Video_Play_Page(Video selected) {

  this.BindingContext = selected;

  // other constructor tasks
}
</code>```

Title: Xamarin Forms Binding Context

Body:
I am creating an app similar to Youtube. When the user clicks an viewcell on the homepage, it will open another page with the video and details about the video. I cannot figure out how to pass the details data of the viewcell to the next page! (I want the details to be specific to the video)

Homepage:

Homepage.xaml.cs:

public partial class Homepage : ContentPage
{
    List<Video> Videos = new List<Video>
        {
            new Video
            {
                Title = "apples",
                Author = "connor",
                Views = 322,
                Upload_DateTime = new DateTime(1996, 8, 26),
                ImageURL = "icon.png",

            },
            new Video
            {
                Title = "Video 2",
                Author = "FedEx",
                Views = 554,
                Upload_DateTime = new DateTime(2017, 1, 23),
                ImageURL = "icon.png",
            },
            new Video
            {
                Title = "bananas",
                Author = "meeks",
                Views = 23,
                Upload_DateTime = new DateTime(2012, 3, 11),
                ImageURL = "icon.png",
            },
            new Video
            {
                Title = "grapes",
                Author = "fedex",
                Views = 211,
                Upload_DateTime = new DateTime(2013, 4, 13),
                ImageURL = "icon.png",
            },
            new Video
            {
                Title = "Video 5",
                Author = "Mike",
                Views = 12,
                Upload_DateTime = new DateTime(2010, 7, 11),
                ImageURL = "icon.png",
            },
            new Video
            {
                Title = "PeARs",
                Author = "JJEORF",
                Views = 2231,
                Upload_DateTime = new DateTime(2009, 5, 14),
                ImageURL = "icon.png",
            },
            new Video
            {
                Title = "pears",
                Author = "FedEx",
                Views = 12345,
                Upload_DateTime = new DateTime(2000, 1, 23),
                ImageURL = "icon.png",
            },
        };

    public Homepage()
    {
        InitializeComponent();

        VideoListView.ItemsSource = Videos; //allows for binding
    }

        private void ViewCellItem_Clicked(object sender, EventArgs e) //this is for when items in the view cells are clicked
    {

        var Video_Play_Page = new Video_Play_Page();
        NavigationPage.SetHasNavigationBar(Video_Play_Page, false); //removes the Navigation bar at top of page
        Navigation.PushAsync(Video_Play_Page);

    }

Homepage.xaml:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="App2.Homepage"
         Title="Homepage">

<ListView x:Name="VideoListView" HasUnevenRows="True" ItemTapped="ViewCellItem_Clicked">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <ViewCell.View>
                        <Grid RowSpacing="0" ColumnSpacing="10" Padding="10, 10, 10, 10">
                            <Grid.RowDefinitions>
                                <RowDefinition Height="auto"/>
                                <RowDefinition Height="auto"/>
                                <RowDefinition Height="auto"/>
                            </Grid.RowDefinitions>

                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="1*"/>
                                <ColumnDefinition Width="2*"/>
                            </Grid.ColumnDefinitions>

                            <Image
                                Source="{Binding ImageURL}"
                                Grid.Row="0" Grid.Column="0" Grid.RowSpan="3"
                                Aspect="AspectFill"/>

                        </Grid>
                    </ViewCell.View>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</ContentPage>

Detail Page:

Video_Play_Page.xaml.cs:

public partial class Video_Play_Page : ContentPage
{

    List<Video> Videos = new List<Video>
        {
            new Video
            {
                Title = "apples",
                Author = "connor",
                Views = 322,
                Upload_DateTime = new DateTime(1996, 8, 26),
                ImageURL = "icon.png",

            },
            new Video
            {
                Title = "Video 2",
                Author = "FedEx",
                Views = 554,
                Upload_DateTime = new DateTime(2017, 1, 23),
                ImageURL = "icon.png",
            },
            new Video
            {
                Title = "bananas",
                Author = "meeks",
                Views = 23,
                Upload_DateTime = new DateTime(2012, 3, 11),
                ImageURL = "icon.png",
            },
            new Video
            {
                Title = "grapes",
                Author = "fedex",
                Views = 211,
                Upload_DateTime = new DateTime(2013, 4, 13),
                ImageURL = "icon.png",
            },
            new Video
            {
                Title = "Video 5",
                Author = "Mike",
                Views = 12,
                Upload_DateTime = new DateTime(2010, 7, 11),
                ImageURL = "icon.png",
            },
            new Video
            {
                Title = "PeARs",
                Author = "JJEORF",
                Views = 2231,
                Upload_DateTime = new DateTime(2009, 5, 14),
                ImageURL = "icon.png",
            },
            new Video
            {
                Title = "pears",
                Author = "FedEx",
                Views = 12345,
                Upload_DateTime = new DateTime(2000, 1, 23),
                ImageURL = "icon.png",
            },
        };

    public Video_Play_Page()
    {
        InitializeComponent();

        VideoListView.ItemsSource = Videos;

    }

    private void VideoBackButton_Clicked(object sender, EventArgs e)
    {

        var Homepage = new Homepage();
        NavigationPage.SetHasNavigationBar(Homepage, false); //removes the Navigation bar at top of page
        Navigation.PushAsync(Homepage);
    }

    private void ViewCellItem_Clicked(object sender, EventArgs e) //this is for when items in the view cells are clicked
    {

        var Video_Play_Page = new Video_Play_Page();
        NavigationPage.SetHasNavigationBar(Video_Play_Page, false); //removes the Navigation bar at top of page
        Navigation.PushAsync(Video_Play_Page);

    }

}

Video_Play_Page.xaml:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="App2.Video_Play_Page"
         Title="Video_Play_Page"

         xmlns:roxv="clr-namespace:Rox;assembly=Rox.Xamarin.Video.Portable"
         BackgroundColor="#4B1388"
         >

                <StackLayout x:Name="VideoDetail" BackgroundColor="Red" Grid.Row="0" Grid.Column="0">

                </StackLayout>

                <ListView x:Name="VideoListView" HasUnevenRows="True" ItemTapped="ViewCellItem_Clicked" BackgroundColor="Green" Grid.Row="1" Grid.Column="0">
                    <ListView.ItemTemplate>
                        <DataTemplate>
                            <ViewCell>
                                <ViewCell.View>
                                    <Grid RowSpacing="0" ColumnSpacing="10" Padding="10, 10, 10, 10">

                                        <Grid.RowDefinitions>
                                            <RowDefinition Height="auto"/>
                                            <RowDefinition Height="auto"/>
                                            <RowDefinition Height="auto"/>
                                        </Grid.RowDefinitions>

                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition Width="1*"/>

                                            <ColumnDefinition Width="2*"/>

                                        </Grid.ColumnDefinitions>

                                        <Image
                                Source="{Binding ImageURL}"
                                Grid.Row="0" Grid.Column="0" Grid.RowSpan="3"
                                Aspect="AspectFill"/>

                                    </Grid>
                                </ViewCell.View>
                            </ViewCell>
                        </DataTemplate>
                    </ListView.ItemTemplate>
                </ListView>
   </ContentPage>

Video.cs:

class Video
{
    public string Title { get; set; }

    //possibly implement tags?

    public string Author { get; set; }
    public int Views { get; set; }
    public DateTime Upload_DateTime { get; set; }
    public string ImageURL { get; set; }

    public string Author_Views
    {

        get
        {
            return string.Format("{0} - {1} Views", Author, Views); //format for viewcell details
        }
    }

    public string Uploaded
    {

        get
        {
            return string.Format("Uploaded: {0} ", Upload_DateTime); //format for viewcell details
        }
    }

}

Body:
private void ViewCellItem_Clicked(object sender, EventArgs e) //this is for when items in the view cells are clicked
{
    var item = ((Video)VideoListView.SelectedItem);
    var Video_Play_Page = new Video_Play_Page(item);
    NavigationPage.SetHasNavigationBar(Video_Play_Page, false);
    //removes the Navigation bar at top of page
    Navigation.PushAsync(Video_Play_Page);
}

in your page's constructor, you will need to accept an argument

public Video_Play_Page(Video selected) {

  this.BindingContext = selected;

  // other constructor tasks
}


来源: stackexchange

问:
SQLPLUS IF Function in Select Causes Identifier Too Long Error
Below select statement causes ORA-00972: identifier is too long error. Suspect a syntax error. Running this select to generate a view in SQLPLUS on an Oracle db. Please advise. Thanks.

```<code>SELECT DISTINCT
    (CASE WHEN PROCEDURE_CODE IS NULL THEN REVENUE_CODE ELSE PROCEDURE_CODE END)
FROM HEALTH.DATA
</code>```

答:
I can't reproduce the problem but maybe my database version is different.

My guess though is adding an alias to your select :

```<code>SELECT DISTINCT (CASE
                   WHEN PROCEDURE_CODE IS NULL THEN
                    REVENUE_CODE
                   ELSE
                    PROCEDURE_CODE
                END) AS THING
  FROM HEALTH.DATA
</code>```

If you don't specify any, it "builds" the column name using the full "CASE" and it might bust some limit there I suppose.

ContentLicense: CC BY-SA 3.0

Body:
Below select statement causes ORA-00972: identifier is too long error. Suspect a syntax error. Running this select to generate a view in SQLPLUS on an Oracle db. Please advise. Thanks.

SELECT DISTINCT
    (CASE WHEN PROCEDURE_CODE IS NULL THEN REVENUE_CODE ELSE PROCEDURE_CODE END)
FROM HEALTH.DATA

Body:
I can't reproduce the problem but maybe my database version is different.

My guess though is adding an alias to your select :

SELECT DISTINCT (CASE
                   WHEN PROCEDURE_CODE IS NULL THEN
                    REVENUE_CODE
                   ELSE
                    PROCEDURE_CODE
                END) AS THING
  FROM HEALTH.DATA

If you don't specify any, it "builds" the column name using the full "CASE" and it might bust some limit there I suppose.


问:
Does a foreign key reduce redundancy if all the columns are referenced?
I've read that one of the benefits of normalization is to reduce redundancy in the DB. But I'm wondering, if you end up referencing all the columns in the target table?

For example, if I have a Video table that references a Genre table, the Genre table might very likely have a single column with a dozen fairly static values like 'Horror' 'Sci-Fi' 'Romance' etc.

In a case like this, does it save any space to separate the two, or is the only benefit making it so you can update all referencing rows from one place?

答:
But you've hit the problem yourself there:

single column with a dozen fairly
  static values like 'Horror' 'Sci-Fi'
  'Romance' etc.

With surrogate keys and normalized tables, you only have "Horror" stored once in database, but its ID number is stored in several places (a simple number is smaller than the text most of the time, and does save space).  Not only does it increase the maintainability of the database, but it does indeed save raw space.

ContentLicense: CC BY-SA 2.5


问:
Trust SSL certificate with IPv6 address
I have an IIS application with an HTTPS binding that uses a self signed certificate. The certificate contains DNS names for the server's hostname, IPv4 address, and IPv6 address. I've installed the certificate on my client machine in the Local Machine's Trusted Root Certificate Authorities folder. Using a web browser I can connect to the server using the host name and both IP addresses without certificate errors. I'm also writing a C# client application that needs to connect to the server. In the application's configuration if I specify the hostname or IPv4 address, the application can connect just fine, but if I specify the IPv6 address I get an exception. The innermost message is "The remote certificate is invalid according to the validation procedure.". If I configure the site to accept HTTP requests, the client application can connect just fine using IPv6.

What do I need to do get the client application to trust my certificate when using the IPv6 address?

Edit: In case it's relevant, I'm using HttpClient's PostAsync method to submit requests.

答:
The certificate contains DNS names for the server's hostname, IPv4 address, and IPv6 address.

IPv4 and IPv6 addresses should not be given as DNS names (type dNSName) but as type iPAddress in the subject alternative names extension. But, MSIE is known to expect this as dNSName although this is wrong so you should probably add these both as dNSName and iPAddress.

If this is still not possible to connect with your application it might be a bug in the certificate validation in C# or in the way you specify the IPv6 address in the URL (i.e. different syntax then expected). Since using IP addresses inside a certificate and especially IPv6 is an uncommon case this might not be that well tested in C# and the TLS library.

Title: Trust SSL certificate with IPv6 address


问:
Javascript show loading icon until a textview is set value
I am using google maps api to load the current geo-location of the user. As it finishes loading, I set the 2 values to 2 hidden html forms:

```<code>document.getElementById("latitude").value = position.coords.latitude;
document.getElementById("longitude").value = position.coords.longitude;
</code>```

If the user presses submit before the values are set, the app crashes. How can I make a loading element until the 2 elements on the page contain the information? Any link or suggestion? Thank you!

答:
You can stop the form from submitting by cancelling the submit event. Like so:</p>

```<code><form id="my_form">
    <input type="hidden" id="latitude" name="latitude" />
    <input type="hidden" id="longitude" name="longitude" />
    <input type="submit" />
</form>

<script>
document.getElementById("my_form").addEventListener("submit", function (e) {
    if (document.getElementById("latitude").value === "" ||
        document.getElementById("longitude").value === "") {
        e.peventDefault(); // stop the submit
        alert("Please wait for values");
    }
});
</script>
</code>```

Body:
I am using google maps api to load the current geo-location of the user. As it finishes loading, I set the 2 values to 2 hidden html forms:

document.getElementById("latitude").value = position.coords.latitude;
document.getElementById("longitude").value = position.coords.longitude;

If the user presses submit before the values are set, the app crashes. How can I make a loading element until the 2 elements on the page contain the information? Any link or suggestion? Thank you!

Body:
You can stop the form from submitting by cancelling the submit event. Like so:

<form id="my_form">
    <input type="hidden" id="latitude" name="latitude" />
    <input type="hidden" id="longitude" name="longitude" />
    <input type="submit" />
</form>

<script>
document.getElementById("my_form").addEventListener("submit", function (e) {
    if (document.getElementById("latitude").value === "" ||
        document.getElementById("longitude").value === "") {
        e.peventDefault(); // stop the submit
        alert("Please wait for values");
    }
});
</script>


问:
xfce4: Keyboard application shortcut to run emacs does not export the current user's environment variables
I have emacs bound to Ctrl-Alt E. I also have some environment variables exported in ~/.bashrc. When running M-x getenv, I get different environment variables not defined in ~/.bashrc</p>

答: ~/.bashrc is normally only sourced for interactive shells.  Put your variables in ~/.bash_profile or ~/.profile.


答: What happens if you want to ensure that your rows in the Video table have valid/predetermined entries for Genre? If you don't have a foreign key constraint you would need an enum for that column in the Video table and then you would have to change the schema every time you add a new Genre instead of just adding a new row to a Genre table.</p>

Title: Does a foreign key reduce redundancy if all the columns are referenced?

Body:
I've read that one of the benefits of normalization is to reduce redundancy in the DB. But I'm wondering, if you end up referencing all the columns in the target table?

For example, if I have a Video table that references a Genre table, the Genre table might very likely have a single column with a dozen fairly static values like 'Horror' 'Sci-Fi' 'Romance' etc.

In a case like this, does it save any space to separate the two, or is the only benefit making it so you can update all referencing rows from one place?


问:
How to reshaping and pivot Tables in dataframe
I have raw data as following example. Variables row corresponds with range of Values; Time column corresponds with Values.
Then, I would like to arrange them in dataframe with expected output. 3 columns, Variables is principle columns and  Values and Time are the corresponding columns. But I don't know how to re-arrange.
I hope I explained clearly for you to understand my question.

```<code>Variables                  var1   var2   var3   var4
Time                     Values
2014-07-11 19:50:20           1      5      9     13
2014-07-11 19:50:30           2      6     10     14
2014-07-11 19:50:40           3      7     11     15
2014-07-11 19:50:50           4      8     12     16
</code>```

Expected output:

```<code>Time                  Variables  Values
2014-07-11 19:50:20   var1       1
2014-07-11 19:50:30   var1       2
2014-07-11 19:50:40   var1       3
2014-07-11 19:50:50   var1       4
2014-07-11 19:50:20   var2       5
2014-07-11 19:50:30   var2       6
2014-07-11 19:50:40   var2       7
2014-07-11 19:50:50   var2       8
</code>```

答:
I tried pd.melt and it's fine.

```<code>import pandas as pd
df1=pd.melt(df, id_vars='Time', value_vars=list(df.columns[1:]), var_name='Variables', value_name='Values')
</code>```

Body:
I have raw data as following example. Variables row corresponds with range of Values; Time column corresponds with Values.
Then, I would like to arrange them in dataframe with expected output. 3 columns, Variables is principle columns and  Values and Time are the corresponding columns. But I don't know how to re-arrange.
I hope I explained clearly for you to understand my question.

Variables                  var1   var2   var3   var4
Time                     Values
2014-07-11 19:50:20           1      5      9     13
2014-07-11 19:50:30           2      6     10     14
2014-07-11 19:50:40           3      7     11     15
2014-07-11 19:50:50           4      8     12     16

Expected output:

Time                  Variables  Values
2014-07-11 19:50:20   var1       1
2014-07-11 19:50:30   var1       2
2014-07-11 19:50:40   var1       3
2014-07-11 19:50:50   var1       4
2014-07-11 19:50:20   var2       5
2014-07-11 19:50:30   var2       6
2014-07-11 19:50:40   var2       7
2014-07-11 19:50:50   var2       8

Body:
I tried pd.melt and it's fine.

import pandas as pd
df1=pd.melt(df, id_vars='Time', value_vars=list(df.columns[1:]), var_name='Variables', value_name='Values')


问:
Find frequency of vector elements in a matrix
I have a matrix in R, here is a small example:

```<code>set.seed(1)
n.columns<-6
mat <- matrix(, nrow = 5, ncol = n.columns)
for(column in 1:n.columns){
  mat[, column] <- sample(1:10,5)
}
mat
</code>```

The matrix looks like this:

```<code>     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    3    9    3    5   10    4
[2,]    4   10    2    7    2    1
[3,]    5    6    6    8    6   10
[4,]    7    5   10    3    1    7
[5,]    2    1    5   10    9    3
</code>```

I also have a vector v of integers, v<-c(1,3,6), whose elements could theoretically appear in the matrix mat above.

What I am looking for is an overview of the number of times that each element in v appears in mat per column. For the current example this overview is

```<code>1: 0 1 0 0 1 1
3: 1 0 1 1 0 1
6: 0 1 1 0 1 0
</code>```

It is fairly straightforward to do this using for-loops and if-statements, but this solution is not very pretty.

Is there a professional way to do this?

答:
Using table:

```<code>table(mat[mat %in% v], col(mat)[mat %in% v])

#   1 2 3 4 5 6
# 1 0 1 0 0 1 1
# 3 1 0 1 1 0 1
# 6 0 1 1 0 1 0
</code>```

A drawback is a column with all values not in v will not be reported.

Body:
I have a matrix in R, here is a small example:

set.seed(1)
n.columns<-6
mat <- matrix(, nrow = 5, ncol = n.columns)
for(column in 1:n.columns){
  mat[, column] <- sample(1:10,5)
}
mat

The matrix looks like this:

     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    3    9    3    5   10    4
[2,]    4   10    2    7    2    1
[3,]    5    6    6    8    6   10
[4,]    7    5   10    3    1    7
[5,]    2    1    5   10    9    3

I also have a vector v of integers, v<-c(1,3,6), whose elements could theoretically appear in the matrix mat above.

What I am looking for is an overview of the number of times that each element in v appears in mat per column. For the current example this overview is

1: 0 1 0 0 1 1
3: 1 0 1 1 0 1
6: 0 1 1 0 1 0

It is fairly straightforward to do this using for-loops and if-statements, but this solution is not very pretty.

Is there a professional way to do this?

Body:
Using table:

table(mat[mat %in% v], col(mat)[mat %in% v])

#   1 2 3 4 5 6
# 1 0 1 0 0 1 1
# 3 1 0 1 1 0 1
# 6 0 1 1 0 1 0

A drawback is a column with all values not in v will not be reported.


问:
error with nodejs PUT request
I am getting an error with atttempting the following PUT request with nodejs.

```<code>var request = require('request');
request('http://1xx.xxx.xxx.xxx:8080/maintable/http%3A%2F%2Ftesturl.com
  %2F',
method: 'PUT',
json:{"Row":[{"key":"aHR0cHM6Ly9tYWt6ZW9uLndvcmRwcmVzcy5jb20v", "Cell":
 [{"column":"YmxvZ3NfZGF0YTp1cmw=", "$":
 "aHR0cHM6Ly9tYWt6ZW9uLndvcmRwcmVzcy5jb20v"},
 {"column":"YmxvZ3NfZGF0YTppbnNlcnREYXRl", "$": "MTQ5Njg3ODk1OA=="},
 {"column":"YmxvZ3NfZGF0YTpzdGF0dXM=", "$": "QWN0aXZl"}],
}]},
function (error, response, body) {
    console.log('error:', error);
    console.log('statusCode:', response && response.statusCode);
    console.log('body:', body);
}
);
</code>```

ERROR:

```<code> method: 'PUT',
    ^^^^^^
 SyntaxError: missing ) after argument list
 at createScript (vm.js:56:10)
 at Object.runInThisContext (vm.js:97:10)
 at Module._compile (module.js:542:28)
 at Object.Module._extensions..js (module.js:579:10)
 at Module.load (module.js:487:32)
 at tryModuleLoad (module.js:446:12)
 at Function.Module._load (module.js:438:3)
  at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:389:7)
at startup (bootstrap_node.js:149:9)
</code>```

Does anyone notice where the error is?

答:
missed '{' for the first parameter of the request function</p>

```<code>var request = require('request');
request({
    uri: 'http://1xx.xxx.xxx.xxx:8080/maintable/http%3A%2F%2Ftesturl.com',
    method: 'PUT',
    json:{
        "Row":[
            {
                "key":"aHR0cHM6Ly9tYWt6ZW9uLndvcmRwcmVzcy5jb20v",
                "Cell": [
                    {
                        "column":"YmxvZ3NfZGF0YTp1cmw=",
                        "$": "aHR0cHM6Ly9tYWt6ZW9uLndvcmRwcmVzcy5jb20v"
                    },
                    {
                        "column":"YmxvZ3NfZGF0YTppbnNlcnREYXRl",
                        "$": "MTQ5Njg3ODk1OA=="
                    },
                    {
                        "column":"YmxvZ3NfZGF0YTpzdGF0dXM=",
                        "$": "QWN0aXZl"
                    }
                ],
            }
        ]
    }
},
function (error, response, body) {
    console.log('error:', error);
    console.log('statusCode:', response && response.statusCode);
    console.log('body:', body);
});
</code>```

Title: error with nodejs PUT request

Body:
I am getting an error with atttempting the following PUT request with nodejs.

var request = require('request');
request('http://1xx.xxx.xxx.xxx:8080/maintable/http%3A%2F%2Ftesturl.com
  %2F',
method: 'PUT',
json:{"Row":[{"key":"aHR0cHM6Ly9tYWt6ZW9uLndvcmRwcmVzcy5jb20v", "Cell":
 [{"column":"YmxvZ3NfZGF0YTp1cmw=", "$":
 "aHR0cHM6Ly9tYWt6ZW9uLndvcmRwcmVzcy5jb20v"},
 {"column":"YmxvZ3NfZGF0YTppbnNlcnREYXRl", "$": "MTQ5Njg3ODk1OA=="},
 {"column":"YmxvZ3NfZGF0YTpzdGF0dXM=", "$": "QWN0aXZl"}],
}]},
function (error, response, body) {
    console.log('error:', error);
    console.log('statusCode:', response && response.statusCode);
    console.log('body:', body);
}
);

ERROR:

 method: 'PUT',
    ^^^^^^
 SyntaxError: missing ) after argument list
 at createScript (vm.js:56:10)
 at Object.runInThisContext (vm.js:97:10)
 at Module._compile (module.js:542:28)
 at Object.Module._extensions..js (module.js:579:10)
 at Module.load (module.js:487:32)
 at tryModuleLoad (module.js:446:12)
 at Function.Module._load (module.js:438:3)
  at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:389:7)
at startup (bootstrap_node.js:149:9)

Does anyone notice where the error is?

Body:
missed '{' for the first parameter of the request function

var request = require('request');
request({
    uri: 'http://1xx.xxx.xxx.xxx:8080/maintable/http%3A%2F%2Ftesturl.com',
    method: 'PUT',
    json:{
        "Row":[
            {
                "key":"aHR0cHM6Ly9tYWt6ZW9uLndvcmRwcmVzcy5jb20v",
                "Cell": [
                    {
                        "column":"YmxvZ3NfZGF0YTp1cmw=",
                        "$": "aHR0cHM6Ly9tYWt6ZW9uLndvcmRwcmVzcy5jb20v"
                    },
                    {
                        "column":"YmxvZ3NfZGF0YTppbnNlcnREYXRl",
                        "$": "MTQ5Njg3ODk1OA=="
                    },
                    {
                        "column":"YmxvZ3NfZGF0YTpzdGF0dXM=",
                        "$": "QWN0aXZl"
                    }
                ],
            }
        ]
    }
},
function (error, response, body) {
    console.log('error:', error);
    console.log('statusCode:', response && response.statusCode);
    console.log('body:', body);
});


问:
python - convert UTC timestamp to unixtime
I'm trying to convert my timestamp to unixtime paying attention to it not being UTC however the unixtime is incorrect.

```<code>import time
import datetime
from dateutil.parser import parse

time_str = '2017-03-09T15:44:40.000-05:00'

time_obj = parse(time_str)

print time_obj

unixtime = time.mktime(time_obj.timetuple())

print unixtime
</code>```

The unixtime it returns is 1489092280.0 which represents to 03/09/2017 @ 8:44pm (UTC) when what I want is 1489074280.

答:
time.mktime expects a broken-down local time and treats input as such, i.e. converts it to UTC and then builds a seconds-since-epoch timestamp. Since you already have the broken-down UTC time, you need to call calendar.timegm instead:

```<code>>>> unixtime = calendar.timegm(time_obj.timetuple())
>>> print unixtime
1489074280
</code>```

Body:
I'm trying to convert my timestamp to unixtime paying attention to it not being UTC however the unixtime is incorrect.

import time
import datetime
from dateutil.parser import parse

time_str = '2017-03-09T15:44:40.000-05:00'

time_obj = parse(time_str)

print time_obj

unixtime = time.mktime(time_obj.timetuple())

print unixtime

The unixtime it returns is 1489092280.0 which represents to 03/09/2017 @ 8:44pm (UTC) when what I want is 1489074280.

Body:
time.mktime expects a broken-down local time and treats input as such, i.e. converts it to UTC and then builds a seconds-since-epoch timestamp. Since you already have the broken-down UTC time, you need to call calendar.timegm instead:

>>> unixtime = calendar.timegm(time_obj.timetuple())
>>> print unixtime
1489074280


问:
GLSL attributes optimized out
So I'm about to loose my mind.

I'm writing an android app, a native activity to be exact. All is fine except that attributes and uniforms seems to be optimized out in my shader.

Vertex Shader:

```<code>#version 100

attribute vec3 position;

void main() {

    gl_Position = vec4(position, 1);

}
</code>```

Fragment Shader:

```<code>#version 100

precision highp float;

uniform vec3 color;

void main() {

    gl_FragColor = vec4(color, 1);

}
</code>```

Shader Compilation:

```<code>unsigned int shader = glCreateProgram();

unsigned int v = glCreateShader(GL_VERTEX_SHADER);
unsigned int f = glCreateShader(GL_FRAGMENT_SHADER);

glShaderSource(v, 1, &vertex, nullptr);
glShaderSource(f, 1, &fragment, nullptr);

glCompileShader(v);
if (check_error(v, GL_COMPILE_STATUS, false)) {
    LOGE("Failed to compile vertex shader");
}

glCompileShader(f);
if (check_error(f, GL_COMPILE_STATUS, false)) {
    LOGE("Failed to compile fragment shader");
}

glAttachShader(shader, v);
glAttachShader(shader, f);

glLinkProgram(shader);
if (check_error(shader, GL_LINK_STATUS, true)) {
    LOGE("Failed to link shader");
}

glValidateProgram(shader);
if (check_error(shader, GL_VALIDATE_STATUS, true)) {
    LOGE("Failed to validate shader");
}
</code>```

Error Checking Code:

```<code>static bool check_error(unsigned int shader, unsigned int param, bool isProgram) {
int res = 123;
char log[2048] = { 0 };
if (isProgram) {
    glGetProgramiv(shader, param, &res);
    if (res == 0) {
        glGetProgramInfoLog(shader, sizeof(log), 0, log);
        LOGE("Shader: %s", log);
        return true;
    }
} else {
    glGetShaderiv(shader, param, &res);
    if (res == 0) {
        glGetShaderInfoLog(shader, sizeof(log), 0, log);
        LOGD("Shader %s", log);
        return true;
    }
}

return false;
}
</code>```

Everything compiles just fine. But when I later call glGetAttribLocation to get the index of position, it return -1. I've also tried binding it before linking with glBindAttribLocation.

Querying all attributs with glGetActiveAttrib just return some junk. Same goes for the uniform "color" in the fragment shader.

I've tried running it on my phone (Galaxy S3) and on the Visual Studio Emulator For Android, same result on both of them.

My guess is that they get optimized out, but they shouldn't since I'm clearly using them and they contribute to the output.

Thanks in advance!

答:
After you compile the shaders and before you link them, you need to explicitly bind the attribute locations using glBindAttribLocation.

After you bind the locations, link the program.

Later, bind directly to the location you specified using glVertexAttribPointer (be sure to enable the stream with `glEnableVertexAttribArray).

Don't query, just set.  If you want to query, make sure that the shader program is enabled and the streams are bound and activated first.

Title: GLSL attributes optimized out

Body:
So I'm about to loose my mind.

I'm writing an android app, a native activity to be exact. All is fine except that attributes and uniforms seems to be optimized out in my shader.

Vertex Shader:

#version 100

attribute vec3 position;

void main() {

    gl_Position = vec4(position, 1);

}

Fragment Shader:

#version 100

precision highp float;

uniform vec3 color;

void main() {

    gl_FragColor = vec4(color, 1);

}

Shader Compilation:

unsigned int shader = glCreateProgram();

unsigned int v = glCreateShader(GL_VERTEX_SHADER);
unsigned int f = glCreateShader(GL_FRAGMENT_SHADER);

glShaderSource(v, 1, &vertex, nullptr);
glShaderSource(f, 1, &fragment, nullptr);

glCompileShader(v);
if (check_error(v, GL_COMPILE_STATUS, false)) {
    LOGE("Failed to compile vertex shader");
}

glCompileShader(f);
if (check_error(f, GL_COMPILE_STATUS, false)) {
    LOGE("Failed to compile fragment shader");
}

glAttachShader(shader, v);
glAttachShader(shader, f);

glLinkProgram(shader);
if (check_error(shader, GL_LINK_STATUS, true)) {
    LOGE("Failed to link shader");
}

glValidateProgram(shader);
if (check_error(shader, GL_VALIDATE_STATUS, true)) {
    LOGE("Failed to validate shader");
}

Error Checking Code:

static bool check_error(unsigned int shader, unsigned int param, bool isProgram) {
int res = 123;
char log[2048] = { 0 };
if (isProgram) {
    glGetProgramiv(shader, param, &res);
    if (res == 0) {
        glGetProgramInfoLog(shader, sizeof(log), 0, log);
        LOGE("Shader: %s", log);
        return true;
    }
} else {
    glGetShaderiv(shader, param, &res);
    if (res == 0) {
        glGetShaderInfoLog(shader, sizeof(log), 0, log);
        LOGD("Shader %s", log);
        return true;
    }
}

return false;
}

Everything compiles just fine. But when I later call glGetAttribLocation to get the index of position, it return -1. I've also tried binding it before linking with glBindAttribLocation.

Querying all attributs with glGetActiveAttrib just return some junk. Same goes for the uniform "color" in the fragment shader.

I've tried running it on my phone (Galaxy S3) and on the Visual Studio Emulator For Android, same result on both of them.

My guess is that they get optimized out, but they shouldn't since I'm clearly using them and they contribute to the output.

Thanks in advance!


问:
Postgres: Query that returns percentage
My SQL is rusty. I have a table that logs all HTTP requests and their status. What I am wanting to do is create a query that shows the percentage of the results where status='404 NOT FOUND' PER DAY

here is what the table looks like

```<code>articles=# select * from log limit 1;

             path              |       ip       | method | status |              time          |   id
-------------------------------+----------------+--------+--------+----------------------------+---------
 /article/balloon-goons-doomed | 198.51.100.108 | GET    | 200 OK |     2016-07-01 06:02:39-05 | 1688046
</code>```

I was able to get the raw counts like this, but not sure how to get the percentage

```<code>SELECT date_trunc('day', time) "day", count(*) as count FROM log WHERE
status='404 NOT FOUND' group by 1 ORDER BY 1;
</code>```

答:
Is it ok to select the total count in a sub query?</p>

```<code>SELECT date_trunc('day', time) as day, count(*) / totalCount.count * 100 as percentage
FROM log,
(
    SELECT count(*) FROM log
) totalCount
WHERE status='404 NOT FOUND' group by 1 ORDER BY 1;
</code>```

Title: Postgres: Query that returns percentage

Body:
My SQL is rusty. I have a table that logs all HTTP requests and their status. What I am wanting to do is create a query that shows the percentage of the results where status='404 NOT FOUND' PER DAY

here is what the table looks like

articles=# select * from log limit 1;

             path              |       ip       | method | status |              time          |   id
-------------------------------+----------------+--------+--------+----------------------------+---------
 /article/balloon-goons-doomed | 198.51.100.108 | GET    | 200 OK |     2016-07-01 06:02:39-05 | 1688046

I was able to get the raw counts like this, but not sure how to get the percentage

SELECT date_trunc('day', time) "day", count(*) as count FROM log WHERE
status='404 NOT FOUND' group by 1 ORDER BY 1;

Body:
Is it ok to select the total count in a sub query?

SELECT date_trunc('day', time) as day, count(*) / totalCount.count * 100 as percentage
FROM log,
(
    SELECT count(*) FROM log
) totalCount
WHERE status='404 NOT FOUND' group by 1 ORDER BY 1;


问:
Symfony 3.2 "security.firewall.map.context.main" has a dependency on a non-existent service ^my authentication handler^
On my personal Symfony 3.2 project (https://github.com/pc-magas/photoalbum) because I wanted to get a Json instead of redirecting based on http://www.webtipblog.com/adding-an-ajax-login-form-to-a-symfony-project/ I made the following authentication Manager:

```<code><?php

namespace AppBundle\Security;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\SecurityContextInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;

class AuthenticationHandler implements AuthenticationSuccessHandlerInterface, AuthenticationFailureHandlerInterface
{
    private $router;
    private $session;

    /**
     * Constructor
     *
     * @author  Joe Sexton <joe@webtipblog.com>
     * @param   RouterInterface $router
     * @param   Session $session
     */
    public function __construct( RouterInterface $router, Session $session )
    {
        $this->router  = $router;
        $this->session = $session;
    }

    /**
     * onAuthenticationSuccess
     *
     * @author  Joe Sexton <joe@webtipblog.com>
     * @param   Request $request
     * @param   TokenInterface $token
     * @return  Response
     */
    public function onAuthenticationSuccess( Request $request, TokenInterface $token )
    {
        // if AJAX login
        if ( $request->isXmlHttpRequest() ) {

            $array = array( 'status' => true ); // data to return via JSON
            $response = new Response( json_encode( $array ) );
            $response->headers->set( 'Content-Type', 'application/json' );

            return $response;

            // if form login
        } else {

            if ( $this->session->get('_security.main.target_path' ) ) {

                $url = $this->session->get( '_security.main.target_path' );

            } else {

                $url = $this->router->generate( 'home_page' );

            } // end if

            return new RedirectResponse( $url );

        }
    }

    /**
     * onAuthenticationFailure
     *
     * @author  Joe Sexton <joe@webtipblog.com>
     * @param   Request $request
     * @param   AuthenticationException $exception
     * @return  Response
     */
    public function onAuthenticationFailure( Request $request, AuthenticationException $exception )
    {
        // if AJAX login
        if ( $request->isXmlHttpRequest() ) {

            $array = array( 'status' => false, 'message' => $exception->getMessage() ); // data to return via JSON
            $response = new Response( json_encode( $array ) );
            $response->headers->set( 'Content-Type', 'application/json' );

            return $response;

            // if form login
        } else {

            // set authentication exception to session
            $request->getSession()->set(SecurityContextInterface::AUTHENTICATION_ERROR, $exception);

            return new RedirectResponse( $this->router->generate( 'login_route' ) );
        }
    }
}
</code>```

And I configured my services.yml like this:

```<code>parameters:

services:
  authentication_handler:
    class: AppBundle\Security\AuthenticationHandler
    public: false
    arguments: ["@router","@session"]
</code>```

And I configured security.yml like that:

```<code>security:
   encoders:
        FOS\UserBundle\Model\UserInterface: bcrypt

   role_hierarchy:
        ROLE_ADMIN:       ROLE_USER
        ROLE_SUPER_ADMIN: ROLE_ADMIN

   providers:
        fos_userbundle:
            id: fos_user.user_provider.username

   firewalls:
        main:
            pattern: ^/
            form_login:
                provider: fos_userbundle
                csrf_token_generator: security.csrf.token_manager
                check_path:      security_check_route
                success_handler: authentication_handler
                failure_handler: authentication_handler

            logout:       true
            anonymous:    true

   access_control:
        - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/admin/, role: ROLE_ADMIN }
</code>```

But I get the following Error:

The service "security.firewall.map.context.main" has a dependency on a non-existent service "authentication_handler".

Do you have any sort of idea how the prob will be solved? I have set the authentication_handler my service into services.yml file but I get the error mentioned above.

答:
Yes, you need to add the service

in services.xml

```<code> <service id="app.security.authentication_handler" class="AppBundle\Security\AuthenticationHandler">
   <argument type="service" id="router" />
   <argument type="service" id="session" />
   <argument type="service" id="doctrine.orm.entity_manager" />
 </service>
</code>```

or in services.yml

```<code>app.security.authentication_handler:
  class: AppBundle\Security\AuthenticationHandler
  arguments: ["@router", "@session", "@doctrine.orm.entity_manager" ]
</code>```

Body:
On my personal Symfony 3.2 project (https://github.com/pc-magas/photoalbum) because I wanted to get a Json instead of redirecting based on http://www.webtipblog.com/adding-an-ajax-login-form-to-a-symfony-project/ I made the following authentication Manager:

<?php

namespace AppBundle\Security;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\SecurityContextInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;

class AuthenticationHandler implements AuthenticationSuccessHandlerInterface, AuthenticationFailureHandlerInterface
{
    private $router;
    private $session;

    /**
     * Constructor
     *
     * @author  Joe Sexton <joe@webtipblog.com>
     * @param   RouterInterface $router
     * @param   Session $session
     */
    public function __construct( RouterInterface $router, Session $session )
    {
        $this->router  = $router;
        $this->session = $session;
    }

    /**
     * onAuthenticationSuccess
     *
     * @author  Joe Sexton <joe@webtipblog.com>
     * @param   Request $request
     * @param   TokenInterface $token
     * @return  Response
     */
    public function onAuthenticationSuccess( Request $request, TokenInterface $token )
    {
        // if AJAX login
        if ( $request->isXmlHttpRequest() ) {

            $array = array( 'status' => true ); // data to return via JSON
            $response = new Response( json_encode( $array ) );
            $response->headers->set( 'Content-Type', 'application/json' );

            return $response;

            // if form login
        } else {

            if ( $this->session->get('_security.main.target_path' ) ) {

                $url = $this->session->get( '_security.main.target_path' );

            } else {

                $url = $this->router->generate( 'home_page' );

            } // end if

            return new RedirectResponse( $url );

        }
    }

    /**
     * onAuthenticationFailure
     *
     * @author  Joe Sexton <joe@webtipblog.com>
     * @param   Request $request
     * @param   AuthenticationException $exception
     * @return  Response
     */
    public function onAuthenticationFailure( Request $request, AuthenticationException $exception )
    {
        // if AJAX login
        if ( $request->isXmlHttpRequest() ) {

            $array = array( 'status' => false, 'message' => $exception->getMessage() ); // data to return via JSON
            $response = new Response( json_encode( $array ) );
            $response->headers->set( 'Content-Type', 'application/json' );

            return $response;

            // if form login
        } else {

            // set authentication exception to session
            $request->getSession()->set(SecurityContextInterface::AUTHENTICATION_ERROR, $exception);

            return new RedirectResponse( $this->router->generate( 'login_route' ) );
        }
    }
}

And I configured my services.yml like this:

parameters:

services:
  authentication_handler:
    class: AppBundle\Security\AuthenticationHandler
    public: false
    arguments: ["@router","@session"]

And I configured security.yml like that:

security:
   encoders:
        FOS\UserBundle\Model\UserInterface: bcrypt

   role_hierarchy:
        ROLE_ADMIN:       ROLE_USER
        ROLE_SUPER_ADMIN: ROLE_ADMIN

   providers:
        fos_userbundle:
            id: fos_user.user_provider.username

   firewalls:
        main:
            pattern: ^/
            form_login:
                provider: fos_userbundle
                csrf_token_generator: security.csrf.token_manager
                check_path:      security_check_route
                success_handler: authentication_handler
                failure_handler: authentication_handler

            logout:       true
            anonymous:    true

   access_control:
        - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/admin/, role: ROLE_ADMIN }

But I get the following Error:

The service "security.firewall.map.context.main" has a dependency on a non-existent service "authentication_handler".

Do you have any sort of idea how the prob will be solved? I have set the authentication_handler my service into services.yml file but I get the error mentioned above.

Body:
Yes, you need to add the service

in services.xml

 <service id="app.security.authentication_handler" class="AppBundle\Security\AuthenticationHandler">
   <argument type="service" id="router" />
   <argument type="service" id="session" />
   <argument type="service" id="doctrine.orm.entity_manager" />
 </service>

or in services.yml

app.security.authentication_handler:
  class: AppBundle\Security\AuthenticationHandler
  arguments: ["@router", "@session", "@doctrine.orm.entity_manager" ]


问:
FullCalendar scheduler update resource JSON object
I'm working with Rails and FullCalendar Scheduler and I want to be able to update the JSON object I give as resource when I add a new one.

Here is a simplified version of my calendar options:

fullcalendar-settings.js

```<code>$(document).ready(function() {
    $('#calendar').fullCalendar({
        header: {
            left: 'promptResource, prev, next, today',
            center: 'title',
            right: 'agendaWeek, timelineDay'
        },
        customButtons: {
          promptResource: {
              text: '+ maker',
              click: function() {
                  var name = prompt('Name');
                  if (name) {
                      $('#calendar').fullCalendar(
                          'addResource', { title: name }, true // scroll to the new source?
                      );
                  }
              }
          }
        },
        defaultView: 'timelineDay',
        defaultDate: moment(),
        editable: true,
        resourceColumns: [
            {
                labelText: 'Client',
                field: 'title'
            }
        ],
        resources: 'scheduler.json',
        events: []
    });
});
</code>```

scheduler.json

```<code>[
  { "id": "1", "title": "LE" },
  { "id": "2", "title": "DB" },
  { "id": "3", "title": "VB" },
  { "id": "7", "title": "RL" }
]
</code>```

Resources are loaded from 'scheduler.json' and I have a button with which you can add a new resource but it is for now only temporary and disappear on reload.

So my question is how can I update the JSON object within 'scheduler.json' when I add a new resource ?

Thanks in advance

答: You need to learn Jquery Ajax. And you need to read the documentation of FullCalendar. There is no other way. But, if you need a quick fix you can watch this screencast. This will meet your requirement for sure I am guessing. </p>

Body:
I'm working with Rails and FullCalendar Scheduler and I want to be able to update the JSON object I give as resource when I add a new one.

Here is a simplified version of my calendar options:

fullcalendar-settings.js

$(document).ready(function() {
    $('#calendar').fullCalendar({
        header: {
            left: 'promptResource, prev, next, today',
            center: 'title',
            right: 'agendaWeek, timelineDay'
        },
        customButtons: {
          promptResource: {
              text: '+ maker',
              click: function() {
                  var name = prompt('Name');
                  if (name) {
                      $('#calendar').fullCalendar(
                          'addResource', { title: name }, true // scroll to the new source?
                      );
                  }
              }
          }
        },
        defaultView: 'timelineDay',
        defaultDate: moment(),
        editable: true,
        resourceColumns: [
            {
                labelText: 'Client',
                field: 'title'
            }
        ],
        resources: 'scheduler.json',
        events: []
    });
});

scheduler.json

[
  { "id": "1", "title": "LE" },
  { "id": "2", "title": "DB" },
  { "id": "3", "title": "VB" },
  { "id": "7", "title": "RL" }
]

Resources are loaded from 'scheduler.json' and I have a button with which you can add a new resource but it is for now only temporary and disappear on reload.

So my question is how can I update the JSON object within 'scheduler.json' when I add a new resource ?

Thanks in advance


问:
Rails 5 - Strong Parameters for Nested Attributes
I am having trouble structuring my nested attributes for my model Request.

The data is being passed in the correct way from my POST action.

What am I missing to whitelist these parameters?

Appreciate any help.

Console Output

```<code>Started POST "/requests" for 127.0.0.1 at 2017-06-08 10:57:15 -0400
Processing by RequestsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"fmvhoPxVpcHoqOd32mO/HJMrfaPUd+KbNqDJiSRs78U44Y0uL3prpTfU6wmw7PAwv0b+mRHXOGMLvD9bsZpxnw==", "request"=>{"concierge_name"=>"Alex", "concierge_number"=>"954-123-4567", "concierge_email"=>"alex@email.com", "client_name"=>"Adam", "client_number"=>"954-765-4321", "client_email"=>"adam@email.com", "hotel_employee"=>"0", "concierge_service"=>"0", "vip_promoter"=>"0", "arriving_with_client"=>"1", "client_alone"=>"0", "males"=>"", "females"=>"1", "table_minimum"=>"1000", "arrival_time(1i)"=>"2017", "arrival_time(2i)"=>"6", "arrival_time(3i)"=>"8", "arrival_time(4i)"=>"14", "arrival_time(5i)"=>"56", "table_location_ids"=>["1"], "drink_attributes"=>[{"id"=>"1", "quantity"=>"1"}, {"id"=>"2", "quantity"=>""}, {"id"=>"3", "quantity"=>""}, {"id"=>"4", "quantity"=>""}], "chaser_ids"=>["1"], "comments"=>""}, "commit"=>"Submit"}
Completed 500 Internal Server Error in 8ms (ActiveRecord: 0.0ms)

ActiveModel::UnknownAttributeError (unknown attribute 'drink_attributes' for Request.):
</code>```

app/models/request.rb

```<code>class Request < ApplicationRecord
    has_many :request_drinks
    has_many :drinks, through: :request_drinks

    accepts_nested_attributes_for :drinks
end
</code>```

app/model/drink.rb

```<code>class Drink < ApplicationRecord
    has_many :request_drinks
    has_many :requests, through: :request_drinks
end
</code>```

app/model/request_drink.rb

```<code>class RequestDrink < ApplicationRecord
    belongs_to :request
    belongs_to :drink
end
</code>```

app/controllers/request_controller.rb

```<code>class RequestsController < ApplicationController
  before_action :set_request, only: [:show,
                                     :edit,
                                     :update,
                                     :destroy]

  def index
    @requests = Request.search(params[:term], params[:filter], params[:page])
  end

  def show
  end

  def new
    @request = Request.new
    @drinks = Drink.active
  end

  def edit
  end

  def create
    @request = Request.new(request_params)

    respond_to do |format|
      if @request.save
        format.html { redirect_to thanks_path, notice: 'Request was successfully created.' }
        format.json { render :show, status: :created, location: @request }
      else
        format.html { render :new }
        format.json { render json: @request.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
    respond_to do |format|
      if @request.update(request_params)
        format.html { redirect_to @request, notice: 'Request was successfully updated.' }
        format.json { render :show, status: :ok, location: @request }
      else
        format.html { render :edit }
        format.json { render json: @request.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @request.destroy
    respond_to do |format|
      format.html { redirect_to requests_url, notice: 'Request was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private

    def set_request
      @request = Request.find(params[:id])
    end

    def request_params
      params.require(:request).permit(:concierge_name,
                                      :concierge_number,
                                      :concierge_email,
                                      :client_name,
                                      :client_number,
                                      :client_email,
                                      :hotel_employee,
                                      :concierge_service,
                                      :vip_promoter,
                                      :arriving_with_client,
                                      :client_alone,
                                      :people,
                                      :males,
                                      :females,
                                      :table_minimum,
                                      :arrival_time,
                                      :comments,
                                      :drink_attributes => [:id, :quantity]
      )
    end
end
</code>```

app/views/requests/_form.html.erb

```<code>...
    <div class="field-3">
      <h4>Drinks</h4>
      <% @drinks.all.each do |d| %>
        <%= hidden_field_tag "request[drink_attributes][][id]", d.id %>
        <%= number_field_tag "request[drink_attributes][][quantity]" %>
        <%= d.name %>
        <br />
      <% end %>
    </div>
...
</code>```

答:
You need to use the plural form of the object (i.e. drinks) when using nested attributes.

So, in your request_params change:

```<code>:drink_attributes => [:id, :quantity]
</code>```

to:

```<code>:drinks_attributes => [:id, :quantity]
</code>```

An you need to update your form too:

```<code>...
  <%= hidden_field_tag "request[drinks_attributes][][id]", d.id %>
  <%= number_field_tag "request[drinks_attributes][][quantity]" %>
...
</code>```

Body:
I am having trouble structuring my nested attributes for my model Request.

The data is being passed in the correct way from my POST action.

What am I missing to whitelist these parameters?

Appreciate any help.

Console Output

Started POST "/requests" for 127.0.0.1 at 2017-06-08 10:57:15 -0400
Processing by RequestsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"fmvhoPxVpcHoqOd32mO/HJMrfaPUd+KbNqDJiSRs78U44Y0uL3prpTfU6wmw7PAwv0b+mRHXOGMLvD9bsZpxnw==", "request"=>{"concierge_name"=>"Alex", "concierge_number"=>"954-123-4567", "concierge_email"=>"alex@email.com", "client_name"=>"Adam", "client_number"=>"954-765-4321", "client_email"=>"adam@email.com", "hotel_employee"=>"0", "concierge_service"=>"0", "vip_promoter"=>"0", "arriving_with_client"=>"1", "client_alone"=>"0", "males"=>"", "females"=>"1", "table_minimum"=>"1000", "arrival_time(1i)"=>"2017", "arrival_time(2i)"=>"6", "arrival_time(3i)"=>"8", "arrival_time(4i)"=>"14", "arrival_time(5i)"=>"56", "table_location_ids"=>["1"], "drink_attributes"=>[{"id"=>"1", "quantity"=>"1"}, {"id"=>"2", "quantity"=>""}, {"id"=>"3", "quantity"=>""}, {"id"=>"4", "quantity"=>""}], "chaser_ids"=>["1"], "comments"=>""}, "commit"=>"Submit"}
Completed 500 Internal Server Error in 8ms (ActiveRecord: 0.0ms)

ActiveModel::UnknownAttributeError (unknown attribute 'drink_attributes' for Request.):

app/models/request.rb

class Request < ApplicationRecord
    has_many :request_drinks
    has_many :drinks, through: :request_drinks

    accepts_nested_attributes_for :drinks
end

app/model/drink.rb

class Drink < ApplicationRecord
    has_many :request_drinks
    has_many :requests, through: :request_drinks
end

app/model/request_drink.rb

class RequestDrink < ApplicationRecord
    belongs_to :request
    belongs_to :drink
end

app/controllers/request_controller.rb

class RequestsController < ApplicationController
  before_action :set_request, only: [:show,
                                     :edit,
                                     :update,
                                     :destroy]

  def index
    @requests = Request.search(params[:term], params[:filter], params[:page])
  end

  def show
  end

  def new
    @request = Request.new
    @drinks = Drink.active
  end

  def edit
  end

  def create
    @request = Request.new(request_params)

    respond_to do |format|
      if @request.save
        format.html { redirect_to thanks_path, notice: 'Request was successfully created.' }
        format.json { render :show, status: :created, location: @request }
      else
        format.html { render :new }
        format.json { render json: @request.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
    respond_to do |format|
      if @request.update(request_params)
        format.html { redirect_to @request, notice: 'Request was successfully updated.' }
        format.json { render :show, status: :ok, location: @request }
      else
        format.html { render :edit }
        format.json { render json: @request.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @request.destroy
    respond_to do |format|
      format.html { redirect_to requests_url, notice: 'Request was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private

    def set_request
      @request = Request.find(params[:id])
    end

    def request_params
      params.require(:request).permit(:concierge_name,
                                      :concierge_number,
                                      :concierge_email,
                                      :client_name,
                                      :client_number,
                                      :client_email,
                                      :hotel_employee,
                                      :concierge_service,
                                      :vip_promoter,
                                      :arriving_with_client,
                                      :client_alone,
                                      :people,
                                      :males,
                                      :females,
                                      :table_minimum,
                                      :arrival_time,
                                      :comments,
                                      :drink_attributes => [:id, :quantity]
      )
    end
end

app/views/requests/_form.html.erb

...

Drinks

      <% @drinks.all.each do |d| %>
        <%= hidden_field_tag "request[drink_attributes][][id]", d.id %>
        <%= number_field_tag "request[drink_attributes][][quantity]" %>
        <%= d.name %>

      <% end %>

...

Body:
You need to use the plural form of the object (i.e. drinks) when using nested attributes.

So, in your request_params change:

:drink_attributes => [:id, :quantity]

to:

:drinks_attributes => [:id, :quantity]

An you need to update your form too:

...
  <%= hidden_field_tag "request[drinks_attributes][][id]", d.id %>
  <%= number_field_tag "request[drinks_attributes][][quantity]" %>
...


问:
Notifications not working in web extension (Firefox)
I am using the Developer Version of Firefox (Version 54.0a2, but also tried the normal Firefox with Version 51) and I want to include notifications in my web extension.

browser["notifications"] does not exist though.

Since it was not working in my extension and I thought maybe something was conflicting I created this very basic web-extension.

the manifest.json:

```<code>{
  "manifest_version": 2,
  "name": "Extension",
  "version": "1.0",

  "description": "...",

  "icons": {
    "48": "icons/icon-48.png"
  },

  "content_scripts": [
    {
      "matches": [
        "http://*/*",
        "https://*/*"
      ],
      "js": ["test.js"]
    }
  ],
  "permissions": ["notifications", "storage"]
}
</code>```

test.js (storage works just fine btw.)

```<code>if (browser["notifications"]) {
    console.log('Notifications exist!');

    browser.notifications.create({
      "type": "basic",
      "iconUrl": browser.extension.getURL("icons/icon-48.png"),
      "title": "test",
      "message": "test"
    });
  }
  else {
    //it always executes this part :/
    console.log('notifications do not exist');
    console.log(browser);
  }
</code>```

Debugging the add-on doesn´t show any errors either.

答:
Many of the apis exclusive for extensions can only be run inside background script. The usual technique if you need to run it from a content script is to send a message from content script to background script, handle the message in background script and run from there the command you wanted.

In your case, there are a few examples at the end of Notification Api, one of them being notify-link-clicks-i18n where you can view how they do the message passing to create the notification from the background script.

Body:
I am using the Developer Version of Firefox (Version 54.0a2, but also tried the normal Firefox with Version 51) and I want to include notifications in my web extension.

browser["notifications"] does not exist though.

Since it was not working in my extension and I thought maybe something was conflicting I created this very basic web-extension.

the manifest.json:

{
  "manifest_version": 2,
  "name": "Extension",
  "version": "1.0",

  "description": "...",

  "icons": {
    "48": "icons/icon-48.png"
  },

  "content_scripts": [
    {
      "matches": [
        "http://*/*",
        "https://*/*"
      ],
      "js": ["test.js"]
    }
  ],
  "permissions": ["notifications", "storage"]
}

test.js (storage works just fine btw.)

if (browser["notifications"]) {
    console.log('Notifications exist!');

    browser.notifications.create({
      "type": "basic",
      "iconUrl": browser.extension.getURL("icons/icon-48.png"),
      "title": "test",
      "message": "test"
    });
  }
  else {
    //it always executes this part :/
    console.log('notifications do not exist');
    console.log(browser);
  }

Debugging the add-on doesn´t show any errors either.


问:
Error while loading shared libraries: libjli.so in Java
I have ElementaryOS installed. I am running Processing IDE in the terminal by running ./processing in the processing-3.3.4 directory. I'm getting this error:

```<code>java: error while loading shared libraries: libjli.so: cannot open shared object file: No such file or directory
</code>```

答:
This is a known issue that is being worked on. As of this moment, it doesn't look like they have released a fix, so I would try the previous version.

In the future, I recommend searching with Google for the specific error you're getting before posting to a forum. It can be hard to know what to search for, so here's an explanation of my process.

First I tried searching for "elementary os" processing cannot open shared object file "libjli.so" but since that didn't give me anything obvious, I assumed that this is not a widespread problem with Elementary OS. Note that I put quotes around "elementary os" and "libjli.so". This ensures that Google treats these as phrases, so pages with the word "elementary" and the word "os" will not match unless those two words are side-by-side.

Next I searched for processing ide cannot open shared object file "libjli.so" which gave me a link to the main Issues page on the github project. On that page, I searched for libjli.so which gave me one result, which is the issue I linked here.

I hope that helps you in the future.

Body:
I have ElementaryOS installed. I am running Processing IDE in the terminal by running ./processing in the processing-3.3.4 directory. I'm getting this error:

java: error while loading shared libraries: libjli.so: cannot open shared object file: No such file or directory


问:
Trigger a job from Powershell
I would like to know how to create a task scheduler job from powershell for the following scenario.

The script runs between the hours of 6 AM and 9 PM Monday through Friday where the script will terminate if it runs longer than 30 minutes.

I have tried

```<code>$adminname=''
$adminpassword=''
$taskName = ""
$L = New-ScheduledTaskAction –Execute "PowerShell.exe" -Argument ''
$T = New-ScheduledTaskTrigger -Daily -At 06:30Pm -DaysOfWeek 'Monday', 'Tuesday', 'Wednesday','Thursday','Friday'
$P = New-ScheduledTaskPrincipal -UserId "" -LogonType Password -RunLevel Highest
$S = New-ScheduledTaskSettingsSet
Register-ScheduledTask -TaskName $taskName -Action $L -Trigger $T -User $adminname -Password $adminpassword -Settings $S
$task = get-scheduledtask -TaskName $taskName
$task.Triggers.repetition.Interval = 'PT15M'
$task | Set-ScheduledTask -User $adminname -Password $adminpassword
</code>```

The above code schedules the job from monday to friday. But could not get a way to apply the time stamp i.e to be run between  6AM to 9PM

I have tried adding $task.Triggers.ExecutionTimeLimit = 'PT30M for terminating job if it runs longer than 30 minutes. But its giving The property 'ExecutionTimeLimit' cannot be found on this object. Verify that the property exists and can be set. error

答:
New-ScheduledTaskAction : Sets What you want to run

New-ScheduledTaskTrigger : Set How often and when to start the run

Register-ScheduledTask : Create the Task

[TASK].Triggers.Repetition.Duration : How long the task time should run from start time

[TASK].Triggers.Repetition.Interval : How long the task should run before its killed

{PK means Pickup Time, Use PK for H(hours) M(Minutes) use P for Pickup for D(Days) Ex PK15H, P5D}

[TASK] | Set-ScheduledTask : Enable Task

```<code>$action = New-ScheduledTaskAction -Execute Powershell.exe
$trigger = New-ScheduledTaskTrigger -Weekly -At 6:30AM -DaysOfWeek 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'
$task = Register-ScheduledTask -TaskName "TESTTASK" -Trigger $trigger -Action $action -RunLevel Highest
$task.Triggers.Repetition.Duration = "PT15H"
$task.Triggers.Repetition.Interval = "PT15M"
$task | Set-ScheduledTask -User "USERNAME" -Password "PASSWORD"
</code>```

Title: Trigger a job from Powershell

Body:
I would like to know how to create a task scheduler job from powershell for the following scenario.

The script runs between the hours of 6 AM and 9 PM Monday through Friday where the script will terminate if it runs longer than 30 minutes.

I have tried

$adminname=''
$adminpassword=''
$taskName = ""
$L = New-ScheduledTaskAction –Execute "PowerShell.exe" -Argument ''
$T = New-ScheduledTaskTrigger -Daily -At 06:30Pm -DaysOfWeek 'Monday', 'Tuesday', 'Wednesday','Thursday','Friday'
$P = New-ScheduledTaskPrincipal -UserId "" -LogonType Password -RunLevel Highest
$S = New-ScheduledTaskSettingsSet
Register-ScheduledTask -TaskName $taskName -Action $L -Trigger $T -User $adminname -Password $adminpassword -Settings $S
$task = get-scheduledtask -TaskName $taskName
$task.Triggers.repetition.Interval = 'PT15M'
$task | Set-ScheduledTask -User $adminname -Password $adminpassword

The above code schedules the job from monday to friday. But could not get a way to apply the time stamp i.e to be run between  6AM to 9PM

I have tried adding $task.Triggers.ExecutionTimeLimit = 'PT30M for terminating job if it runs longer than 30 minutes. But its giving The property 'ExecutionTimeLimit' cannot be found on this object. Verify that the property exists and can be set. error

Body:
New-ScheduledTaskAction : Sets What you want to run

New-ScheduledTaskTrigger : Set How often and when to start the run

Register-ScheduledTask : Create the Task

[TASK].Triggers.Repetition.Duration : How long the task time should run from start time

[TASK].Triggers.Repetition.Interval : How long the task should run before its killed

{PK means Pickup Time, Use PK for H(hours) M(Minutes) use P for Pickup for D(Days) Ex PK15H, P5D}

[TASK] | Set-ScheduledTask : Enable Task

$action = New-ScheduledTaskAction -Execute Powershell.exe
$trigger = New-ScheduledTaskTrigger -Weekly -At 6:30AM -DaysOfWeek 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'
$task = Register-ScheduledTask -TaskName "TESTTASK" -Trigger $trigger -Action $action -RunLevel Highest
$task.Triggers.Repetition.Duration = "PT15H"
$task.Triggers.Repetition.Interval = "PT15M"
$task | Set-ScheduledTask -User "USERNAME" -Password "PASSWORD"


问:
64Bit Big Endian data from ushort array
I have a ushort array which holds two array items inside command.Data[].
I am able to combine those two item values and get 32Bit Big Endian value as UInt32 with the following picece of code.

```<code>UInt32 param32BitValue= (UInt32)command.Data[0] << 32 | command.Data[1];
</code>```

I have another parameter which holds 4 items inside ushort array and I want to combine those four values into ulong value like

(Illustration)

```<code>UInt64 param64BitValue= (UInt64)command.Data[0] << 64 | command.Data[1] << 64 | command.Data[2] << 64 | command.Data[3];
</code>```

Big or little endian format. How do I achieve this?

答:
Your first code snippet should actually shift by 16 bits, not 32, if command.Data really is a ushort[] array.

```<code>uint bigEndian32 = ((uint)command.Data[0] << 16) | command.Data[1];
</code>```

For 64-bit, you'd just keep shifting left by 16 bits more each time:

```<code>ulong bigEndian64 = ((ulong)command.Data[0] << 48) | (command.Data[1] << 32) | (command.Data[2] << 16) | command.Data[3];
</code>```

Title: 64Bit Big Endian data from ushort array

Body:
I have a ushort array which holds two array items inside command.Data[].
I am able to combine those two item values and get 32Bit Big Endian value as UInt32 with the following picece of code.

UInt32 param32BitValue= (UInt32)command.Data[0] << 32 | command.Data[1];

I have another parameter which holds 4 items inside ushort array and I want to combine those four values into ulong value like

(Illustration)

UInt64 param64BitValue= (UInt64)command.Data[0] << 64 | command.Data[1] << 64 | command.Data[2] << 64 | command.Data[3];

Big or little endian format. How do I achieve this?

Body:
Your first code snippet should actually shift by 16 bits, not 32, if command.Data really is a ushort[] array.

uint bigEndian32 = ((uint)command.Data[0] << 16) | command.Data[1];

For 64-bit, you'd just keep shifting left by 16 bits more each time:

ulong bigEndian64 = ((ulong)command.Data[0] << 48) | (command.Data[1] << 32) | (command.Data[2] << 16) | command.Data[3];


问:
Converting data type nvarchar with decimal place
I have a Job Costing report that I am building for a client of mine. Their Chart of Accounts contains a decimal to the tenth place (i.e. 1001.55). I am running into an issue where no matter what I do I can't get the nvarchar to convert to either floating, int or numeric. If I take out the last Where clause where I try to filter by COA 5310 then it runs without issue. What glaring obvious issue am I overlooking? Any help would be appreciated!

```<code>--Build Equiptment
Create Table tmpEquiptment
(
       [dtmDate] datetime
       ,[iCustID] int
       ,[Amount] money
       ,[COA_Number]  DECIMAL(18,2)
)
Insert into tmpEquiptment
       SELECT dtmDate, iCustID, (Register.Debit - Register.Credit), STR(COA.Number)
       From Register
       Inner Join COA on Register.AccountID = COA.ID
       WHERE TranType IN ('Payment', 'Invoice', 'Sale', 'Credit', 'Journal Entry', 'Check', 'Item Receipt', 'Bill', 'Vendor Credit', 'CC Charge', 'CC Credit', 'Deposit', 'Inventory Adjustment', 'Serialized Adjustment')
       AND Coa.Type in ('Cost of Goods Sold','Expense','Other Expense')
       AND Isnull(COA.iJobCostingType,0) In (2,3)
       AND Register.iCustID Is Not Null
       And Register.dtmDate Between '2016-01-01 00:00:00.000' AND '2018-01-01 00:00:00.000'
       And STR(COA.Number) = 5310
</code>```

--OR--

```<code>--Build Equiptment
Create Table tmpEquiptment
(
       [dtmDate] datetime
       ,[iCustID] int
       ,[Amount] money
       ,[COA_Number]  DECIMAL(18,2)
)
Insert into tmpEquiptment
       SELECT dtmDate, iCustID, (Register.Debit - Register.Credit), CONVERT(varchar(10), COA.Number)
       From Register
       Inner Join COA on Register.AccountID = COA.ID
       WHERE TranType IN ('Payment', 'Invoice', 'Sale', 'Credit', 'Journal Entry', 'Check', 'Item Receipt', 'Bill', 'Vendor Credit', 'CC Charge', 'CC Credit', 'Deposit', 'Inventory Adjustment', 'Serialized Adjustment')
       AND Coa.Type in ('Cost of Goods Sold','Expense','Other Expense')
       AND Isnull(COA.iJobCostingType,0) In (2,3)
       AND Register.iCustID Is Not Null
       And Register.dtmDate Between '2016-01-01 00:00:00.000' AND '2018-01-01 00:00:00.000'
       And CONVERT(varchar(10), COA.Number) = 5310
</code>```

--OR--

```<code>--Build Equiptment
Create Table tmpEquiptment
(
       [dtmDate] datetime
       ,[iCustID] int
       ,[Amount] money
       ,[COA_Number]  DECIMAL(18,2)
)
Insert into tmpEquiptment
       SELECT dtmDate, iCustID, (Register.Debit - Register.Credit), CONVERT(DECIMAL(18,2), COA.Number)
       From Register
       Inner Join COA on Register.AccountID = COA.ID
       WHERE TranType IN ('Payment', 'Invoice', 'Sale', 'Credit', 'Journal Entry', 'Check', 'Item Receipt', 'Bill', 'Vendor Credit', 'CC Charge', 'CC Credit', 'Deposit', 'Inventory Adjustment', 'Serialized Adjustment')
       AND Coa.Type in ('Cost of Goods Sold','Expense','Other Expense')
       AND Isnull(COA.iJobCostingType,0) In (2,3)
       AND Register.iCustID Is Not Null
       And Register.dtmDate Between '2016-01-01 00:00:00.000' AND '2018-01-01 00:00:00.000'
       And CONVERT(DECIMAL(18,2), COA.Number) = 5310
</code>```

--OR--

```<code>--Build Equiptment
Create Table tmpEquiptment
(
       [dtmDate] datetime
       ,[iCustID] int
       ,[Amount] money
       ,[COA_Number]  DECIMAL(18,2)
)
Insert into tmpEquiptment
       SELECT dtmDate, iCustID, (Register.Debit - Register.Credit), CAST([COA.Number] AS NVARCHAR(25))
       From Register
       Inner Join COA on Register.AccountID = COA.ID
       WHERE TranType IN ('Payment', 'Invoice', 'Sale', 'Credit', 'Journal Entry', 'Check', 'Item Receipt', 'Bill', 'Vendor Credit', 'CC Charge', 'CC Credit', 'Deposit', 'Inventory Adjustment', 'Serialized Adjustment')
       AND Coa.Type in ('Cost of Goods Sold','Expense','Other Expense')
       AND Isnull(COA.iJobCostingType,0) In (2,3)
       AND Register.iCustID Is Not Null
       And Register.dtmDate Between '2016-01-01 00:00:00.000' AND '2018-01-01 00:00:00.000'
       And CAST([COA.Number] AS NVARCHAR(25)) = 5310
</code>```

答:
Thanks to @Jacob H for the explanation behind bjones answer. This was an issue of simply over engineering a solution when it really was just an ID10T error. One can not use a int (read without quotes) for a String value (with single quotes)</p>

```<code>--Build Equiptment
Create Table tmpEquiptment
(
       [dtmDate] datetime
       ,[iCustID] int
       ,[Amount] money
       ,[COA_Number]  DECIMAL(18,2)
)
Insert into tmpEquiptment
       SELECT dtmDate, iCustID, (Register.Debit - Register.Credit), COA.Number
       From Register
       Inner Join COA on Register.AccountID = COA.ID
       WHERE TranType IN ('Payment', 'Invoice', 'Sale', 'Credit', 'Journal Entry', 'Check', 'Item Receipt', 'Bill', 'Vendor Credit', 'CC Charge', 'CC Credit', 'Deposit', 'Inventory Adjustment', 'Serialized Adjustment')
       AND Coa.Type in ('Cost of Goods Sold','Expense','Other Expense')
       AND Isnull(COA.iJobCostingType,0) In (2,3)
       AND Register.iCustID Is Not Null
       And Register.dtmDate Between '2016-01-01 00:00:00.000' AND '2018-01-01 00:00:00.000'
       And COA.Number = '5310'
</code>```

Body:
I have a Job Costing report that I am building for a client of mine. Their Chart of Accounts contains a decimal to the tenth place (i.e. 1001.55). I am running into an issue where no matter what I do I can't get the nvarchar to convert to either floating, int or numeric. If I take out the last Where clause where I try to filter by COA 5310 then it runs without issue. What glaring obvious issue am I overlooking? Any help would be appreciated!

--Build Equiptment
Create Table tmpEquiptment
(
       [dtmDate] datetime
       ,[iCustID] int
       ,[Amount] money
       ,[COA_Number]  DECIMAL(18,2)
)
Insert into tmpEquiptment
       SELECT dtmDate, iCustID, (Register.Debit - Register.Credit), STR(COA.Number)
       From Register
       Inner Join COA on Register.AccountID = COA.ID
       WHERE TranType IN ('Payment', 'Invoice', 'Sale', 'Credit', 'Journal Entry', 'Check', 'Item Receipt', 'Bill', 'Vendor Credit', 'CC Charge', 'CC Credit', 'Deposit', 'Inventory Adjustment', 'Serialized Adjustment')
       AND Coa.Type in ('Cost of Goods Sold','Expense','Other Expense')
       AND Isnull(COA.iJobCostingType,0) In (2,3)
       AND Register.iCustID Is Not Null
       And Register.dtmDate Between '2016-01-01 00:00:00.000' AND '2018-01-01 00:00:00.000'
       And STR(COA.Number) = 5310

--OR--

--Build Equiptment
Create Table tmpEquiptment
(
       [dtmDate] datetime
       ,[iCustID] int
       ,[Amount] money
       ,[COA_Number]  DECIMAL(18,2)
)
Insert into tmpEquiptment
       SELECT dtmDate, iCustID, (Register.Debit - Register.Credit), CONVERT(varchar(10), COA.Number)
       From Register
       Inner Join COA on Register.AccountID = COA.ID
       WHERE TranType IN ('Payment', 'Invoice', 'Sale', 'Credit', 'Journal Entry', 'Check', 'Item Receipt', 'Bill', 'Vendor Credit', 'CC Charge', 'CC Credit', 'Deposit', 'Inventory Adjustment', 'Serialized Adjustment')
       AND Coa.Type in ('Cost of Goods Sold','Expense','Other Expense')
       AND Isnull(COA.iJobCostingType,0) In (2,3)
       AND Register.iCustID Is Not Null
       And Register.dtmDate Between '2016-01-01 00:00:00.000' AND '2018-01-01 00:00:00.000'
       And CONVERT(varchar(10), COA.Number) = 5310

--OR--

--Build Equiptment
Create Table tmpEquiptment
(
       [dtmDate] datetime
       ,[iCustID] int
       ,[Amount] money
       ,[COA_Number]  DECIMAL(18,2)
)
Insert into tmpEquiptment
       SELECT dtmDate, iCustID, (Register.Debit - Register.Credit), CONVERT(DECIMAL(18,2), COA.Number)
       From Register
       Inner Join COA on Register.AccountID = COA.ID
       WHERE TranType IN ('Payment', 'Invoice', 'Sale', 'Credit', 'Journal Entry', 'Check', 'Item Receipt', 'Bill', 'Vendor Credit', 'CC Charge', 'CC Credit', 'Deposit', 'Inventory Adjustment', 'Serialized Adjustment')
       AND Coa.Type in ('Cost of Goods Sold','Expense','Other Expense')
       AND Isnull(COA.iJobCostingType,0) In (2,3)
       AND Register.iCustID Is Not Null
       And Register.dtmDate Between '2016-01-01 00:00:00.000' AND '2018-01-01 00:00:00.000'
       And CONVERT(DECIMAL(18,2), COA.Number) = 5310

--OR--

--Build Equiptment
Create Table tmpEquiptment
(
       [dtmDate] datetime
       ,[iCustID] int
       ,[Amount] money
       ,[COA_Number]  DECIMAL(18,2)
)
Insert into tmpEquiptment
       SELECT dtmDate, iCustID, (Register.Debit - Register.Credit), CAST([COA.Number] AS NVARCHAR(25))
       From Register
       Inner Join COA on Register.AccountID = COA.ID
       WHERE TranType IN ('Payment', 'Invoice', 'Sale', 'Credit', 'Journal Entry', 'Check', 'Item Receipt', 'Bill', 'Vendor Credit', 'CC Charge', 'CC Credit', 'Deposit', 'Inventory Adjustment', 'Serialized Adjustment')
       AND Coa.Type in ('Cost of Goods Sold','Expense','Other Expense')
       AND Isnull(COA.iJobCostingType,0) In (2,3)
       AND Register.iCustID Is Not Null
       And Register.dtmDate Between '2016-01-01 00:00:00.000' AND '2018-01-01 00:00:00.000'
       And CAST([COA.Number] AS NVARCHAR(25)) = 5310

Body:
Thanks to @Jacob H for the explanation behind bjones answer. This was an issue of simply over engineering a solution when it really was just an ID10T error. One can not use a int (read without quotes) for a String value (with single quotes)

--Build Equiptment
Create Table tmpEquiptment
(
       [dtmDate] datetime
       ,[iCustID] int
       ,[Amount] money
       ,[COA_Number]  DECIMAL(18,2)
)
Insert into tmpEquiptment
       SELECT dtmDate, iCustID, (Register.Debit - Register.Credit), COA.Number
       From Register
       Inner Join COA on Register.AccountID = COA.ID
       WHERE TranType IN ('Payment', 'Invoice', 'Sale', 'Credit', 'Journal Entry', 'Check', 'Item Receipt', 'Bill', 'Vendor Credit', 'CC Charge', 'CC Credit', 'Deposit', 'Inventory Adjustment', 'Serialized Adjustment')
       AND Coa.Type in ('Cost of Goods Sold','Expense','Other Expense')
       AND Isnull(COA.iJobCostingType,0) In (2,3)
       AND Register.iCustID Is Not Null
       And Register.dtmDate Between '2016-01-01 00:00:00.000' AND '2018-01-01 00:00:00.000'
       And COA.Number = '5310'


问:
Fragment doesn't fill screen properly
I'm instantiating a Fragment inside another Fragment. The inner fragment has its layout defined as match_parent for width and height. And their parent too.

This is the code for main Fragment. CustomFragment which is inside is the inner Fragment. Its a regular fragment with a calendar.

```<code>public class CalendarFragment extends Fragment {
...
public void onViewCreated( LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState ){
customFragment = new CustomFragment();
                    customFragment.setArguments( bundle );

                    FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
                    transaction.add( R.id.calendar_container, customFragment );
                    transaction.commit();
...
}
</code>```

When this fargment comes to life, the inner fragment which contains the calendar adjusts its height based on content of each calendar cell.
Screenshot. Notice the empty space:

If both fragments have match_parent in its layout why this behavior occurs?

答:
try to replace this line:

```<code>transaction.add( R.id.calendar_container, customFragment );
</code>```

with this line:

```<code>transaction.replace(R.id.calendar_container, customFragment);
</code>```

and add this line after the line of the commit:

```<code>getFragmentManager().executePendingTransactions();
</code>```

i hope it will help you, for me it's doing the work.

Title: Fragment doesn't fill screen properly

Body:
I'm instantiating a Fragment inside another Fragment. The inner fragment has its layout defined as match_parent for width and height. And their parent too.

This is the code for main Fragment. CustomFragment which is inside is the inner Fragment. Its a regular fragment with a calendar.

public class CalendarFragment extends Fragment {
...
public void onViewCreated( LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState ){
customFragment = new CustomFragment();
                    customFragment.setArguments( bundle );

                    FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
                    transaction.add( R.id.calendar_container, customFragment );
                    transaction.commit();
...
}

When this fargment comes to life, the inner fragment which contains the calendar adjusts its height based on content of each calendar cell.
Screenshot. Notice the empty space:

If both fragments have match_parent in its layout why this behavior occurs?

Body:
try to replace this line:

transaction.add( R.id.calendar_container, customFragment );

with this line:

transaction.replace(R.id.calendar_container, customFragment);

and add this line after the line of the commit:

getFragmentManager().executePendingTransactions();

i hope it will help you, for me it's doing the work.


问:
Fabric gradle plugin integrate with AS3.0(android-gradle-plugin-3.0)
Error:

Execution failed for task ':app:crashlyticsUploadDistributionPreviewRelease'.
   getMainOutputFile is no longer supported.  Use getOutputFileName if you need to determine the file name of the output.

When I call crashlyticsUploadDistributionRelease, the gradle console display these message to me,

I tried the latest fabric plugin(io.fabric.tools:gradle:1.22.1), I assume that fabric gradle plugin didn't support the latest android-gradle-plugin-3.0-x.

Here is more info about new gradle-plugin-variant-api, may be it it would help

答:
Mike from Fabric here.

Edit
Update to version 1.24.1 of the Fabric Gradle plugin for compatibility with Gradle 3.0.+.

Original
Yes, the Alpha versions of Android Studio and Gradle contain breaking changes and potentially bugs. We will be on the lookout for changes to Gradle and Android Studio to see if additional changes are needed on our end or if they are resolved by those tools.

If you need to continue to use Fabric, using a more stable version of Android Studio and Gradle is recommended.