问:
Issue in passport implementation in multi tenant laravel application
First things first, I am using Hyn-Multi Tenant in my laravel 6 application Where there is a central database [connection = system] handles multiple tenant database. So far this package has helped me a lot but my application needs passport implementation for apis which is not documented in the package.

However there are other tutorials which claim passport implementation on Hyn package. I followed them and able to create access token per tenant user.

This is my config/auth.php:

```<code>return [
'defaults' => [
        'guard' => 'web',
        'passwords' => 'system-users',
    ],

'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'system',
        ],

        'staff' => [
            'driver' => 'session',
            'provider' => 'staff',
        ],

        'api' => [
            'driver' => 'passport',
            'provider' => 'staff',
            'hash' => false,
        ],
        'student' => [
            'driver' => 'passport',
            'provider' => 'student',
            'hash' => false,
        ],
    ],

'providers' => [
        'system' => [
            'driver' => 'eloquent',
            'model' => App\Models\System\User::class,
        ],
        'staff' => [
            'driver' => 'eloquent',
            'model' => App\Models\Tenant\Staff::class,
        ],
        'student' => [
            'driver' => 'eloquent',
            'model' => App\Models\Tenant\Student::class,
        ],

        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],

</code>```

My each tenant models uses UsesTenantConnection trait

This is my EnforceTenancy middleware

```<code><?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Config;

class EnforceTenancy
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        Config::set('database.default', 'tenant');

        return $next($request);
    }
}

</code>```

This is my AuthServiceProvider.php

```<code>public function boot()
    {
        $this->registerPolicies();

        Passport::routes(null, ['middleware' => 'tenancy.enforce']);

        // FOLLOWING CODE IS HAVING PROBLEM
        //Passport::useTokenModel(OAuthAccessToken::class);
        //Passport::useClientModel(OAuthClient::class);
        //Passport::useAuthCodeModel(OAuthCode::class);
        //Passport::usePersonalAccessClientModel(OAuthPersonalAccessClient::class);

        $this->commands([
            \Laravel\Passport\Console\InstallCommand::class,
            \Laravel\Passport\Console\ClientCommand::class,
            \Laravel\Passport\Console\KeysCommand::class,
        ]);

        \Laravel\Passport\Passport::tokensExpireIn(\Carbon\Carbon::now()->addMinutes(10));
        \Laravel\Passport\Passport::refreshTokensExpireIn(\Carbon\Carbon::now()->addDays(1));
    }
</code>```

So far all good, now I am going to explain in points,

When I call createToken('MyApp') I am able to generate token on tenant db, for example:

```<code>if (Auth::guard('staff')->attempt(['email' => $request->email, 'password' => $request->password])) {

            $user = Auth::guard('staff')->user();

            $auth_tokens = $user->createToken('MyApp');

            $access_token = $auth_tokens->accessToken;
...
}
</code>```

but to access login protected apis, I am sending bearer access token in header

```<code>window.axios
                .get("/api/meta",{
                    headers: fetchAuthHeaders()
                })
                .then(response => {
                    if(true == response.data.status) {
                        var data = response.data.data;
                        this.school.name = data.school_meta.name;
                        this.school.logo = data.school_meta.logo;
                    } else{
                        alert(response.data.message);
                    }

                })
</code>```

api.php

```<code>Route::domain('{hostname}.lvh.me')->group(function () {
    Route::middleware('tenant.exists')->group(function () {
        Route::get('/get-oauth-secret', 'Tenant\MetaController@getOAuthData');
        Route::post('validate-login','Tenant\AuthController@validateLogin');

        Route::middleware(['auth:api'])->group(function (){
            Route::get('meta','Tenant\AuthController@getMetaData'); //this api
        });
    });

});

</code>```

I am getting response as {"message":"Unauthenticated."}

Once the token is generated in step 1, I copy this token and paste into postman's header section and uncomment the custom passport models in AuthServiceProvider.php as shown below

AuthServiceProvider.php

```<code>public function boot()
    {
        ...

        // UNCOMMENTED FOLLOWING CUSTOM PASSPORT MODELS
        Passport::useTokenModel(OAuthAccessToken::class);
        Passport::useClientModel(OAuthClient::class);
        Passport::useAuthCodeModel(OAuthCode::class);
        Passport::usePersonalAccessClientModel(OAuthPersonalAccessClient::class);

        ...
    }
</code>```

Now I can access api/meta route but while login and creating token I am getting error:

```<code>ErrorException: Trying to get property 'id' of non-object in file /home/winlappy1/Desktop/multi_tenancy/vendor/laravel/passport/src/PersonalAccessTokenFactory.php on line 98
</code>```

I just want to know where I am going wrong, I know my explanation is quite ambiguous and confusing but thats all how I can explain my issue. I am ready to provide more clarification but I need to resolve this issue.

答:
Try to add

```<code>\App\Http\Middleware\EnforceTenancy::class
</code>```

into the beginning of $middlewarePriority array in Kernel.php

Body:
First things first, I am using Hyn-Multi Tenant in my laravel 6 application Where there is a central database [connection = system] handles multiple tenant database. So far this package has helped me a lot but my application needs passport implementation for apis which is not documented in the package.

However there are other tutorials which claim passport implementation on Hyn package. I followed them and able to create access token per tenant user.

This is my config/auth.php:

return [
'defaults' => [
        'guard' => 'web',
        'passwords' => 'system-users',
    ],

'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'system',
        ],

        'staff' => [
            'driver' => 'session',
            'provider' => 'staff',
        ],

        'api' => [
            'driver' => 'passport',
            'provider' => 'staff',
            'hash' => false,
        ],
        'student' => [
            'driver' => 'passport',
            'provider' => 'student',
            'hash' => false,
        ],
    ],

'providers' => [
        'system' => [
            'driver' => 'eloquent',
            'model' => App\Models\System\User::class,
        ],
        'staff' => [
            'driver' => 'eloquent',
            'model' => App\Models\Tenant\Staff::class,
        ],
        'student' => [
            'driver' => 'eloquent',
            'model' => App\Models\Tenant\Student::class,
        ],

        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],

My each tenant models uses UsesTenantConnection trait

This is my EnforceTenancy middleware

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Config;

class EnforceTenancy
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        Config::set('database.default', 'tenant');

        return $next($request);
    }
}

This is my AuthServiceProvider.php

public function boot()
    {
        $this->registerPolicies();

        Passport::routes(null, ['middleware' => 'tenancy.enforce']);

        // FOLLOWING CODE IS HAVING PROBLEM
        //Passport::useTokenModel(OAuthAccessToken::class);
        //Passport::useClientModel(OAuthClient::class);
        //Passport::useAuthCodeModel(OAuthCode::class);
        //Passport::usePersonalAccessClientModel(OAuthPersonalAccessClient::class);

        $this->commands([
            \Laravel\Passport\Console\InstallCommand::class,
            \Laravel\Passport\Console\ClientCommand::class,
            \Laravel\Passport\Console\KeysCommand::class,
        ]);

        \Laravel\Passport\Passport::tokensExpireIn(\Carbon\Carbon::now()->addMinutes(10));
        \Laravel\Passport\Passport::refreshTokensExpireIn(\Carbon\Carbon::now()->addDays(1));
    }

So far all good, now I am going to explain in points,

When I call createToken('MyApp') I am able to generate token on tenant db, for example:

if (Auth::guard('staff')->attempt(['email' => $request->email, 'password' => $request->password])) {

            $user = Auth::guard('staff')->user();

            $auth_tokens = $user->createToken('MyApp');

            $access_token = $auth_tokens->accessToken;
...
}

but to access login protected apis, I am sending bearer access token in header

window.axios
                .get("/api/meta",{
                    headers: fetchAuthHeaders()
                })
                .then(response => {
                    if(true == response.data.status) {
                        var data = response.data.data;
                        this.school.name = data.school_meta.name;
                        this.school.logo = data.school_meta.logo;
                    } else{
                        alert(response.data.message);
                    }

                })

api.php

Route::domain('{hostname}.lvh.me')->group(function () {
    Route::middleware('tenant.exists')->group(function () {
        Route::get('/get-oauth-secret', 'Tenant\MetaController@getOAuthData');
        Route::post('validate-login','Tenant\AuthController@validateLogin');

        Route::middleware(['auth:api'])->group(function (){
            Route::get('meta','Tenant\AuthController@getMetaData'); //this api
        });
    });

});

I am getting response as {"message":"Unauthenticated."}

Once the token is generated in step 1, I copy this token and paste into postman's header section and uncomment the custom passport models in AuthServiceProvider.php as shown below

AuthServiceProvider.php

public function boot()
    {
        ...

        // UNCOMMENTED FOLLOWING CUSTOM PASSPORT MODELS
        Passport::useTokenModel(OAuthAccessToken::class);
        Passport::useClientModel(OAuthClient::class);
        Passport::useAuthCodeModel(OAuthCode::class);
        Passport::usePersonalAccessClientModel(OAuthPersonalAccessClient::class);

        ...
    }

Now I can access api/meta route but while login and creating token I am getting error:

ErrorException: Trying to get property 'id' of non-object in file /home/winlappy1/Desktop/multi_tenancy/vendor/laravel/passport/src/PersonalAccessTokenFactory.php on line 98

I just want to know where I am going wrong, I know my explanation is quite ambiguous and confusing but thats all how I can explain my issue. I am ready to provide more clarification but I need to resolve this issue.

Body:
Try to add

\App\Http\Middleware\EnforceTenancy::class

into the beginning of $middlewarePriority array in Kernel.php


来源: stackexchange

问:
How to customize not cms components in Spartacus
I have a task to override some general functionality in Spartacus core (angular component), which is used in other OTTB components (like CMS and not CMS).

The example is cx-generic-link.

But I faced with problem that the only way of customizing OOTB components are if they are cms Components.

Question: Is there any way to customize cx-generic-link (for instance display name "Maks" everywhere), so that all other Spartacus components (which I am using as a library) use my cx-generic-link, but not a OOTB cx-generic-link.

答: Other than CSS customisation there's currently no concept for this in Spartacus nor in Angular. We're working on a more generic concept to customise lower level components, but it's likely not going to make it in 2.0. It's still a stretch for 2.0 though, but with the various priorities we have, this is likely moving to a later release. </p>

ContentLicense: CC BY-SA 4.0


问:
Retrieve the contents of cookies using Java
I need to retrieve the properties of the cookies stored upon visiting a web page. Specifically,

Name

Host

Expiration Date

Is there a library that I can use?

EDIT: I apologize for the lack of detail..
I am employing Selenium to retrieve the WEB page. Asserting the presence of the cookie (and ultimately deleting it) is present in Selenium's native functionality. Reading the contents, however, is something I was hoping to do...

答:
You can use

selenium.getCookieByName("CookieName")

to read the cookie by its name. This returns the cookie value as String

selenium.getCookie()

to get all the cookies in the page. You can assign this to a string and read it.

Finally to delete it you can use :

selenium.deleteCookie("CookieName")

ContentLicense: CC BY-SA 3.0


问:
How to fill and expand a Button within a Frame Xamarin.Forms
I have different Buttons that I want to put inside the <Frame> control, all this with the aim of avoiding the overflow of the image within the <ListView>, but when putting the HorizontalOptions and VerticalOptions property in FillAndExpand is not filling the Frame, I attached an image of the problem

How can I make the <Button> inside the <Frame> fill the space? I have tried to give the Columns and Rows the Auto property and I have not succeeded.

How can I keep the size of the button (Height and Width) but without losing the frame?
How can I fill and expand the button inside a Frame?

Any help for me?

VIEW.XAML:

```<code><ListView
                ItemsSource="{Binding ListaInventario}"
                SelectionMode="None"
                VerticalOptions="FillAndExpand"
                IsRefreshing="{Binding IsRefreshing, Mode=TwoWay}"
                HasUnevenRows="True">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <StackLayout
                                Margin="0,4,0,0"
                            Orientation="Vertical">

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

                                    <Label
                                        Text="{Binding Id}"
                                        FontSize="Small"
                                        HorizontalOptions="Center"
                                        FontAttributes="Bold"
                                        HeightRequest="39"
                                        VerticalTextAlignment="Start"
                                        TextColor="{StaticResource das.color.texto}"
                                        Grid.Column="0"
                                        Grid.Row="0">
                                    </Label>

                                    <Label
                                        Text="{Binding NombreComercial}"
                                        HorizontalOptions="Start"
                                        FontSize="Small"
                                        MaxLines="3"
                                        HeightRequest="39"
                                        TextColor="{StaticResource das.color.texto}"
                                        VerticalOptions="Start"
                                        Grid.Column="1"
                                        Grid.Row="0">
                                    </Label>

                                    <Frame
                                        HorizontalOptions="End"
                                        BackgroundColor="Transparent"
                                        Grid.Column="2"
                                        Grid.Row="0">

                                         <Button
                                        ImageSource="ic_pdf"
                                        HeightRequest="35"
                                        WidthRequest="50"
                                        BackgroundColor="{StaticResource das.color.estado_primary}"
                                        HorizontalOptions="FillAndExpand"
                                        VerticalOptions="FillAndExpand"
                                        Command="{Binding HDSSisquimCommand}"/>

                                    </Frame>

                                </Grid>

                                <!---->

                                        <!--CANTIDAD-->
                                    <StackLayout
                                        Orientation="Horizontal"
                                        HorizontalOptions="FillAndExpand"
                                        Margin="0,1,0,2">

                                        <StackLayout
                                              Orientation="Horizontal"
                                              HorizontalOptions="Start"
                                              Margin="0,0,3,0">
                                            <Label
                                                HorizontalOptions="Start"
                                                HorizontalTextAlignment="Start"
                                                VerticalOptions="End"
                                                VerticalTextAlignment="Center"
                                                Text="Cantidad: "
                                                FontAttributes="Bold"
                                                FontSize="Small"
                                                HeightRequest="35"
                                                IsEnabled="{Binding EnabledEstimadoEntry}"></Label>
                                            <Entry
                                                HorizontalOptions="FillAndExpand"
                                                Placeholder="Cantidad"
                                                Keyboard="Numeric"
                                                HorizontalTextAlignment="Center"
                                                MaxLength="4"
                                                FontSize="Small"
                                                HeightRequest="35"
                                                Text="{Binding CantidadDecimal}"
                                                IsEnabled="{Binding EnabledContenedorEntry}">
                                                <VisualStateManager.VisualStateGroups>
                                                  <VisualStateGroup x:Name="CommonStatesEntry">
                                                  <VisualState x:Name="Normal">
                                                   <VisualState.Setters>
                                                     <Setter Property="BackgroundColor" Value="Transparent" />
                                                   </VisualState.Setters>
                                                 </VisualState>
                                                 <VisualState x:Name="Focused">
                                                    <VisualState.Setters>
                                                        <Setter Property="BackgroundColor" Value="LightGray" />
                                                    </VisualState.Setters>
                                                </VisualState>
                                                </VisualStateGroup>
                                              </VisualStateManager.VisualStateGroups>
                                            </Entry>
                                        </StackLayout>

                                        <!--UNIDAD-->
                                        <StackLayout
                                            Orientation="Horizontal"
                                            HorizontalOptions="FillAndExpand">
                                            <Label
                                                HorizontalOptions="Start"
                                                HorizontalTextAlignment="Start"
                                                VerticalOptions="End"
                                                VerticalTextAlignment="Center"
                                                Text="Unidad: "
                                                FontAttributes="Bold"
                                                FontSize="Small"
                                                HeightRequest="35"
                                                IsEnabled="{Binding EnabledEstimadoEntry}"></Label>
                                            <Picker
                                                iOSSpecific:Picker.UpdateMode = "WhenFinished"
                                                ItemsSource="{Binding ListaUnidadesMedida}"
                                                SelectedItem="{Binding SelectedUnidadMedida}"
                                                ItemDisplayBinding="{Binding NombreCorto}"
                                                Title="Unidad"
                                                FontSize="Small"
                                                HeightRequest="35"
                                                HorizontalOptions="FillAndExpand"
                                                IsEnabled="{Binding EnabledContenedor}">
                                                <VisualStateManager.VisualStateGroups>
                                                  <VisualStateGroup x:Name="CommonStatesPicker">
                                                      <VisualState x:Name="Normal">
                                                   <VisualState.Setters>
                                                     <Setter Property="BackgroundColor" Value="Transparent" />
                                                   </VisualState.Setters>
                                                 </VisualState>
                                                 <VisualState x:Name="Focused">
                                                    <VisualState.Setters>
                                                        <Setter Property="BackgroundColor" Value="LightGray" />
                                                    </VisualState.Setters>
                                                </VisualState>
                                                 </VisualStateGroup>
                                             </VisualStateManager.VisualStateGroups>
                                            </Picker>
                                        </StackLayout>

                                    </StackLayout>

                                <!-- TWO BUTTONS -->
                                <StackLayout
                                     Orientation="Horizontal"
                                        HorizontalOptions="End"
                                        Margin="0,1,0,2">

                                                <Button
                                                    Margin="0,0,2,0"
                                            ImageSource="ic_actualizar"
                                            BackgroundColor="{Binding ColorBotonActualizar}"
                                            HorizontalOptions="End"
                                            VerticalOptions="Center"
                                            HeightRequest="35"
                                            WidthRequest="50"
                                            Command="{Binding ActualizarSQCommand}"/>

                                               <Button
                                            ImageSource="ic_minus_sisquim"
                                            BackgroundColor="{StaticResource das.color.estado_danger}"
                                            HorizontalOptions="End"
                                            VerticalOptions="Center"
                                            HeightRequest="35"
                                            WidthRequest="50"
                                            Command="{Binding DesasociarSQCommand}"/>

                                </StackLayout>

                            </StackLayout>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
</code>```

答:
I only needed to set Padding="0" in the frame.

HorizontalOptions and VerticalOptions where not necessary to set as @Jessie Zhang -MSFT suggested.

```<code><Frame Padding="0">
    <Button />
</Frame>
</code>```

Body:
I have different Buttons that I want to put inside the <Frame> control, all this with the aim of avoiding the overflow of the image within the <ListView>, but when putting the HorizontalOptions and VerticalOptions property in FillAndExpand is not filling the Frame, I attached an image of the problem

How can I make the <Button> inside the <Frame> fill the space? I have tried to give the Columns and Rows the Auto property and I have not succeeded.

How can I keep the size of the button (Height and Width) but without losing the frame?
How can I fill and expand the button inside a Frame?

Any help for me?

VIEW.XAML:

<ListView
                ItemsSource="{Binding ListaInventario}"
                SelectionMode="None"
                VerticalOptions="FillAndExpand"
                IsRefreshing="{Binding IsRefreshing, Mode=TwoWay}"
                HasUnevenRows="True">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <StackLayout
                                Margin="0,4,0,0"
                            Orientation="Vertical">

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

                                    <Label
                                        Text="{Binding Id}"
                                        FontSize="Small"
                                        HorizontalOptions="Center"
                                        FontAttributes="Bold"
                                        HeightRequest="39"
                                        VerticalTextAlignment="Start"
                                        TextColor="{StaticResource das.color.texto}"
                                        Grid.Column="0"
                                        Grid.Row="0">

                                    <Label
                                        Text="{Binding NombreComercial}"
                                        HorizontalOptions="Start"
                                        FontSize="Small"
                                        MaxLines="3"
                                        HeightRequest="39"
                                        TextColor="{StaticResource das.color.texto}"
                                        VerticalOptions="Start"
                                        Grid.Column="1"
                                        Grid.Row="0">

                                    <Frame
                                        HorizontalOptions="End"
                                        BackgroundColor="Transparent"
                                        Grid.Column="2"
                                        Grid.Row="0">

                                         <Button
                                        ImageSource="ic_pdf"
                                        HeightRequest="35"
                                        WidthRequest="50"
                                        BackgroundColor="{StaticResource das.color.estado_primary}"
                                        HorizontalOptions="FillAndExpand"
                                        VerticalOptions="FillAndExpand"
                                        Command="{Binding HDSSisquimCommand}"/>

                                    </Frame>

                                </Grid>

                                    <StackLayout
                                        Orientation="Horizontal"
                                        HorizontalOptions="FillAndExpand"
                                        Margin="0,1,0,2">

                                        <StackLayout
                                              Orientation="Horizontal"
                                              HorizontalOptions="Start"
                                              Margin="0,0,3,0">
                                            <Label
                                                HorizontalOptions="Start"
                                                HorizontalTextAlignment="Start"
                                                VerticalOptions="End"
                                                VerticalTextAlignment="Center"
                                                Text="Cantidad: "
                                                FontAttributes="Bold"
                                                FontSize="Small"
                                                HeightRequest="35"
                                                IsEnabled="{Binding EnabledEstimadoEntry}">
                                            <Entry
                                                HorizontalOptions="FillAndExpand"
                                                Placeholder="Cantidad"
                                                Keyboard="Numeric"
                                                HorizontalTextAlignment="Center"
                                                MaxLength="4"
                                                FontSize="Small"
                                                HeightRequest="35"
                                                Text="{Binding CantidadDecimal}"
                                                IsEnabled="{Binding EnabledContenedorEntry}">
                                                <VisualStateManager.VisualStateGroups>
                                                  <VisualStateGroup x:Name="CommonStatesEntry">
                                                  <VisualState x:Name="Normal">
                                                   <VisualState.Setters>
                                                     <Setter Property="BackgroundColor" Value="Transparent" />
                                                   </VisualState.Setters>
                                                 </VisualState>
                                                 <VisualState x:Name="Focused">
                                                    <VisualState.Setters>
                                                        <Setter Property="BackgroundColor" Value="LightGray" />
                                                    </VisualState.Setters>
                                                </VisualState>
                                                </VisualStateGroup>
                                              </VisualStateManager.VisualStateGroups>
                                            </Entry>
                                        </StackLayout>

                                        <StackLayout
                                            Orientation="Horizontal"
                                            HorizontalOptions="FillAndExpand">
                                            <Label
                                                HorizontalOptions="Start"
                                                HorizontalTextAlignment="Start"
                                                VerticalOptions="End"
                                                VerticalTextAlignment="Center"
                                                Text="Unidad: "
                                                FontAttributes="Bold"
                                                FontSize="Small"
                                                HeightRequest="35"
                                                IsEnabled="{Binding EnabledEstimadoEntry}">
                                            <Picker
                                                iOSSpecific:Picker.UpdateMode = "WhenFinished"
                                                ItemsSource="{Binding ListaUnidadesMedida}"
                                                SelectedItem="{Binding SelectedUnidadMedida}"
                                                ItemDisplayBinding="{Binding NombreCorto}"
                                                Title="Unidad"
                                                FontSize="Small"
                                                HeightRequest="35"
                                                HorizontalOptions="FillAndExpand"
                                                IsEnabled="{Binding EnabledContenedor}">
                                                <VisualStateManager.VisualStateGroups>
                                                  <VisualStateGroup x:Name="CommonStatesPicker">
                                                      <VisualState x:Name="Normal">
                                                   <VisualState.Setters>
                                                     <Setter Property="BackgroundColor" Value="Transparent" />
                                                   </VisualState.Setters>
                                                 </VisualState>
                                                 <VisualState x:Name="Focused">
                                                    <VisualState.Setters>
                                                        <Setter Property="BackgroundColor" Value="LightGray" />
                                                    </VisualState.Setters>
                                                </VisualState>
                                                 </VisualStateGroup>
                                             </VisualStateManager.VisualStateGroups>
                                            </Picker>
                                        </StackLayout>

                                    </StackLayout>

                                <StackLayout
                                     Orientation="Horizontal"
                                        HorizontalOptions="End"
                                        Margin="0,1,0,2">

                                                <Button
                                                    Margin="0,0,2,0"
                                            ImageSource="ic_actualizar"
                                            BackgroundColor="{Binding ColorBotonActualizar}"
                                            HorizontalOptions="End"
                                            VerticalOptions="Center"
                                            HeightRequest="35"
                                            WidthRequest="50"
                                            Command="{Binding ActualizarSQCommand}"/>

                                               <Button
                                            ImageSource="ic_minus_sisquim"
                                            BackgroundColor="{StaticResource das.color.estado_danger}"
                                            HorizontalOptions="End"
                                            VerticalOptions="Center"
                                            HeightRequest="35"
                                            WidthRequest="50"
                                            Command="{Binding DesasociarSQCommand}"/>

                                </StackLayout>

                            </StackLayout>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>

Body:
I only needed to set Padding="0" in the frame.

HorizontalOptions and VerticalOptions where not necessary to set as @Jessie Zhang -MSFT suggested.

<Frame Padding="0">
    <Button />
</Frame>


问:
Linkedin Lead Gen Forms webhook API
I did not find the webhook of LinkedIn. Please provide the API to set up a webhook in the ads form.

the API I found is Documentation

but I did not find the Linkedin Lead Gen Forms webhook API.

答:
Did you mean this?
Lead Notification Webhooks</p>

Title: Linkedin Lead Gen Forms webhook API


问:
TypeError: props.tracks.map is not a function
I'm currently working on a react app exercise based around creating Spotify playlists. Here is the primary code-base:

App.js

```<code>import React from 'react';
import './App.css';
import SearchBar from'../SearchBar/SearchBar';
import SearchResults from '../SearchResults/SearchResults';
import Playlist from '../Playlist/Playlist';

const track = {
  name: "Hello",
  artist: "Again",
  album: "Friend of a friend",
  id: 0
};

const tracks = [track, track, track];

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      searchResults: tracks,
      playlistName: "DEFAULT",
      playlistTracks: tracks
    };
    this.addTrack = this.addTrack.bind(this);
    this.removeTrack = this.removeTrack.bind(this);
  }

  addTrack(track) {
    this.state.playlistTracks.map(id => {
      if(track.id === id)
        return;
    });
    this.setState((state, track) => ({
      playlistTracks: state.playlistTracks.push(track)
    }));
  }

  removeTrack(track) {
    this.state.playlistTracks.map(id => {
      if(track.id === id)
        {
          this.setState((state, track) => ({
            playlistTracks: state.playlistTracks.remove(track)
          }));
        }
    });
  }

  render(){
  return (
    <div>
    <h1>Ja<span className="highlight">mmm</span>ing</h1>
      <div className="App">
        <SearchBar />
        <div className="App-playlist">
          <SearchResults searchResults={this.state.searchResults} onAdd= {this.addTrack}/>
          <Playlist name= {this.state.playlistName} tracks= {this.state.playlistTracks} onRemove= {this.removeTrack}/>
        </div>
      </div>
    </div>
  );
  }
}

export default App;
</code>```

Playlist.js

```<code>
import React from 'react';
import './Playlist.css';
import TrackList from '../TrackList/TrackList';

function Playlist(props) {
    return (
        <div className="Playlist">
        <input value="New Playlist"/>
        <button className="Playlist-save">SAVE TO SPOTIFY</button>
        <TrackList tracks= {props.tracks} onRemove= {props.onRemove} isRemoval= {true}/>
        </div>
    );
}

export default Playlist;
</code>```

```<code>import React from 'react';
import './SearchBar.css';

function SearchBar () {
        return (
            <div className="SearchBar">
            <input placeholder="Enter A Song, Album, or Artist" />
            <button className="SearchButton">SEARCH</button>
            </div>
        );
}

export default SearchBar;
</code>```

SearchBar.js

```<code>import React from 'react';
import './SearchBar.css';

function SearchBar () {
        return (
            <div className="SearchBar">
            <input placeholder="Enter A Song, Album, or Artist" />
            <button className="SearchButton">SEARCH</button>
            </div>
        );
}

export default SearchBar;
</code>```

SearchResults.js

```<code>import React from 'react';
import './SearchResults.css';
import TrackList from '../TrackList/TrackList';

function SearchResults (props) {
        return (
            <div className="SearchResults">
            <h2>Results</h2>
            <TrackList tracks={props.searchResults} onAdd= {props.onAdd} isRemoval= {false}/>
            </div>
        );
}

export default SearchResults;
</code>```

Track.js

```<code>import React from 'react';
import './Track.css';

class Track extends React.Component {
    constructor(props) {
        super(props);
        this.addTrack = this.addTrack.bind(this);
        this.removeTrack = this.addTrack.bind(this);
    }

    addTrack() {
        this.props.onAdd(this.props.track);
    }

    removeTrack() {
        this.props.onRemove(this.props.track);
    }

    render() {
        return (
            <div className="Track">
                    <div className="Track-information">
                        <h3>{ this.props.track.name }</h3>
                        <p>{ this.props.track.artist } | { this.props.track.album }</p>
                        <div onClick= {this.addTrack}>+</div>
                        <div onClick= {this.removeTrack}>-</div>
                    </div>
            </div>
        );
}
}

export default Track;
</code>```

TrackList.js

```<code>import React from 'react';
import './TrackList.css';
import Track from '../Track/Track';

function TracklList (props) {
        return (
            <div className="TrackList">
            {
                props.tracks.map(track => {
                    return <Track
                        track={track}
                        key={track.id}
                        onAdd= {props.onAdd}
                        onRemoval= {props.onRemoval}
                        isRemove= {props.isRemove}
                    />;
                })
            }
            </div>
        );
}

export default TracklList;
</code>```

It's a very baseline application at the moment but I'm trying to test a certain functionality so far. I am trying to test the process of adding a song from the Results section into the Playlist. However, when I click the plus icon on one of the songs, I get the following bug:

The bug only pops up after I click the plus icon so my initial assumptions is that I am changing the state object from an array to a list. however, I don't kow how that is the case. Anyway, I could definitely use a second opinion so far!

答:
Array.push mutate the calling array and returns a number indicate the length of the new array.

In your addTrack method, your old playlistTracks state was mutated and new state was set to be a number instead of the new array.

Use the spread syntax to add new item to your array in an immutable way.

Also setState accept a new state, or a function that received old state and return new state, track should be received from the addTrack method

P/S: the .map above the setState seems like it won't work as intended.

addTrack(track) {
    /*
     * NOTE: the code below doesn't affect anything since `map`
     * will be applied on each item and does not stop when you `return`
     * also, it seems like `playlistTracks` is an array of object, but was
     * used as an array of string here
     */
    this.state.playlistTracks.map(id => {
        if (track.id === id)
            return;
    });
    this.setState((state/* ,track -- I think this should be removed */) => ({
        // old code: playlistTracks: state.playlistTracks.push(track)
        playlistTracks: [...state.playlistTracks, track]
    }));
}
```

Body:
I'm currently working on a react app exercise based around creating Spotify playlists. Here is the primary code-base:

App.js

import React from 'react';
import './App.css';
import SearchBar from'../SearchBar/SearchBar';
import SearchResults from '../SearchResults/SearchResults';
import Playlist from '../Playlist/Playlist';

const track = {
  name: "Hello",
  artist: "Again",
  album: "Friend of a friend",
  id: 0
};

const tracks = [track, track, track];

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      searchResults: tracks,
      playlistName: "DEFAULT",
      playlistTracks: tracks
    };
    this.addTrack = this.addTrack.bind(this);
    this.removeTrack = this.removeTrack.bind(this);
  }

  addTrack(track) {
    this.state.playlistTracks.map(id => {
      if(track.id === id)
        return;
    });
    this.setState((state, track) => ({
      playlistTracks: state.playlistTracks.push(track)
    }));
  }

  removeTrack(track) {
    this.state.playlistTracks.map(id => {
      if(track.id === id)
        {
          this.setState((state, track) => ({
            playlistTracks: state.playlistTracks.remove(track)
          }));
        }
    });
  }

  render(){
  return (

Jammming

        <SearchBar />

          <SearchResults searchResults={this.state.searchResults} onAdd= {this.addTrack}/>
          <Playlist name= {this.state.playlistName} tracks= {this.state.playlistTracks} onRemove= {this.removeTrack}/>

  );
  }
}

export default App;

Playlist.js

import React from 'react';
import './Playlist.css';
import TrackList from '../TrackList/TrackList';

function Playlist(props) {
    return (

        <input value="New Playlist"/>
        <button className="Playlist-save">SAVE TO SPOTIFY</button>
        <TrackList tracks= {props.tracks} onRemove= {props.onRemove} isRemoval= {true}/>

    );
}

export default Playlist;

import React from 'react';
import './SearchBar.css';

function SearchBar () {
        return (

            <input placeholder="Enter A Song, Album, or Artist" />
            <button className="SearchButton">SEARCH</button>

        );
}

export default SearchBar;

SearchBar.js

import React from 'react';
import './SearchBar.css';

function SearchBar () {
        return (

            <input placeholder="Enter A Song, Album, or Artist" />
            <button className="SearchButton">SEARCH</button>

        );
}

export default SearchBar;

SearchResults.js

import React from 'react';
import './SearchResults.css';
import TrackList from '../TrackList/TrackList';

function SearchResults (props) {
        return (

Results

            <TrackList tracks={props.searchResults} onAdd= {props.onAdd} isRemoval= {false}/>

        );
}

export default SearchResults;

Track.js

import React from 'react';
import './Track.css';

class Track extends React.Component {
    constructor(props) {
        super(props);
        this.addTrack = this.addTrack.bind(this);
        this.removeTrack = this.addTrack.bind(this);
    }

    addTrack() {
        this.props.onAdd(this.props.track);
    }

    removeTrack() {
        this.props.onRemove(this.props.track);
    }

    render() {
        return (

{ this.props.track.name }

{ this.props.track.artist } | { this.props.track.album }

+

-

        );
}
}

export default Track;

TrackList.js

import React from 'react';
import './TrackList.css';
import Track from '../Track/Track';

function TracklList (props) {
        return (

            {
                props.tracks.map(track => {
                    return <Track
                        track={track}
                        key={track.id}
                        onAdd= {props.onAdd}
                        onRemoval= {props.onRemoval}
                        isRemove= {props.isRemove}
                    />;
                })
            }

        );
}

export default TracklList;

It's a very baseline application at the moment but I'm trying to test a certain functionality so far. I am trying to test the process of adding a song from the Results section into the Playlist. However, when I click the plus icon on one of the songs, I get the following bug:

The bug only pops up after I click the plus icon so my initial assumptions is that I am changing the state object from an array to a list. however, I don't kow how that is the case. Anyway, I could definitely use a second opinion so far!


问:
What is the correct way to set State according to fetch data?
I did search about this but I could not find explanation which way should be valid and followed.

If we want to add new data our state , for sure we are using immutable way like map the entire data to create new array or filter to delete and so on. However I cannot figure out which way is appropriate when data is fetched from server and why? Do I really need to iterate entire array or create deep copy of object?

Way 1

```<code>const [data, setData] = useState([]);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/posts')
      .then((response) => {
        return response.json();
      })
      .then(myJson => {
        const newData = [];
        myJson.forEach(item => newData.push(item));
        setData(newData);
      });
  }, []);
</code>```

Way 2

```<code>const [data, setData] = useState([]);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/posts')
      .then((response) => {
        return response.json();
      })
      .then(myJson => {
        setData(myJson);
      });
  }, []);
</code>```

答: Both way are setting state using immutable way, to me if you need to process the data for example filter, format, or delete in the frontend, you will need to use way 1. If the data do not need to be processed, I will recommend way 2. Furthermore I will recommend prepare the data as you needed in the database or backend, then send it to frontend. </p>

Body:
I did search about this but I could not find explanation which way should be valid and followed.

If we want to add new data our state , for sure we are using immutable way like map the entire data to create new array or filter to delete and so on. However I cannot figure out which way is appropriate when data is fetched from server and why? Do I really need to iterate entire array or create deep copy of object?

Way 1

const [data, setData] = useState([]);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/posts')
      .then((response) => {
        return response.json();
      })
      .then(myJson => {
        const newData = [];
        myJson.forEach(item => newData.push(item));
        setData(newData);
      });
  }, []);

Way 2

const [data, setData] = useState([]);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/posts')
      .then((response) => {
        return response.json();
      })
      .then(myJson => {
        setData(myJson);
      });
  }, []);


问:
How can I trigger on mouse movement Variable font in different section?
I was looking to trigger different sections with a variable font based on my mouse movement.

For the first section, everything looks great, but when I tried to trigger the second section, it does not work as I expected since is connected to the first one I guess.

I would need to make the section working independently and in the correct way (to have an idea see section one how react in debug mode)

I was wondering what I have to modify in my Javascript code to make my snippet work with all the sections I want, working independently with their respective variable font interaction. Any ideas?

$('.square').on('mousemove', function(e) {
  var x = e.pageX - $(this).offset().left;
  var y = e.pageY;
  var $tlSquare = $('.division--top.division--left');
  var $trSquare = $('.division--top.division--right');
  var $blSquare = $('.division--bottom.division--left');
  var $brSquare = $('.division--bottom.division--right');
  var squareWidth = $(this).width(),
    squareHeight = $(this).height();

  $tlSquare.width(x).height(y);
  $trSquare.width(squareWidth - x).height(y);
  $blSquare.width(x).height(squareHeight - y);
  $brSquare.width(squareWidth - x).height(squareHeight - y);

  stretchLetter(false);
});

stretchLetter(false);

$('.square').on('mouseleave', function() {
  $('.division').width('50%').height('50%');
  $('.letter').css('transform', '');
  stretchLetter(false);
});

function stretchLetter(animation) {
  $('.letter').each(function() {
    var parentWidth = $(this).parent().width();
    var parentHeight = $(this).parent().height();
    var thisWidth = $(this).width();
    var thisHeight = $(this).height();
    var widthPercent = parentWidth / thisWidth;
    var heightPercent = parentHeight / thisHeight;
    var timing = animation == true ? .5 : 0;

    TweenMax.to($(this), timing, {
      scaleX: widthPercent,
      scaleY: heightPercent
    })
    //$(this).css('transform', 'scalex('+ widthPercent +') scaley('+ heightPercent +')');
  });
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body,
html {
  margin: 0;
  padding: 0;
  font-weight: bold;
  font-family: helvetica;
}

section {
  height: 200px;
  background: blue;
  color: white;
  font-size: 28px;
}

.wrapper {
  display: flex;
  justify-content: center;
  /*justify-content: flex-end;*/
  width: 100%;
  height: 100vh;
  //background-color: blue;
  overflow: hidden;
}

.square {
  display: flex;
  flex-wrap: wrap;
  width: 100vh;
  height: 100vh;
  background-color: black;
}

.square-2 {
  display: flex;
  flex-wrap: wrap;
  width: 100vh;
  height: 100vh;
  background-color: yellow;
}

.division {
  //display: flex;
  //align-items: center;
  //justify-content: center;
  width: 50%;
  height: 50%;
  //background-color: red;
  //border: 1px solid white;
  box-sizing: border-box;
}

.letter {
  cursor: -webkit-grab;
  cursor: grab;
}

.letter {
  display: inline-block;
  font-size: 50vh;
  margin: 0;
  padding: 0;
  line-height: .8;
  transform-origin: top left;
  color: white;
}

/* .division:nth-child(1){
 background-color: blue;
}
.division:nth-child(2){
 background-color: red;
}
.division:nth-child(3){
 background-color: green;
}
.division:nth-child(4){
 background-color: orange;
} */

.circle {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  border: 1px solid white;
  background-color: blue;
  box-sizing: border-box;
}</code>```

SECTION-01

L

A

S

T

SECTION-02

F

A

S

T

```

https://jsfiddle.net/CAT999/ohaf61qp/5/

答:
See working FIDDLE

You had to change the y variable because you were calculating with the offset top of the mouse position inn the document. This is always bigger than the element, so you have to extract the offset top of the element you were scrolling on, to get the right value.

```<code>var y = e.pageY - $(this).offset().top;
</code>```

Body:
I was looking to trigger different sections with a variable font based on my mouse movement.

For the first section, everything looks great, but when I tried to trigger the second section, it does not work as I expected since is connected to the first one I guess.

I would need to make the section working independently and in the correct way (to have an idea see section one how react in debug mode)

I was wondering what I have to modify in my Javascript code to make my snippet work with all the sections I want, working independently with their respective variable font interaction. Any ideas?

$('.square').on('mousemove', function(e) {
  var x = e.pageX - $(this).offset().left;
  var y = e.pageY;
  var $tlSquare = $('.division--top.division--left');
  var $trSquare = $('.division--top.division--right');
  var $blSquare = $('.division--bottom.division--left');
  var $brSquare = $('.division--bottom.division--right');
  var squareWidth = $(this).width(),
    squareHeight = $(this).height();

  $tlSquare.width(x).height(y);
  $trSquare.width(squareWidth - x).height(y);
  $blSquare.width(x).height(squareHeight - y);
  $brSquare.width(squareWidth - x).height(squareHeight - y);

  stretchLetter(false);
});

stretchLetter(false);

$('.square').on('mouseleave', function() {
  $('.division').width('50%').height('50%');
  $('.letter').css('transform', '');
  stretchLetter(false);
});

function stretchLetter(animation) {
  $('.letter').each(function() {
    var parentWidth = $(this).parent().width();
    var parentHeight = $(this).parent().height();
    var thisWidth = $(this).width();
    var thisHeight = $(this).height();
    var widthPercent = parentWidth / thisWidth;
    var heightPercent = parentHeight / thisHeight;
    var timing = animation == true ? .5 : 0;

    TweenMax.to($(this), timing, {
      scaleX: widthPercent,
      scaleY: heightPercent
    })
    //$(this).css('transform', 'scalex('+ widthPercent +') scaley('+ heightPercent +')');
  });
}

body,
html {
  margin: 0;
  padding: 0;
  font-weight: bold;
  font-family: helvetica;
}

section {
  height: 200px;
  background: blue;
  color: white;
  font-size: 28px;
}

.wrapper {
  display: flex;
  justify-content: center;
  /*justify-content: flex-end;*/
  width: 100%;
  height: 100vh;
  //background-color: blue;
  overflow: hidden;
}

.square {
  display: flex;
  flex-wrap: wrap;
  width: 100vh;
  height: 100vh;
  background-color: black;
}

.square-2 {
  display: flex;
  flex-wrap: wrap;
  width: 100vh;
  height: 100vh;
  background-color: yellow;
}

.division {
  //display: flex;
  //align-items: center;
  //justify-content: center;
  width: 50%;
  height: 50%;
  //background-color: red;
  //border: 1px solid white;
  box-sizing: border-box;
}

.letter {
  cursor: -webkit-grab;
  cursor: grab;
}

.letter {
  display: inline-block;
  font-size: 50vh;
  margin: 0;
  padding: 0;
  line-height: .8;
  transform-origin: top left;
  color: white;
}

/* .division:nth-child(1){
 background-color: blue;
}
.division:nth-child(2){
 background-color: red;
}
.division:nth-child(3){
 background-color: green;
}
.division:nth-child(4){
 background-color: orange;
} */

.circle {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  border: 1px solid white;
  background-color: blue;
  box-sizing: border-box;
}

SECTION-01

L

A

S

T

SECTION-02

F

A

S

T

https://jsfiddle.net/CAT999/ohaf61qp/5/

Body:
See working FIDDLE

You had to change the y variable because you were calculating with the offset top of the mouse position inn the document. This is always bigger than the element, so you have to extract the offset top of the element you were scrolling on, to get the right value.

var y = e.pageY - $(this).offset().top;


问:
"NotSerializableException " in scala map function
I am reading a file and try to map the values using a function. But it is giving a error NotSerializableException
Below is the code I am running:

```<code>package com.sundogsoftware.spark

import org.apache.spark._
import org.apache.spark.SparkContext._
import org.apache.log4j._
import scala.math.min

/** Find the minimum temperature by weather station */
object MinTemperatures {

  def parseLine(line: String) = {
    val fields = line.split(",")
    val stationID = fields(0)
    val entryType = fields(2)
    val temperature = fields(3).toFloat * 0.1f * (9.0f / 5.0f) + 32.0f
    (stationID, entryType, temperature)
  }

  /** Our main function where the action happens */
  def main(args: Array[String]) {

    // Set the log level to only print errors
    Logger.getLogger("org").setLevel(Level.ERROR)

    // Create a SparkContext using every core of the local machine
    val sc = new SparkContext("local[*]", "MinTemperatures")

    // Read each line of input data
    val lines = sc.textFile("../DataSet/1800.csv")

    // Convert to (stationID, entryType, temperature) tuples
    val parsedLines = lines.map(parseLine)
}
}
</code>```

When I run the above code it is giving me below error:

Using Spark's default log4j profile:
  org/apache/spark/log4j-defaults.properties Exception in thread "main"
  org.apache.spark.SparkException: Task not serializable    at
  org.apache.spark.util.ClosureCleaner$.ensureSerializable(ClosureCleaner.scala:403)
    at
  org.apache.spark.util.ClosureCleaner$.clean(ClosureCleaner.scala:393)
    at
  org.apache.spark.util.ClosureCleaner$.clean(ClosureCleaner.scala:162)
    at org.apache.spark.SparkContext.clean(SparkContext.scala:2326)     at
  org.apache.spark.rdd.RDD.$anonfun$map$1(RDD.scala:371)    at
  org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at
  org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112)
    at org.apache.spark.rdd.RDD.withScope(RDD.scala:363)    at
  org.apache.spark.rdd.RDD.map(RDD.scala:370)   at
  com.sundogsoftware.spark.MinTemperatures$.main(MinTemperatures.scala:32)
    at
  com.sundogsoftware.spark.MinTemperatures.main(MinTemperatures.scala)

Caused by: java.io.NotSerializableException:

com.sundogsoftware.spark.MinTemperatures$ Serialization stack:
    - object not serializable (class: com.sundogsoftware.spark.MinTemperatures$, value:
  com.sundogsoftware.spark.MinTemperatures$@41fed14f)
    - element of array (index: 0)
    - array (class [Ljava.lang.Object;, size 1)
    - field (class: java.lang.invoke.SerializedLambda, name: capturedArgs, type: class [Ljava.lang.Object;)
    - object (class java.lang.invoke.SerializedLambda, SerializedLambda[capturingClass=class
  com.sundogsoftware.spark.MinTemperatures$,
  functionalInterfaceMethod=scala/Function1.apply:(Ljava/lang/Object;)Ljava/lang/Object;,
  implementation=invokeStatic
  com/sundogsoftware/spark/MinTemperatures$.$anonfun$main$1:(Lcom/sundogsoftware/spark/MinTemperatures$;Ljava/lang/String;)Lscala/Tuple3;,
  instantiatedMethodType=(Ljava/lang/String;)Lscala/Tuple3;,
  numCaptured=1])
    - writeReplace data (class: java.lang.invoke.SerializedLambda)

But when I run the same code with anonymous function it is running successfully:

```<code>package com.sundogsoftware.spark

import org.apache.spark._
import org.apache.spark.SparkContext._
import org.apache.log4j._
import scala.math.min

/** Find the minimum temperature by weather station */
object MinTemperatures {

  /** Our main function where the action happens */
  def main(args: Array[String]) {

    // Set the log level to only print errors
    Logger.getLogger("org").setLevel(Level.ERROR)

    // Create a SparkContext using every core of the local machine
    val sc = new SparkContext("local[*]", "MinTemperatures")

    // Read each line of input data
    val lines = sc.textFile("../DataSet/1800.csv")

    // Convert to (stationID, entryType, temperature) tuples
    val parsedLines = lines.map(x => {
      val fields = x.split(",");
      val stationID = fields(0);
      val entryType = fields(2);
      val temperature = fields(3).toFloat * 0.1f * (9.0f / 5.0f) + 32.0f;
      (stationID, entryType, temperature)
    })

    // Filter out all but TMIN entries
    val minTemps = parsedLines.filter(x => x._2 == "TMIN")

    // Convert to (stationID, temperature)
    val stationTemps = minTemps.map(x => (x._1, x._3.toFloat))

    // Reduce by stationID retaining the minimum temperature found
    val minTempsByStation = stationTemps.reduceByKey((x, y) => min(x, y))

    // Collect, format, and print the results
    val results = minTempsByStation.collect()

    for (result <- results.sorted) {
      val station = result._1
      val temp = result._2
      val formattedTemp = f"$temp%.2f F"
      println(s"$station minimum temperature: $formattedTemp")
    }

  }
}
</code>```

Output:

```<code>EZE00100082 minimum temperature: 7.70 F
ITE00100554 minimum temperature: 5.36 F
</code>```

As you seen above, when I am using named function (parseLine) inside map it is giving error, but the same program instead of named function when I used anonymous function in map it is running successfully.

I looked into few blogs but didn't get the reason for the error.
Could anyone help me to understand this?

答:
This issue doesn't seem to be sbt or dependency related, as I checked, this happens when the script is not defined as object (Scala objects are serialize-able by default) so this error means the script is not serializable.
I created a new object and pasted the same code. It worked.</p>

Body:
I am reading a file and try to map the values using a function. But it is giving a error NotSerializableException
Below is the code I am running:

package com.sundogsoftware.spark

import org.apache.spark._
import org.apache.spark.SparkContext._
import org.apache.log4j._
import scala.math.min

/** Find the minimum temperature by weather station */
object MinTemperatures {

  def parseLine(line: String) = {
    val fields = line.split(",")
    val stationID = fields(0)
    val entryType = fields(2)
    val temperature = fields(3).toFloat * 0.1f * (9.0f / 5.0f) + 32.0f
    (stationID, entryType, temperature)
  }

  /** Our main function where the action happens */
  def main(args: Array[String]) {

    // Set the log level to only print errors
    Logger.getLogger("org").setLevel(Level.ERROR)

    // Create a SparkContext using every core of the local machine
    val sc = new SparkContext("local[*]", "MinTemperatures")

    // Read each line of input data
    val lines = sc.textFile("../DataSet/1800.csv")

    // Convert to (stationID, entryType, temperature) tuples
    val parsedLines = lines.map(parseLine)
}
}

When I run the above code it is giving me below error:

Using Spark's default log4j profile:
  org/apache/spark/log4j-defaults.properties Exception in thread "main"
  org.apache.spark.SparkException: Task not serializable    at
  org.apache.spark.util.ClosureCleaner$.ensureSerializable(ClosureCleaner.scala:403)
    at
  org.apache.spark.util.ClosureCleaner$.clean(ClosureCleaner.scala:393)
    at
  org.apache.spark.util.ClosureCleaner$.clean(ClosureCleaner.scala:162)
    at org.apache.spark.SparkContext.clean(SparkContext.scala:2326)     at
  org.apache.spark.rdd.RDD.$anonfun$map$1(RDD.scala:371)    at
  org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at
  org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112)
    at org.apache.spark.rdd.RDD.withScope(RDD.scala:363)    at
  org.apache.spark.rdd.RDD.map(RDD.scala:370)   at
  com.sundogsoftware.spark.MinTemperatures$.main(MinTemperatures.scala:32)
    at
  com.sundogsoftware.spark.MinTemperatures.main(MinTemperatures.scala)

Caused by: java.io.NotSerializableException:

com.sundogsoftware.spark.MinTemperatures$ Serialization stack:
    - object not serializable (class: com.sundogsoftware.spark.MinTemperatures$, value:
  com.sundogsoftware.spark.MinTemperatures$@41fed14f)
    - element of array (index: 0)
    - array (class [Ljava.lang.Object;, size 1)
    - field (class: java.lang.invoke.SerializedLambda, name: capturedArgs, type: class [Ljava.lang.Object;)
    - object (class java.lang.invoke.SerializedLambda, SerializedLambda[capturingClass=class
  com.sundogsoftware.spark.MinTemperatures$,
  functionalInterfaceMethod=scala/Function1.apply:(Ljava/lang/Object;)Ljava/lang/Object;,
  implementation=invokeStatic
  com/sundogsoftware/spark/MinTemperatures$.$anonfun$main$1:(Lcom/sundogsoftware/spark/MinTemperatures$;Ljava/lang/String;)Lscala/Tuple3;,
  instantiatedMethodType=(Ljava/lang/String;)Lscala/Tuple3;,
  numCaptured=1])
    - writeReplace data (class: java.lang.invoke.SerializedLambda)

But when I run the same code with anonymous function it is running successfully:

package com.sundogsoftware.spark

import org.apache.spark._
import org.apache.spark.SparkContext._
import org.apache.log4j._
import scala.math.min

/** Find the minimum temperature by weather station */
object MinTemperatures {

  /** Our main function where the action happens */
  def main(args: Array[String]) {

    // Set the log level to only print errors
    Logger.getLogger("org").setLevel(Level.ERROR)

    // Create a SparkContext using every core of the local machine
    val sc = new SparkContext("local[*]", "MinTemperatures")

    // Read each line of input data
    val lines = sc.textFile("../DataSet/1800.csv")

    // Convert to (stationID, entryType, temperature) tuples
    val parsedLines = lines.map(x => {
      val fields = x.split(",");
      val stationID = fields(0);
      val entryType = fields(2);
      val temperature = fields(3).toFloat * 0.1f * (9.0f / 5.0f) + 32.0f;
      (stationID, entryType, temperature)
    })

    // Filter out all but TMIN entries
    val minTemps = parsedLines.filter(x => x._2 == "TMIN")

    // Convert to (stationID, temperature)
    val stationTemps = minTemps.map(x => (x._1, x._3.toFloat))

    // Reduce by stationID retaining the minimum temperature found
    val minTempsByStation = stationTemps.reduceByKey((x, y) => min(x, y))

    // Collect, format, and print the results
    val results = minTempsByStation.collect()

    for (result <- results.sorted) {
      val station = result._1
      val temp = result._2
      val formattedTemp = f"$temp%.2f F"
      println(s"$station minimum temperature: $formattedTemp")
    }

  }
}

Output:

EZE00100082 minimum temperature: 7.70 F
ITE00100554 minimum temperature: 5.36 F

As you seen above, when I am using named function (parseLine) inside map it is giving error, but the same program instead of named function when I used anonymous function in map it is running successfully.

I looked into few blogs but didn't get the reason for the error.
Could anyone help me to understand this?


问:
c# linq to sql - moving around FirstOrDefault() at end of linq breaks query
What is the difference between the two pieces of code below?

This returns the data I expect....

```<code>return productTable.FirstOrDefault(p => p.ProductId == productId);
</code>```

This doesn't....

```<code>return productTable.Where(x => x.ProductId == productId).FirstOrDefault();
</code>```

I'm mainly just wondering if there's a logical difference between these two.

答:
Those queries should be essentially identical.  The parameterless version of FirstOrDefault() just grabs the first record available from the query, or default value (i.e., null) if no records are available.

Edit 2 As duly pointed out in the comments, I should be using LINQ-to-SQL.  Here is a sample with LINQ-to-SQL:

```<code>using (ProductsDataContext context = new ProductsDataContext())
{
    context.Log = Console.Out;
    var p1 = context.Products.FirstOrDefault(p => p.ProductId == 1);
    var p2 = context.Products.Where(p => p.ProductId == 1).FirstOrDefault();
}
</code>```

Output (notice the queries are exactly identical):

SELECT TOP (1) [t0].[ProductId],
  [t0].[Name] FROM [dbo].[Products] AS
  [t0] WHERE [t0].[ProductId] = @p0
  -- @p0: Input Int (Size = -1; Prec = 0; Scale = 0) [1]
  -- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build:
  4.0.30319.1

SELECT TOP (1) [t0].[ProductId],
  [t0].[Name] FROM [dbo].[Products] AS
  [t0] WHERE [t0].[ProductId] = @p0
  -- @p0: Input Int (Size = -1; Prec = 0; Scale = 0) [1]
  -- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build:
  4.0.30319.1

Edit: Here is sample code to demonstrate they are the same thing:

```<code>class Product
{
    public int ProductId { get; set; }
    public string Name { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        List<Product> productTable = new List<Product> {
            new Product { ProductId = 123, Name = "Cheese" },
            new Product { ProductId = 456, Name = "Milk" },
        };

        var r1 = productTable.FirstOrDefault(p => p.ProductId == 123);
        var r2 = productTable.Where(p => p.ProductId == 123).FirstOrDefault();

        // these print out the same thing
        Console.WriteLine(r1.Name);
        Console.WriteLine(r2.Name);

        Console.ReadLine();
    }
}
</code>```

Body:
What is the difference between the two pieces of code below?

This returns the data I expect....

return productTable.FirstOrDefault(p => p.ProductId == productId);

This doesn't....

return productTable.Where(x => x.ProductId == productId).FirstOrDefault();

I'm mainly just wondering if there's a logical difference between these two.

Body:
Those queries should be essentially identical.  The parameterless version of FirstOrDefault() just grabs the first record available from the query, or default value (i.e., null) if no records are available.

Edit 2 As duly pointed out in the comments, I should be using LINQ-to-SQL.  Here is a sample with LINQ-to-SQL:

using (ProductsDataContext context = new ProductsDataContext())
{
    context.Log = Console.Out;
    var p1 = context.Products.FirstOrDefault(p => p.ProductId == 1);
    var p2 = context.Products.Where(p => p.ProductId == 1).FirstOrDefault();
}

Output (notice the queries are exactly identical):

SELECT TOP (1) [t0].[ProductId],
  [t0].[Name] FROM [dbo].[Products] AS
  [t0] WHERE [t0].[ProductId] = @p0
  -- @p0: Input Int (Size = -1; Prec = 0; Scale = 0) [1]
  -- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build:
  4.0.30319.1

SELECT TOP (1) [t0].[ProductId],
  [t0].[Name] FROM [dbo].[Products] AS
  [t0] WHERE [t0].[ProductId] = @p0
  -- @p0: Input Int (Size = -1; Prec = 0; Scale = 0) [1]
  -- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build:
  4.0.30319.1

Edit: Here is sample code to demonstrate they are the same thing:

class Product
{
    public int ProductId { get; set; }
    public string Name { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        List<Product> productTable = new List<Product> {
            new Product { ProductId = 123, Name = "Cheese" },
            new Product { ProductId = 456, Name = "Milk" },
        };

        var r1 = productTable.FirstOrDefault(p => p.ProductId == 123);
        var r2 = productTable.Where(p => p.ProductId == 123).FirstOrDefault();

        // these print out the same thing
        Console.WriteLine(r1.Name);
        Console.WriteLine(r2.Name);

        Console.ReadLine();
    }
}


问:
Access nested values in json using System.Text.Json
I have a JSON file returned from a system that looks like this:

```<code>{
    "value1": "Hello",
    "value2": "World",
    "result":
    {
        "stats":
        {
            "count":"1"
        }
    }
}
</code>```

Getting to the values "Value1" and "Value2" is no issue.
However, I cannot get to "count" - Does not appear to be in a good format.

This is my code:

```<code>class Program
{
    static void Main(string[] args)
    {
        string json1 = File.ReadAllText("test.json");
        var info = JsonSerializer.Deserialize<SnData>(json1);
        WriteLine("Value1: {0} , Value2: {1}",info.value1,info.value2);
    }
}
class SnData
{
    public string value1 {get; set;}
    public string value2 {get; set;}
}
</code>```

How to get the value "count"?

答:
You can fetch the count with the following code:

```<code>public class SnData
{
    public string Value1 { get; set; }
    public string Value2 { get; set; }
    public Result Result { get; set; }

}
public class Result
{
    public Stats Stats { get; set; }

}

public class Stats
{
    public int Count { get; set; }
}
</code>```

In the main:

```<code> class Program
{
    static void Main(string[] args)
    {
        string json1 = File.ReadAllText("test.json");
        var info = JsonSerializer.Deserialize<SnData>(json1);
        WriteLine("Value1: {0} , Value2: {1}, Count {2}", info.Value1, info.Value2, info.Result.Stats.Count);
    }
}
</code>```

The above code will simply replicate the json structure.

Body:
I have a JSON file returned from a system that looks like this:

{
    "value1": "Hello",
    "value2": "World",
    "result":
    {
        "stats":
        {
            "count":"1"
        }
    }
}

Getting to the values "Value1" and "Value2" is no issue.
However, I cannot get to "count" - Does not appear to be in a good format.

This is my code:

class Program
{
    static void Main(string[] args)
    {
        string json1 = File.ReadAllText("test.json");
        var info = JsonSerializer.Deserialize<SnData>(json1);
        WriteLine("Value1: {0} , Value2: {1}",info.value1,info.value2);
    }
}
class SnData
{
    public string value1 {get; set;}
    public string value2 {get; set;}
}

How to get the value "count"?

Body:
You can fetch the count with the following code:

public class SnData
{
    public string Value1 { get; set; }
    public string Value2 { get; set; }
    public Result Result { get; set; }

}
public class Result
{
    public Stats Stats { get; set; }

}

public class Stats
{
    public int Count { get; set; }
}

In the main:

 class Program
{
    static void Main(string[] args)
    {
        string json1 = File.ReadAllText("test.json");
        var info = JsonSerializer.Deserialize<SnData>(json1);
        WriteLine("Value1: {0} , Value2: {1}, Count {2}", info.Value1, info.Value2, info.Result.Stats.Count);
    }
}

The above code will simply replicate the json structure.


问:
Wrong end date for Google calendar recurring event
I'm wondering if Google has changed something in the calendar API or I'm just nuts... When I look at the data exported for a recurring event, the "end" "dateTime" for the event is the last date of the series. Unless I'm nuts, previously, this value was the end date/time of the first instance of the event. I can manipulate the date so my software is not longer broken, but there is no way that I did not notice this problem before - something got changed I'm pretty sure.

Sample json extracted from Google:

```<code>    "start":    {
        "dateTime": "2018-11-26T13:30:00-05:00",
        "timeZone": "America/Chicago"
    },
    "end":  {
        "dateTime": "2018-12-14T14:30:00-05:00",
        "timeZone": "America/Chicago"
    },
    "recurrence":   ["RRULE:FREQ=WEEKLY;UNTIL=20181128T055959Z;BYDAY=MO,TU,WE,TH,FR
</code>```

答:
Retrieving recurring events with Events: get gives you the end time of the singles event specified by eventId, rather than the final data of the recurrence.

Indeed, your line

```<code>["RRULE:FREQ=WEEKLY;UNTIL=20181128T055959Z;BYDAY=MO,TU,WE,TH,FR...
</code>```

contains UNTIL=20181128T055959Z - showing that the end date for the recurrence is 28th of November 2018, which is before

```<code>"end":  {
        "dateTime": "2018-12-14T14:30:00-05:00", ...}
</code>```

The only reasonable explanation is that during event creation the 14 of December 2018 was erroneously specified as the end date of a single event occurrence - this is not the end date for recurrences.

Body:
I'm wondering if Google has changed something in the calendar API or I'm just nuts... When I look at the data exported for a recurring event, the "end" "dateTime" for the event is the last date of the series. Unless I'm nuts, previously, this value was the end date/time of the first instance of the event. I can manipulate the date so my software is not longer broken, but there is no way that I did not notice this problem before - something got changed I'm pretty sure.

Sample json extracted from Google:

    "start":    {
        "dateTime": "2018-11-26T13:30:00-05:00",
        "timeZone": "America/Chicago"
    },
    "end":  {
        "dateTime": "2018-12-14T14:30:00-05:00",
        "timeZone": "America/Chicago"
    },
    "recurrence":   ["RRULE:FREQ=WEEKLY;UNTIL=20181128T055959Z;BYDAY=MO,TU,WE,TH,FR

Body:
Retrieving recurring events with Events: get gives you the end time of the singles event specified by eventId, rather than the final data of the recurrence.

Indeed, your line

["RRULE:FREQ=WEEKLY;UNTIL=20181128T055959Z;BYDAY=MO,TU,WE,TH,FR...

contains UNTIL=20181128T055959Z - showing that the end date for the recurrence is 28th of November 2018, which is before

"end":  {
        "dateTime": "2018-12-14T14:30:00-05:00", ...}

The only reasonable explanation is that during event creation the 14 of December 2018 was erroneously specified as the end date of a single event occurrence - this is not the end date for recurrences.


问:
Sentry: beforeSend is called mutliple times
I have a react-native app with redux. I want to fetch a PUT request with data when Sentry logs an error. I’m new in Sentry and I use this in my App.js:

```<code>Sentry.init({
  dsn: ...,
  enableInExpoDevelopment: true,
  debug: true,

  beforeSend(event) {
try {
  fetchMyData(data)
  Sentry.withScope(function(scope) {
    Sentry.captureMessage('Error');
  });
  return event;
}
catch (e) {
  return e;
}
  },
});
</code>```

It works and the request is successfull the most time, but beforeSend is called mutliple times and in Sentry the events loop: Put Request -> captureMessage -> Put Request -> captureMessage… and so on.

Is there another way for calling the method when Sentry logs? The data is only defined at the moment when beforeSend is called. why is there this loop?

Thank you!

答:
I think this is what you want:

Sentry.init({
  dsn: 'http://bla.com/12',
  debug: true,
  beforeSend(event) {
    try {
      // fetchMyData(data)
      // Sentry.withScope(function(scope) {
      //   Sentry.captureMessage('Error');
      // });
      const client = new Sentry.ReactNativeClient({dsn: 'http://bla.com/12'});
      client.captureMessage('test');
      return event;
    }
    catch (e) {
      return e;
    }
  },
});
```

You need to create a new Client to send those events from beforeSend. If you call Sentry.captureMessage in beforeSend you create an endless loop if you don't check for a specific event.

Body:
I have a react-native app with redux. I want to fetch a PUT request with data when Sentry logs an error. I’m new in Sentry and I use this in my App.js:

Sentry.init({
  dsn: ...,
  enableInExpoDevelopment: true,
  debug: true,

  beforeSend(event) {
try {
  fetchMyData(data)
  Sentry.withScope(function(scope) {
    Sentry.captureMessage('Error');
  });
  return event;
}
catch (e) {
  return e;
}
  },
});

It works and the request is successfull the most time, but beforeSend is called mutliple times and in Sentry the events loop: Put Request -> captureMessage -> Put Request -> captureMessage… and so on.

Is there another way for calling the method when Sentry logs? The data is only defined at the moment when beforeSend is called. why is there this loop?

Thank you!

Body:
I think this is what you want:

Sentry.init({
  dsn: 'http://bla.com/12',
  debug: true,
  beforeSend(event) {
    try {
      // fetchMyData(data)
      // Sentry.withScope(function(scope) {
      //   Sentry.captureMessage('Error');
      // });
      const client = new Sentry.ReactNativeClient({dsn: 'http://bla.com/12'});
      client.captureMessage('test');
      return event;
    }
    catch (e) {
      return e;
    }
  },
});

You need to create a new Client to send those events from beforeSend. If you call Sentry.captureMessage in beforeSend you create an endless loop if you don't check for a specific event.


问:
PHP Table auto update client side
I am trying to get a website to auto update the table on client side every (x) seconds with the newest data, this data is stored in a database and receives constant updates. Currently the only way to see the newest data is to do a Ctrl+F5 refresh on the website.

Any assistance will be greatly appreciated, code is as follows:

```<code>    include ('./vam_index_header.php');
    include ('./helpers/conversions.php');
    header('Cache-Control: no-cache');
    header('Pragma: no-cache');
    if (!isset($_GET["page"]) || trim($_GET["page"]) == "") {
        ?>
        <?php
            $sql = 'select callsign, arrival, departure, flight_status, name, surname, pending_nm, plane_type from vam_live_flights vf, gvausers gu where gu.gvauser_id = vf.gvauser_id ';
            if (!$result = $db->query($sql)) {
                die('There was an error running the query [' . $db->error . ']');
            }
            $row_cnt = $result->num_rows;
            $sql = "SELECT flight_id FROM `vam_live_flights` WHERE UNIX_TIMESTAMP (now())-UNIX_TIMESTAMP (last_update)>180";
            if (!$result = $db->query($sql)) {
                die('There was an error running the query [' . $db->error . ']');
            }
            while ($row = $result->fetch_assoc())
            {
                $sql_inner = "delete from vam_live_acars where flight_id='".$row["flight_id"]."'";
                if (!$result_acars = $db->query($sql_inner))
                {
                die('There was an error running the query [' . $db->error . ']');
                }
                $sql_inner = "delete from vam_live_flights where flight_id='".$row["flight_id"]."'";
                if (!$result_acars = $db->query($sql_inner))
                {
                die('There was an error running the query [' . $db->error . ']');
                }
            }
            if ($row_cnt>0){
        ?>
        <div class="row" id="live_flights">
            <div class="col-md-12">
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h3 class="panel-title"><IMG src="images/icons/ic_flight_takeoff_white_18dp_1x.png"> <?php echo "LIVE FIGHTS" ?></h3>
                    </div>
                    <div class="panel-body">
                        <div class="table-responsive">
                            <table class="table table-hover" id="live_flights_table">
                            <?php
                                    echo "<tr><th>" . LF_CALLSIG . "</th><th>" . LF_PILOT . "</th><th>" . LF_DEPARTURE . "</th><th>" . LF_ARRIVAL . "</th><th>" . FLIGHT_STAGE . "</th><th>". BOOK_ROUTE_ARICRAFT_TYPE . "</th><th>" . PERC_DONE ."</th><th>" . PENDING_NM . "</th></tr>";
                            ?>
                            </table>
                        <?php include ('./vam_live_flights_map.php') ?>
                    </div>
                </div>
            </div>
        </div>```
```

答:
The best in your situation could be to use the EventSource. It's well described at https://developer.mozilla.org/en-US/docs/Web/API/EventSource with some examples.

An EventSource instance opens a persistent connection to an HTTP server, which sends events in text/event-stream format.

There is another example at https://www.w3schools.com/html/html5_serversentevents.asp

I have used there in a scenario where the backend code run in a loop that sleeps for a few seconds per loop. And each iteration of the loop can detect if new data is available and it will send some corresponding event messages that can be collected by the front-end.

Another good example is available at https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events

I have one word of caution. When using the while(true){} style loop, you have to create a way to break the loop if the client-side connection is closed. That when you can do something like the following ...

```<code><?php
while(true) {
    //... some code

    // A way to break out of the loop.
    if (connection_aborted()) {
        break;
    }
}
</code>```

Title: PHP Table auto update client side

Body:
I am trying to get a website to auto update the table on client side every (x) seconds with the newest data, this data is stored in a database and receives constant updates. Currently the only way to see the newest data is to do a Ctrl+F5 refresh on the website.

Any assistance will be greatly appreciated, code is as follows:

    include ('./vam_index_header.php');
    include ('./helpers/conversions.php');
    header('Cache-Control: no-cache');
    header('Pragma: no-cache');
    if (!isset($_GET["page"]) || trim($_GET["page"]) == "") {
        ?>
        <?php
            $sql = 'select callsign, arrival, departure, flight_status, name, surname, pending_nm, plane_type from vam_live_flights vf, gvausers gu where gu.gvauser_id = vf.gvauser_id ';
            if (!$result = $db->query($sql)) {
                die('There was an error running the query [' . $db->error . ']');
            }
            $row_cnt = $result->num_rows;
            $sql = "SELECT flight_id FROM `vam_live_flights` WHERE UNIX_TIMESTAMP (now())-UNIX_TIMESTAMP (last_update)>180";
            if (!$result = $db->query($sql)) {
                die('There was an error running the query [' . $db->error . ']');
            }
            while ($row = $result->fetch_assoc())
            {
                $sql_inner = "delete from vam_live_acars where flight_id='".$row["flight_id"]."'";
                if (!$result_acars = $db->query($sql_inner))
                {
                die('There was an error running the query [' . $db->error . ']');
                }
                $sql_inner = "delete from vam_live_flights where flight_id='".$row["flight_id"]."'";
                if (!$result_acars = $db->query($sql_inner))
                {
                die('There was an error running the query [' . $db->error . ']');
                }
            }
            if ($row_cnt>0){
        ?>

 <?php echo "LIVE FIGHTS" ?>

                            <?php
                                    echo "
" . LF_CALLSIG . "	" . LF_PILOT . "	" . LF_DEPARTURE . "	" . LF_ARRIVAL . "	" . FLIGHT_STAGE . "	". BOOK_ROUTE_ARICRAFT_TYPE . "	" . PERC_DONE ."	" . PENDING_NM . "
";
                            ?>

                        <?php include ('./vam_live_flights_map.php') ?>

```

Body:
The best in your situation could be to use the EventSource. It's well described at https://developer.mozilla.org/en-US/docs/Web/API/EventSource with some examples.

An EventSource instance opens a persistent connection to an HTTP server, which sends events in text/event-stream format.

There is another example at https://www.w3schools.com/html/html5_serversentevents.asp

I have used there in a scenario where the backend code run in a loop that sleeps for a few seconds per loop. And each iteration of the loop can detect if new data is available and it will send some corresponding event messages that can be collected by the front-end.

Another good example is available at https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events

I have one word of caution. When using the while(true){} style loop, you have to create a way to break the loop if the client-side connection is closed. That when you can do something like the following ...

<?php
while(true) {
    //... some code

    // A way to break out of the loop.
    if (connection_aborted()) {
        break;
    }
}


问:
Understanding CSS rendering
So I read everywhere that CSS is render blocking. Though this is different than the blocking caused by

答:
if browser always waits for the CSS to be loaded and parsed first before rendering anything, FOUC should not happen.

Indeed, that's what should happen in such a case, except that browsers don't wait for all resources to be loaded before rendering.

Note that this doesn't contradict what you "read everywhere", if you really did read "The browser basically waits for the CSSOM to be constructed and then only render anything to the webpage."

The browser can very well build the CSSOM while it still misses resources, for instance, it definitely doesn't need to load all background-images resources to calculate the elements' box positions.

And it may actually even need to build the CSSOM as soon as the DOM is being constructed because in cases like the below snippet, you need the CSSOM for the js to work:

test

```

Title: Understanding CSS rendering

Body:
if browser always waits for the CSS to be loaded and parsed first before rendering anything, FOUC should not happen.

Indeed, that's what should happen in such a case, except that browsers don't wait for all resources to be loaded before rendering.

Note that this doesn't contradict what you "read everywhere", if you really did read "The browser basically waits for the CSSOM to be constructed and then only render anything to the webpage."

The browser can very well build the CSSOM while it still misses resources, for instance, it definitely doesn't need to load all background-images resources to calculate the elements' box positions.

And it may actually even need to build the CSSOM as soon as the DOM is being constructed because in cases like the below snippet, you need the CSSOM for the js to work:

<h1>test</h1>
<script>
  // without CSSOM, we couldn't get its width yet
  console.log(document.querySelector('h1').offsetWidth);
</script>
<style>
  /* even if it's gonna be invalidated later on */
  h1 { width: 300px; border:1px solid; }
</style>


问:
Error because of quote char after converting file to string with Delphi XE?
I have incorrect result when converting file to string in Delphi XE. There are several ' characters that makes the result incorrect. I've used UnicodeFileToWideString and FileToString from http://www.delphidabbler.com/codesnip and my code :

```<code> function LoadFile(const FileName: TFileName): ansistring;
  begin
    with TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite) do
    begin
      try
        SetLength(Result, Size);
        Read(Pointer(Result)^, Size);
        // ReadBuffer(Result[1], Size);
      except
        Result := '';
        Free;
      end;
      Free;
    end;
  end;
</code>```

The result between Delphi XE and Delphi 6 is different. The result from D6 is correct. I've compared with result of a hex editor program.

答:
Actually, looking at the real data, your problem is that the file stores binary data, not string data, so interpreting this as a string is not valid at all. The only reason it works at all in Delphi 6 is that non-Unicode Delphi allows you to treat binary data and strings the same way. You cannot do this in Unicode Delphi, nor should you.

The solution to get the actual text from within the file is to read the file as binary data, and then copy any values from this binary data, one byte at a time, to a string if it is a "valid" Ansi character (printable).

Body:
I have incorrect result when converting file to string in Delphi XE. There are several ' characters that makes the result incorrect. I've used UnicodeFileToWideString and FileToString from http://www.delphidabbler.com/codesnip and my code :

 function LoadFile(const FileName: TFileName): ansistring;
  begin
    with TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite) do
    begin
      try
        SetLength(Result, Size);
        Read(Pointer(Result)^, Size);
        // ReadBuffer(Result[1], Size);
      except
        Result := '';
        Free;
      end;
      Free;
    end;
  end;

The result between Delphi XE and Delphi 6 is different. The result from D6 is correct. I've compared with result of a hex editor program.


问:
Github Flutter Login
Github API specifies that redirect url is required in order to get the login result of the authorization. But if I am developing a non hybrid flutter app without using webviews. How would I redirect the user to come back to the app after prompting user to login using things like URL Launcher?</p>

答:
You can use package https://pub.dev/packages/simple_auth

code snippet

```<code>final simpleAuth.GithubApi githubApi = new simpleAuth.GithubApi(
      "github", "clientId", "clientSecret", "redirect:/",
      scopes: [
        "user",
        "repo",
        "public_repo",
      ]);

void login(simpleAuth.AuthenticatedApi api) async {
    try {
      var success = await api.authenticate();
      showMessage("Logged in success: $success");
    } catch (e) {
      showError(e);
    }
  }
...
ListTile(
            leading: Icon(Icons.launch),
            title: Text('Login'),
            onTap: () {
              login(githubApi);
            },
          ),
ListTile(
            leading: Icon(Icons.delete),
            title: Text('Logout'),
            onTap: () {
              logout(githubApi);
            },
          ),
</code>```

full example code
https://github.com/Clancey/simple_auth/blob/master/simple_auth_flutter_example/lib/main.dart

Title: Github Flutter Login

Body:
You can use package https://pub.dev/packages/simple_auth

code snippet

final simpleAuth.GithubApi githubApi = new simpleAuth.GithubApi(
      "github", "clientId", "clientSecret", "redirect:/",
      scopes: [
        "user",
        "repo",
        "public_repo",
      ]);

void login(simpleAuth.AuthenticatedApi api) async {
    try {
      var success = await api.authenticate();
      showMessage("Logged in success: $success");
    } catch (e) {
      showError(e);
    }
  }
...
ListTile(
            leading: Icon(Icons.launch),
            title: Text('Login'),
            onTap: () {
              login(githubApi);
            },
          ),
ListTile(
            leading: Icon(Icons.delete),
            title: Text('Logout'),
            onTap: () {
              logout(githubApi);
            },
          ),

full example code
https://github.com/Clancey/simple_auth/blob/master/simple_auth_flutter_example/lib/main.dart


问:
how to autorun php file per day
The website is written in .php with the connection of MySQL
I had a file that's named PMautoemail.php It can be run successfully but I only want it to run once a day. Cronjob couldn't be set up as I am running in a windows server and this website will be run by other people too. What should I do?

答:
Well, if you can't use CronJob, you can always start file in background and set some sleep. It's not proper solution, but sometimes be only option in some cases:</p>

```<code>// init_linux.php
exec('php my_cron.php &');

// init_win.php
pclose(popen("start /B php my_cron.php", "r"));

// my_cron.php

// [... do some stuff ...];
sleep(60 * 60 * 24); // sleep for 1 day
</code>```

Title: how to autorun php file per day

Body:
Well, if you can't use CronJob, you can always start file in background and set some sleep. It's not proper solution, but sometimes be only option in some cases:

// init_linux.php
exec('php my_cron.php &');

// init_win.php
pclose(popen("start /B php my_cron.php", "r"));

// my_cron.php

// [... do some stuff ...];
sleep(60 * 60 * 24); // sleep for 1 day