问:
Error when using pyinstaller: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff
I have an issue when i compile a PyQt code with pyinstaller.

I use this line to compile:

```<code>c:\Anaconda3\Scripts\pyinstaller.exe -y -F --distpath="." MyQt.py
</code>```

then I get this error message:

```<code>      File "c:\anaconda36bis\lib\site-packages\PyInstaller\hooks\hook-zmq.py", line
18, in <module>
    hiddenimports.extend(collect_submodules('zmq.backend'))
  File "c:\anaconda36bis\lib\site-packages\PyInstaller\utils\hooks\__init__.py",
 line 619, in collect_submodules
    repr(pkg_dir), package))
  File "c:\anaconda36bis\lib\site-packages\PyInstaller\utils\hooks\__init__.py",
 line 90, in exec_statement
    return __exec_python_cmd(cmd)
  File "c:\anaconda36bis\lib\site-packages\PyInstaller\utils\hooks\__init__.py",
 line 77, in __exec_python_cmd
    txt = exec_python(*cmd, env=pp_env)
  File "c:\anaconda36bis\lib\site-packages\PyInstaller\compat.py", line 562, in
exec_python
    return exec_command(*cmdargs, **kwargs)
  File "c:\anaconda36bis\lib\site-packages\PyInstaller\compat.py", line 369, in
exec_command
    out = out.decode(encoding)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 152: invali
d start byte
</code>```

The error message is not clear to me and I don't understand why this happens.

Is it possible that pyinstaller try to use a module which is not compatible?
I use these in my script:

```<code># -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
# from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys
import numpy as np
import matplotlib
matplotlib.use('Qt5Agg')
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as     FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as     NavigationToolbar
from scipy.ndimage import imread
from scipy.ndimage.morphology import binary_dilation
from scipy.optimize import curve_fit, leastsq
</code>```

update

the issue printed in the console come directly after

```<code>142859 INFO: Loading module hook "hook-zmq.py"...
</code>```

So it should mean that the error is coming from zmq?

答:
I found an answer on another forum.
I change the line number 369 in the Python\Lib\site-packages\Pyinstaller\compat.py file:

```<code>out = out.decode(encoding)
</code>```

to

```<code>out = out.decode(encoding, errors='ignore')
</code>```

or

```<code>out = out.decode(encoding, "replace")
</code>```

Now I can compile my script without any issue.
I still don't know why my issue happened in the first place but at least that compiles now.

Body:
I have an issue when i compile a PyQt code with pyinstaller.

I use this line to compile:

c:\Anaconda3\Scripts\pyinstaller.exe -y -F --distpath="." MyQt.py

then I get this error message:

      File "c:\anaconda36bis\lib\site-packages\PyInstaller\hooks\hook-zmq.py", line
18, in <module>
    hiddenimports.extend(collect_submodules('zmq.backend'))
  File "c:\anaconda36bis\lib\site-packages\PyInstaller\utils\hooks\__init__.py",
 line 619, in collect_submodules
    repr(pkg_dir), package))
  File "c:\anaconda36bis\lib\site-packages\PyInstaller\utils\hooks\__init__.py",
 line 90, in exec_statement
    return __exec_python_cmd(cmd)
  File "c:\anaconda36bis\lib\site-packages\PyInstaller\utils\hooks\__init__.py",
 line 77, in __exec_python_cmd
    txt = exec_python(*cmd, env=pp_env)
  File "c:\anaconda36bis\lib\site-packages\PyInstaller\compat.py", line 562, in
exec_python
    return exec_command(*cmdargs, **kwargs)
  File "c:\anaconda36bis\lib\site-packages\PyInstaller\compat.py", line 369, in
exec_command
    out = out.decode(encoding)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 152: invali
d start byte

The error message is not clear to me and I don't understand why this happens.

Is it possible that pyinstaller try to use a module which is not compatible?
I use these in my script:

# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
# from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys
import numpy as np
import matplotlib
matplotlib.use('Qt5Agg')
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as     FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as     NavigationToolbar
from scipy.ndimage import imread
from scipy.ndimage.morphology import binary_dilation
from scipy.optimize import curve_fit, leastsq

update

the issue printed in the console come directly after

142859 INFO: Loading module hook "hook-zmq.py"...

So it should mean that the error is coming from zmq?

Body:
I found an answer on another forum.
I change the line number 369 in the Python\Lib\site-packages\Pyinstaller\compat.py file:

out = out.decode(encoding)

to

out = out.decode(encoding, errors='ignore')

or

out = out.decode(encoding, "replace")

Now I can compile my script without any issue.
I still don't know why my issue happened in the first place but at least that compiles now.


来源: stackexchange

问:
Android Studio 3.0 - No server to serve request
After clean install of Android Studio I always get the error

Error:java.util.concurrent.ExecutionException:
  java.lang.RuntimeException: No server to serve request. Check logs for
  details.

and

Error:Execution failed for task ':Application:mergeDebugResources'.
  Error: java.util.concurrent.ExecutionException: java.lang.RuntimeException: No server to serve request. Check logs for details.

Java is up to date and the path is set.

I am new to Android Studio, what should I try?

答:
You can run Android Studio as Admin.

I hope it will help you.

To Do So :

Right click

choose Run as Administrator

Best regards,

ContentLicense: CC BY-SA 3.0


问:
How to get the tab bar height in a Xamarin.Forms page
I'm displaying an image within my content pages such that its height is a fixed percentage of the page height. I do this using a grid with star unit row height. However, when the content pages are placed within a TabbedPage, the total grid height seems to be that of [the screen minus the tab bar height], so as a consequence, the image appears a bit shorter.

If I could access the tab bar height within my content pages, it would be a simple adjustment to the percentage.

Question:

1) How do I get the tab bar height within a content page?

2) Is there a better way to achieve the desired result?

答:
1) How do I get the tab bar height within a content page?

We can't get tabbar height from PCL directly.Just need a custom renderers for TabbedRenderer

```<code>[assembly: ExportRenderer(typeof(TabbedPage),
typeof(CustomTabbedPageRenderer))]
namespace TabbedPageWithNavigationPage.iOS
{
    class CustomTabbedPageRenderer : TabbedRenderer
    {
        public override void ViewWillAppear(bool animated)
        {
            base.ViewWillAppear(animated);
            App.TabHeight = (int)TabBar.Frame.Height;
        }
    }
}
</code>```

Define TabHeight in App in PCL

```<code>public static int TabHeight { get; set; }
</code>```

Get the height in TabbedPage

```<code>protected override void OnAppearing()
{
    base.OnAppearing();
    int height = App.TabHeight;
}
</code>```

2) Is there a better way to achieve the desired result?

We'r better not set the fixed frame on Image, and should not operate the frame manually .

Aspect of Image can help us to show the image as we want.

AspectFit

AspectFill

Fill

Body:
1) How do I get the tab bar height within a content page?

We can't get tabbar height from PCL directly.Just need a custom renderers for TabbedRenderer

[assembly: ExportRenderer(typeof(TabbedPage),
typeof(CustomTabbedPageRenderer))]
namespace TabbedPageWithNavigationPage.iOS
{
    class CustomTabbedPageRenderer : TabbedRenderer
    {
        public override void ViewWillAppear(bool animated)
        {
            base.ViewWillAppear(animated);
            App.TabHeight = (int)TabBar.Frame.Height;
        }
    }
}

Define TabHeight in App in PCL

public static int TabHeight { get; set; }

Get the height in TabbedPage

protected override void OnAppearing()
{
    base.OnAppearing();
    int height = App.TabHeight;
}

2) Is there a better way to achieve the desired result?

We'r better not set the fixed frame on Image, and should not operate the frame manually .

Aspect of Image can help us to show the image as we want.

AspectFit

AspectFill

Fill


问:
Couldn't send a value from client to server in Angular 2+ to Node
I am trying to send an email value from client to server side, but I am getting some errors. My code below.

HTML

```<code><form class="example-form" (ngSubmit)="uptpwd()">
        <input class="form-control lht" placeholder="Email" type="email" name="email" [(ngModel)]="email">
        <br/>
        <br/>
        <button class="lgbtn" type="submit">Enter</button>
        </form>
</code>```

TS

```<code>export class ForgotComponent implements OnInit {

 email: string = '';

   constructor(private auth: AuthService,
          private formBuilder: FormBuilder,
          private http: Http,
          public toast: ToastComponent) { }

         ngOnInit() {

           }
       uptpwd(email)
         {
      this.auth.uptpwd(this.email).subscribe();
     }
      }
</code>```

Service

```<code>uptpwd(email){
 return this.http.post(`http://localhost:3000/sendmail`,email).map(res =>
 res.json());
  }
</code>```

Server

```<code>    app.post('/sendmail', function (req, res) {

    let transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: 'f*******@gmail.com',
        pass: *************
    }
});

let mailOptions = {
    from: *******@gmail.com
    to:req.body.email,
    subject: 'Password Reset',
    text: 'Click the link to reset password: ',
};

app.options('/sendmail', function (req, res) {
  res.sendStatus(200);
});

res.setHeader('Access-Control-Allow-Origin', 'localhost:4200/forgot'); // Change this to your Angular 2 port number
res.setHeader('Access-Control-Request-Method', '*');
res.setHeader('Access-Control-Allow-Methods', 'POST');
res.setHeader('Access-Control-Allow-Headers', '*');

    transporter.sendMail(mailOptions, (error, info) =>

{
        if (error) {
            return console.log(error);
        }
        console.log('Message %s sent: %s',

info.messageId, info.response);
    });

})
</code>```

Error: Failed to load resource: the server responded with a status of 500 (Internal Server Error)
  forgot:1 Failed to load http://localhost:3000/sendmail: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 500.

答:
try to make it this way, I had faced the same error I made it work in the following way,</p>

```<code>app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', '*');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
});
</code>```

Body:
I am trying to send an email value from client to server side, but I am getting some errors. My code below.

HTML

<form class="example-form" (ngSubmit)="uptpwd()">
        <input class="form-control lht" placeholder="Email" type="email" name="email" [(ngModel)]="email">

        <button class="lgbtn" type="submit">Enter</button>
        </form>

TS

export class ForgotComponent implements OnInit {

 email: string = '';

   constructor(private auth: AuthService,
          private formBuilder: FormBuilder,
          private http: Http,
          public toast: ToastComponent) { }

         ngOnInit() {

           }
       uptpwd(email)
         {
      this.auth.uptpwd(this.email).subscribe();
     }
      }

Service

uptpwd(email){
 return this.http.post(`http://localhost:3000/sendmail`,email).map(res =>
 res.json());
  }

Server

    app.post('/sendmail', function (req, res) {

    let transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: 'f*******@gmail.com',
        pass: *************
    }
});

let mailOptions = {
    from: *******@gmail.com
    to:req.body.email,
    subject: 'Password Reset',
    text: 'Click the link to reset password: ',
};

app.options('/sendmail', function (req, res) {
  res.sendStatus(200);
});

res.setHeader('Access-Control-Allow-Origin', 'localhost:4200/forgot'); // Change this to your Angular 2 port number
res.setHeader('Access-Control-Request-Method', '*');
res.setHeader('Access-Control-Allow-Methods', 'POST');
res.setHeader('Access-Control-Allow-Headers', '*');

    transporter.sendMail(mailOptions, (error, info) =>

{
        if (error) {
            return console.log(error);
        }
        console.log('Message %s sent: %s',

info.messageId, info.response);
    });

})

Error: Failed to load resource: the server responded with a status of 500 (Internal Server Error)
  forgot:1 Failed to load http://localhost:3000/sendmail: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 500.

Body:
try to make it this way, I had faced the same error I made it work in the following way,

app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', '*');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
});


问:
MVVM Navigation Force Close Xamarin Forms
I try using mvvm in my xamarin forms but i'm still litle bit confused with the navigation in each page, I Already Create Interface and NavigationService to handle all Navigation in my Xamarin Forms, there is no error code line but when i click the buton and try to navigate to other page it always crash. Here is some of my code
My Interface

```<code>namespace KGVC.Interfaces
{
    public interface INavigationService
    {
        void NavigateToDashboard();
        void NavigateToLogout();
        void NavigateBack();
        void gotoNews();
        void goEvent();
        void gotoKGCash();
        void gotoCardCommnunity();
        void gotoSetting();
        void gotoNearbyLocation();
    }
}
</code>```

my navigationservice

```<code>namespace KGVC.Services
{
    public class NavigationService : INavigationService
    {
        public  void goEvent()
        {
            var currentPage = GetCurrentPage();

             currentPage.Navigation.PushAsync(new EventPage());
        }

        public  void gotoCardCommnunity()
        {
            var currentPage = GetCurrentPage();

             currentPage.Navigation.PushAsync(new CardCommunityPage());
        }

        public  void gotoKGCash()
        {
            var currentPage = GetCurrentPage();

             currentPage.Navigation.PushAsync(new KGCashPage());
        }

        public  void gotoNearbyLocation()
        {
            var currentPage = GetCurrentPage();

             currentPage.Navigation.PushAsync(new StoreMaps());
        }

        public  void gotoNews()
        {
            var currentPage = GetCurrentPage();

             currentPage.Navigation.PushAsync(new RssFeedView());
        }

        public   void gotoSetting()
        {
            var currentPage = GetCurrentPage();

             currentPage.Navigation.PushAsync(new SettingPages());
        }

        public void NavigateBack()
        {
            throw new NotImplementedException();
        }

        public  void NavigateToDashboard()
        {

            var currentPage = GetCurrentPage();

             Application.Current.MainPage = new MainPage();
        }

        public void NavigateToLogout()
        {
            var currentPage = GetCurrentPage();
            Application.Current.MainPage = new NewPageLogin();
        }

        private Page GetCurrentPage()
        {
            var currentPage = Application.Current.MainPage.Navigation.NavigationStack.LastOrDefault();

            return currentPage;
        }
    }
}
</code>```

my view model

```<code>public class GridMenuViewModel
    {

        public ICommand gotoNews { get; private set; }
        public ICommand goEvent { get; private set; }
        public ICommand gotoKGCash { get; private set; }
        public ICommand gotoSetting { get; private set; }
        public ICommand gotoNearbyLocation { get; private set; }
        public GridMenuViewModel()
        {
            gotoNews = new Command(() =>
            {
                var navigationService = new NavigationService();

                navigationService.gotoNews();
            });
            goEvent = new Command(() =>
            {
                var navigationService = new NavigationService();

                navigationService.goEvent();
            });

            gotoKGCash = new Command(() =>
            {
                var navigationService = new NavigationService();

                navigationService.gotoKGCash();
            });
            gotoSetting = new Command(() =>
            {
                var navigationService = new NavigationService();

                navigationService.gotoSetting();
            });
            gotoNearbyLocation = new Command(() =>
            {
                var navigationService = new NavigationService();

                navigationService.gotoNearbyLocation();
            });
        }
    }
</code>```

And my view

```<code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             NavigationPage.HasNavigationBar="True"
             NavigationPage.BackButtonTitle="False"
               BindingContext="{Binding GridMenuViewModel, Source={StaticResource Locator}}"
             xmlns:control="clr-namespace:Xamarin.Forms;assembly=Xamarin.Forms.CarouselView"
             xmlns:local="clr-namespace:KGVC.Views.MainPages"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="KGVC.Views.MainPages.GridMenu"
             Title="HOME"
            >

    <ContentPage.Content>
        <StackLayout >
            <StackLayout  BackgroundColor="##CEB053">
                <StackLayout  HeightRequest="35" BackgroundColor="##CEB053" Orientation="Horizontal">
                    <Label  FontAttributes="Italic" TextColor="Black" Margin="9" Text="Hello," FontSize="15"/>
                    <Label  TextColor="Black"  Margin="9" Text="John Doe" FontSize="15" FontAttributes="Bold"/>

                </StackLayout>

                <StackLayout  Padding="0"  HeightRequest="30" BackgroundColor="#E3E6E3" Orientation="Horizontal">
                    <Image Margin="5" Source="ic_logo.png"/>
                    <Label  Text="Points" Margin="5" FontSize="13" TextColor="Black"/>
                </StackLayout>

            </StackLayout>

            <StackLayout  HeightRequest="220" VerticalOptions="StartAndExpand">

                <control:CarouselView HeightRequest="185" ItemsSource="{Binding MyDataSource}" Position="{Binding Position, Mode=TwoWay}">
                    <control:CarouselView.ItemTemplate>
                        <DataTemplate>
                            <Image  Source="{Binding Image}"/>

                        </DataTemplate>
                    </control:CarouselView.ItemTemplate>
                </control:CarouselView>
                <local:CarouselIndicators IndicatorHeight="9" IndicatorWidth="9" UnselectedIndicator="unselected_circle.png" SelectedIndicator="selected_circle.png" Position="{Binding Position}" ItemsSource="{Binding MyDataSource}" />
            </StackLayout>

            <ScrollView IsClippedToBounds="True" VerticalOptions="StartAndExpand" Orientation="Vertical" >

                    <Grid x:Name="controlGrid" VerticalOptions="StartAndExpand" HeightRequest="370" Margin="15">

                        <Grid.RowDefinitions>
                            <RowDefinition Height="0" />
                            <RowDefinition Height="100" />
                            <RowDefinition Height="100" />
                            <RowDefinition Height="100" />

                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>

                            <ColumnDefinition Width="110" />
                            <ColumnDefinition Width="110" />
                            <ColumnDefinition Width="110" />

                        </Grid.ColumnDefinitions>

                        <StackLayout Orientation="Vertical"  Grid.Row="1" Grid.Column="0" >
                            <Button Image="ic_account.png" Margin="5"
        Style="{StaticResource plainButton}" />
                            <Label FontSize="12" Text="MY ACCOUNT" HorizontalOptions="Center"/>
                        </StackLayout>

                        <StackLayout Orientation="Vertical" Grid.Row="1" Grid.Column="1">
                        <Button Margin="5" Command="{Binding gotoCardCommunity}" Image="ic_card.png"
        Style="{StaticResource plainButton}" />
                            <Label FontSize="12" Text="CARD" HorizontalOptions="Center"/>
                        </StackLayout>

                        <StackLayout Orientation="Vertical" Grid.Row="1" Grid.Column="2">
                        <Button Margin="5" Command="{Binding goEvent}" Image="ic_event"
        Style="{StaticResource plainButton}" />
                            <Label FontSize="12" Text="PROMO" HorizontalOptions="Center"/>
                        </StackLayout>

                        <StackLayout Grid.Row="2" Grid.Column="0" Orientation="Vertical">
                        <Button Margin="5" Command="{Binding gotoNearbyLocation}" Image="ic_store"
        Style="{StaticResource plainButton}" />
                            <Label FontSize="12" Text="STORE LOCATIONS" HorizontalOptions="Center"/>
                        </StackLayout>

                        <StackLayout Orientation="Vertical" Grid.Row="2" Grid.Column="1">
                        <Button Margin="5" Command="{Binding gotoNews}"  Image="ic_news"
        Style="{StaticResource plainButton}" />
                            <Label FontSize="12" Text="NEWS" HorizontalOptions="Center"/>

                        </StackLayout>

                        <StackLayout Grid.Row="2" Grid.Column="2" Orientation="Vertical">
                        <Button Margin="5"  Command="{Binding gotoKGCash}" Image="ic_kgcash"
        Style="{StaticResource plainButton}" />
                            <Label FontSize="12" Text="E-WALLET" HorizontalOptions="Center"/>
                        </StackLayout>

                        <StackLayout Orientation="Vertical" Grid.Row="3" Grid.Column="0">
                            <Button Margin="5"  Image="ic_ecommerce"
        Style="{StaticResource plainButton}" />
                            <Label FontSize="12" Text="E-COMMERCE" HorizontalOptions="Center"/>
                        </StackLayout>

                        <StackLayout Orientation="Vertical" Grid.Row="3" Grid.Column="1">
                        <Button Margin="5"  Command="{Binding gotoSetting}" Image="ic_pointsummary.png"
        Style="{StaticResource plainButton}" />
                            <Label FontSize="12" Text="POINT SUMMARY" HorizontalOptions="Center"/>
                        </StackLayout>

                        <StackLayout Orientation="Vertical" Grid.Row="3" Grid.Column="2">
                        <Button Margin="5"  Command="{Binding gotoSetting}" Image="ic_setting"
        Style="{StaticResource plainButton}" />
                            <Label FontSize="12" Text="SETTINGS" HorizontalOptions="Center"/>
                        </StackLayout>

                    </Grid>

            </ScrollView>

        </StackLayout>

    </ContentPage.Content>
</ContentPage>
</code>```

i already try change the navigation service to use pushmodalasync, make the navigation async but still crash, Anyone can help me ? and i'm not using prism , mvvmlight and other 3rd party mvvm nuget

答:
It depends on your MainPage. Did you check if GetCurrentPage() actually returns something?

Try to change the GetCurrentPage() to:

```<code>Page GetCurrentPage() =>
  Application.Current.MainPage.Navigation?.NavigationStack?.LastOrDefault() ??
  Application.Current.MainPage;
</code>```

Another problems that I spotted:

1. C# naming conventions are different from Java. Method names should start with a capital letter. Currently you have a pure mix.

2. Initialising the BindingContext in XAML the way you did will create the ViewModel twice due to a bug. Change it to:

```<code><ContentPage
  xmlns:vm="your-namespace.vm"
  ...>
  <ContentPage.BindingContext>
    <vm:GridMenuViewModel />
  </ContentPage.BindingContext>
</ContentPage>
</code>```

3. No need to recreate the NavigationService for each command. Reuse it in your ViewModel.

4. You have some corrupted XAML:

```<code><StackLayout  BackgroundColor="##CEB053">
</code>```

Fix the hex code. Generally speaking you could enable XAMLC so you would get notified about XAML errors while building your code.

5. In order to use PushAsync your MainPage should be wrapped by NavigationPage.

6. You need to await async code execution:

```<code>public async Task GoToCardCommnunity()
{
  var currentPage = GetCurrentPage();
  await currentPage.Navigation.PushAsync(new CardCommunityPage());
}
</code>```

Check over the list above and pay attention to the application output and exceptions.

Body:
I try using mvvm in my xamarin forms but i'm still litle bit confused with the navigation in each page, I Already Create Interface and NavigationService to handle all Navigation in my Xamarin Forms, there is no error code line but when i click the buton and try to navigate to other page it always crash. Here is some of my code
My Interface

namespace KGVC.Interfaces
{
    public interface INavigationService
    {
        void NavigateToDashboard();
        void NavigateToLogout();
        void NavigateBack();
        void gotoNews();
        void goEvent();
        void gotoKGCash();
        void gotoCardCommnunity();
        void gotoSetting();
        void gotoNearbyLocation();
    }
}

my navigationservice

namespace KGVC.Services
{
    public class NavigationService : INavigationService
    {
        public  void goEvent()
        {
            var currentPage = GetCurrentPage();

             currentPage.Navigation.PushAsync(new EventPage());
        }

        public  void gotoCardCommnunity()
        {
            var currentPage = GetCurrentPage();

             currentPage.Navigation.PushAsync(new CardCommunityPage());
        }

        public  void gotoKGCash()
        {
            var currentPage = GetCurrentPage();

             currentPage.Navigation.PushAsync(new KGCashPage());
        }

        public  void gotoNearbyLocation()
        {
            var currentPage = GetCurrentPage();

             currentPage.Navigation.PushAsync(new StoreMaps());
        }

        public  void gotoNews()
        {
            var currentPage = GetCurrentPage();

             currentPage.Navigation.PushAsync(new RssFeedView());
        }

        public   void gotoSetting()
        {
            var currentPage = GetCurrentPage();

             currentPage.Navigation.PushAsync(new SettingPages());
        }

        public void NavigateBack()
        {
            throw new NotImplementedException();
        }

        public  void NavigateToDashboard()
        {

            var currentPage = GetCurrentPage();

             Application.Current.MainPage = new MainPage();
        }

        public void NavigateToLogout()
        {
            var currentPage = GetCurrentPage();
            Application.Current.MainPage = new NewPageLogin();
        }

        private Page GetCurrentPage()
        {
            var currentPage = Application.Current.MainPage.Navigation.NavigationStack.LastOrDefault();

            return currentPage;
        }
    }
}

my view model

public class GridMenuViewModel
    {

        public ICommand gotoNews { get; private set; }
        public ICommand goEvent { get; private set; }
        public ICommand gotoKGCash { get; private set; }
        public ICommand gotoSetting { get; private set; }
        public ICommand gotoNearbyLocation { get; private set; }
        public GridMenuViewModel()
        {
            gotoNews = new Command(() =>
            {
                var navigationService = new NavigationService();

                navigationService.gotoNews();
            });
            goEvent = new Command(() =>
            {
                var navigationService = new NavigationService();

                navigationService.goEvent();
            });

            gotoKGCash = new Command(() =>
            {
                var navigationService = new NavigationService();

                navigationService.gotoKGCash();
            });
            gotoSetting = new Command(() =>
            {
                var navigationService = new NavigationService();

                navigationService.gotoSetting();
            });
            gotoNearbyLocation = new Command(() =>
            {
                var navigationService = new NavigationService();

                navigationService.gotoNearbyLocation();
            });
        }
    }

And my view

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             NavigationPage.HasNavigationBar="True"
             NavigationPage.BackButtonTitle="False"
               BindingContext="{Binding GridMenuViewModel, Source={StaticResource Locator}}"
             xmlns:control="clr-namespace:Xamarin.Forms;assembly=Xamarin.Forms.CarouselView"
             xmlns:local="clr-namespace:KGVC.Views.MainPages"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="KGVC.Views.MainPages.GridMenu"
             Title="HOME"
            >

    <ContentPage.Content>
        <StackLayout >
            <StackLayout  BackgroundColor="##CEB053">
                <StackLayout  HeightRequest="35" BackgroundColor="##CEB053" Orientation="Horizontal">

                </StackLayout>

                <StackLayout  Padding="0"  HeightRequest="30" BackgroundColor="#E3E6E3" Orientation="Horizontal">
                    <Image Margin="5" Source="ic_logo.png"/>

                </StackLayout>

            </StackLayout>

            <StackLayout  HeightRequest="220" VerticalOptions="StartAndExpand">

                <control:CarouselView HeightRequest="185" ItemsSource="{Binding MyDataSource}" Position="{Binding Position, Mode=TwoWay}">
                    <control:CarouselView.ItemTemplate>
                        <DataTemplate>
                            <Image  Source="{Binding Image}"/>

                        </DataTemplate>
                    </control:CarouselView.ItemTemplate>
                </control:CarouselView>
                <local:CarouselIndicators IndicatorHeight="9" IndicatorWidth="9" UnselectedIndicator="unselected_circle.png" SelectedIndicator="selected_circle.png" Position="{Binding Position}" ItemsSource="{Binding MyDataSource}" />
            </StackLayout>

            <ScrollView IsClippedToBounds="True" VerticalOptions="StartAndExpand" Orientation="Vertical" >

                    <Grid x:Name="controlGrid" VerticalOptions="StartAndExpand" HeightRequest="370" Margin="15">

                        <Grid.RowDefinitions>
                            <RowDefinition Height="0" />
                            <RowDefinition Height="100" />
                            <RowDefinition Height="100" />
                            <RowDefinition Height="100" />

                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>

                            <ColumnDefinition Width="110" />
                            <ColumnDefinition Width="110" />
                            <ColumnDefinition Width="110" />

                        </Grid.ColumnDefinitions>

                        <StackLayout Orientation="Vertical"  Grid.Row="1" Grid.Column="0" >
                            <Button Image="ic_account.png" Margin="5"
        Style="{StaticResource plainButton}" />

                        </StackLayout>

                        <StackLayout Orientation="Vertical" Grid.Row="1" Grid.Column="1">
                        <Button Margin="5" Command="{Binding gotoCardCommunity}" Image="ic_card.png"
        Style="{StaticResource plainButton}" />

                        </StackLayout>

                        <StackLayout Orientation="Vertical" Grid.Row="1" Grid.Column="2">
                        <Button Margin="5" Command="{Binding goEvent}" Image="ic_event"
        Style="{StaticResource plainButton}" />

                        </StackLayout>

                        <StackLayout Grid.Row="2" Grid.Column="0" Orientation="Vertical">
                        <Button Margin="5" Command="{Binding gotoNearbyLocation}" Image="ic_store"
        Style="{StaticResource plainButton}" />

                        </StackLayout>

                        <StackLayout Orientation="Vertical" Grid.Row="2" Grid.Column="1">
                        <Button Margin="5" Command="{Binding gotoNews}"  Image="ic_news"
        Style="{StaticResource plainButton}" />

                        </StackLayout>

                        <StackLayout Grid.Row="2" Grid.Column="2" Orientation="Vertical">
                        <Button Margin="5"  Command="{Binding gotoKGCash}" Image="ic_kgcash"
        Style="{StaticResource plainButton}" />

                        </StackLayout>

                        <StackLayout Orientation="Vertical" Grid.Row="3" Grid.Column="0">
                            <Button Margin="5"  Image="ic_ecommerce"
        Style="{StaticResource plainButton}" />

                        </StackLayout>

                        <StackLayout Orientation="Vertical" Grid.Row="3" Grid.Column="1">
                        <Button Margin="5"  Command="{Binding gotoSetting}" Image="ic_pointsummary.png"
        Style="{StaticResource plainButton}" />

                        </StackLayout>

                        <StackLayout Orientation="Vertical" Grid.Row="3" Grid.Column="2">
                        <Button Margin="5"  Command="{Binding gotoSetting}" Image="ic_setting"
        Style="{StaticResource plainButton}" />

                        </StackLayout>

                    </Grid>

            </ScrollView>

        </StackLayout>

    </ContentPage.Content>
</ContentPage>

i already try change the navigation service to use pushmodalasync, make the navigation async but still crash, Anyone can help me ? and i'm not using prism , mvvmlight and other 3rd party mvvm nuget

Body:
It depends on your MainPage. Did you check if GetCurrentPage() actually returns something?

Try to change the GetCurrentPage() to:

Page GetCurrentPage() =>
  Application.Current.MainPage.Navigation?.NavigationStack?.LastOrDefault() ??
  Application.Current.MainPage;

Another problems that I spotted:

1. C# naming conventions are different from Java. Method names should start with a capital letter. Currently you have a pure mix.

2. Initialising the BindingContext in XAML the way you did will create the ViewModel twice due to a bug. Change it to:

<ContentPage
  xmlns:vm="your-namespace.vm"
  ...>
  <ContentPage.BindingContext>
    <vm:GridMenuViewModel />
  </ContentPage.BindingContext>
</ContentPage>

3. No need to recreate the NavigationService for each command. Reuse it in your ViewModel.

4. You have some corrupted XAML:

<StackLayout  BackgroundColor="##CEB053">

Fix the hex code. Generally speaking you could enable XAMLC so you would get notified about XAML errors while building your code.

5. In order to use PushAsync your MainPage should be wrapped by NavigationPage.

6. You need to await async code execution:

public async Task GoToCardCommnunity()
{
  var currentPage = GetCurrentPage();
  await currentPage.Navigation.PushAsync(new CardCommunityPage());
}

Check over the list above and pay attention to the application output and exceptions.


问:
Laravel get unknown file after upload
in my administrator of website, i'm implementing upload file, when i design view and define validations and controller this uploader upload unknown file into upload directory when i try to use that

result of dd($request->all()); is:

```<code>array:6 [▼
  "_token" => "9tNfMnakc6viX2qYRYr6abkrJapo1qz7jG88USYf"
  "title" => "hello"
  "type" => "post"
  "images" => "Untitled-1.png"
]
</code>```

validation:

```<code>return [
    'title' => 'required|string|max:200|unique:contents',
    'images'=>'required|mimes:jpeg,jpg,gif,png'
];
</code>```

my store function on controller:

```<code>public function store(RequestContents $request)
{
    $featured_images = $request->file('images');
    $this->uploadImage($featured_images);
    ...
}

public function uploadImage($file)
{
    $year = Carbon::now()->year;
    $imagePath = "/uploads/post_images/{$year}/";
    $filename = $file->getClientOriginalName();
    $file->move(public_path($imagePath, $filename));
}
</code>```

html:

```<code><form action="manage_contents" method="POST" enctype="multipart/form-data">
...

<div class="media-body">
    <input type="file" class="file-styled" name="images">
</div>

...
</form>
</code>```

output:

答:
Try changing

```<code>$file->move(public_path($imagePath, $filename))
</code>```

To

```<code>$file->move(public_path($imagePath), $filename)
</code>```

as first parameter takes the destination folder name and the second parameter takes the new file name

API Reference

Title: Laravel get unknown file after upload

Body:
in my administrator of website, i'm implementing upload file, when i design view and define validations and controller this uploader upload unknown file into upload directory when i try to use that

result of dd($request->all()); is:

array:6 [▼
  "_token" => "9tNfMnakc6viX2qYRYr6abkrJapo1qz7jG88USYf"
  "title" => "hello"
  "type" => "post"
  "images" => "Untitled-1.png"
]

validation:

return [
    'title' => 'required|string|max:200|unique:contents',
    'images'=>'required|mimes:jpeg,jpg,gif,png'
];

my store function on controller:

public function store(RequestContents $request)
{
    $featured_images = $request->file('images');
    $this->uploadImage($featured_images);
    ...
}

public function uploadImage($file)
{
    $year = Carbon::now()->year;
    $imagePath = "/uploads/post_images/{$year}/";
    $filename = $file->getClientOriginalName();
    $file->move(public_path($imagePath, $filename));
}

html:

<form action="manage_contents" method="POST" enctype="multipart/form-data">
...

    <input type="file" class="file-styled" name="images">

...
</form>

output:

Body:
Try changing

$file->move(public_path($imagePath, $filename))

To

$file->move(public_path($imagePath), $filename)

as first parameter takes the destination folder name and the second parameter takes the new file name

API Reference


问:
Angular4 + Protractor + Cucumber + TypeScript + weback-dev-server - Angular not found

OS: macOS Sierra 10.12.4

Node: v7.9.0

Npm: 5.0.3

Cucumber-js: 2.3.0

Protractor: 4.0.14

TypeScript: 2.2.2

webpack-dev-server: 2.4.5

i have a problem with running e2e tests. When I try to get an element from the page:

```<code>const el = browser.findElement(by.id('app-name'));
el.getText().then(function (text) {
    console.log(text);
    callback();
});
</code>```

using 'browser' I get this error:

```<code>> test-app@0.0.1 bdd:test /Users/p24/PhpstormProjects/alex-angular2
> node ./node_modules/.bin/protractor

(node:28198) DeprecationWarning: os.tmpDir() is deprecated. Use os.tmpdir() instead.
[13:03:31] I/hosted - Using the selenium server at http://selenium-standalone-chrome:4444/wd/hub
[13:03:31] I/launcher - Running 1 instances of WebDriver
Feature: : adding an advertisement

  @web-test
  Scenario: : adding new advertisement
  ✔ Given I am on the main page
  ✔ When I click the add advertisement button
  ✖ Then I should see the form to add an advertisement

Failures:

1) Scenario: : adding new advertisement - features/adding_advertisement.feature:5
   Step: Then I should see the form to add an advertisement - features/adding_advertisement.feature:8
   Step Definition: features/step_definitions/advertisement.ts:32
   Message:
     Error: function timed out after 5000 milliseconds
         at Timeout._onTimeout (/Users/p24/PhpstormProjects/alex-angular2/node_modules/cucumber/lib/user_code_runner.js:91:22)
         at ontimeout (timers.js:386:14)
         at tryOnTimeout (timers.js:250:5)
         at Timer.listOnTimeout (timers.js:214:5)

1 scenario (1 failed)
3 steps (1 failed, 2 passed)
0m05.026s
Cucumber HTML report report/html/cucumber_report_hierarchy.html generated successfully.
Modified files:
[13:03:47] E/protractor - Could not find Angular on page http://alex.local/ : retries looking for angular exceeded
[13:03:47] E/launcher - Angular could not be found on the page http://alex.local/. If this is not an Angular application, you may need to turn off waiting for Angular. Please see https://github.com/angular/protractor/blob/master/docs/timeouts.md#waiting-for-angular-on-page-load
[13:03:47] E/launcher - Error: Angular could not be found on the page http://alex.local/. If this is not an Angular application, you may need to turn off waiting for Angular. Please see https://github.com/angular/protractor/blob/master/docs/timeouts.md#waiting-for-angular-on-page-load
    at /Users/p24/PhpstormProjects/alex-angular2/node_modules/protractor/built/browser.js:506:23
    at ManagedPromise.invokeCallback_ (/Users/p24/PhpstormProjects/alex-angular2/node_modules/protractor/node_modules/selenium-webdriver/lib/promise.js:1379:14)
    at TaskQueue.execute_ (/Users/p24/PhpstormProjects/alex-angular2/node_modules/protractor/node_modules/selenium-webdriver/lib/promise.js:2913:14)
    at TaskQueue.executeNext_ (/Users/p24/PhpstormProjects/alex-angular2/node_modules/protractor/node_modules/selenium-webdriver/lib/promise.js:2896:21)
    at asyncRun (/Users/p24/PhpstormProjects/alex-angular2/node_modules/protractor/node_modules/selenium-webdriver/lib/promise.js:2775:27)
    at /Users/p24/PhpstormProjects/alex-angular2/node_modules/protractor/node_modules/selenium-webdriver/lib/promise.js:639:7
    at process._tickCallback (internal/process/next_tick.js:109:7)
[13:03:47] E/launcher - Process exited with error code 199
npm ERR! code ELIFECYCLE
npm ERR! errno 199
npm ERR! test-app@0.0.1 bdd:test: `node ./node_modules/.bin/protractor`
npm ERR! Exit status 199
npm ERR!
npm ERR! Failed at the test-app@0.0.1 bdd:test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/p24/.npm/_logs/2017-06-10T11_03_47_694Z-debug.log
</code>```

Here is my webpack.config:

```<code>'use strict';

const HtmlWebpack = require('html-webpack-plugin');
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const extractPlugin = new ExtractTextPlugin({
   filename: 'main.css'
});
const CleanWebpack = require('clean-webpack-plugin');

const rootDir = path.resolve(__dirname);

module.exports = {
    devServer: {
        contentBase: path.resolve(rootDir, 'dist'),
        port: 3000,
        host: '0.0.0.0',
        disableHostCheck: true,
        public: '172.23.0.1'
    },
    watchOptions: {
        poll: true
    },
    devtool: 'source-map',
    entry: {
        "bundle": "./src/webpack.main.js",
        "plugins": "./src/plugins.js"
    },
    output: {
        path: path.resolve(__dirname, "dist"),
        filename: "[name].js",
        // publicPath: "/dist"
    },
    resolve: {
        extensions: [ '.js', '.ts' ]
    },
    module: {
        exprContextCritical: false,
        rules: [
            {
                test: /\.html$/,
                use: [
                    {
                        loader: 'file-loader',
                        options: {
                            name: '[name].[ext]'
                        },
                    },
                    { loader: 'extract-loader' },
                    { loader: 'html-loader' }
                ],
                exclude: path.resolve(__dirname, 'src/index.html')
            },
            {
                test: /\index.html$/,
                loader: ['html-loader']
            },
            {
                test: /\.ts$/,
                loader: 'ts-loader',
                exclude: /node_modules/
            },
            {
                test: /\.(scss|css)$/,
                use: extractPlugin.extract({
                    use: ['css-loader', 'sass-loader']
                })
            },
            {
                test: /\.(jpg|png|gif|eot|ttf|svg|woff|woff2)$/,
                use: [{
                    loader: 'file-loader',
                    options: {
                        name: '[name].[ext]',
                        outputPath: 'img/',
                        publicPath: 'img/'
                    }
                }]
            },
        ],
    },
    plugins: [
        new CleanWebpack(['dist']),
        extractPlugin,
        new HtmlWebpack({
            template: 'src/index.html'
        }),
        new webpack.ProvidePlugin({
            $: "jquery",
            jQuery: "jquery",
            "window.jQuery": "jquery",
            "Tether": 'tether'
        })
    ],
};
</code>```

My protractor.config:

```<code>// Protractor configuration file, see link for more information
// https://github.com/angular/protractor/blob/master/lib/config.ts

exports.config = {
    seleniumAddress: 'http://selenium-standalone-chrome:4444/wd/hub',

    baseUrl: 'http://alex.local',

    capabilities: {
        browserName:'chrome'
    },

    framework: 'custom',

    frameworkPath: require.resolve('protractor-cucumber-framework'),

    specs: [
        './features/*.feature'
    ],

    cucumberOpts: {
        require: ['./features/step_definitions/*.ts'],
        tags: [],
        strict: false,
        format: ["pretty", "json:report/json/cucumber_report.json"],
        dryRun: false,
        compiler: ["ts:ts-node/register"]
    },

    onPrepare: function () {
        browser.manage().window().maximize();
    }
};
</code>```

And my step definition file where an error occurs:

```<code>'use strict';

import {browser, element, by, By, $, $$, ExpectedConditions} from 'protractor';

const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');

chai.use(chaiAsPromised);
const expect = chai.expect;

const {defineSupportCode} = require('cucumber');

    defineSupportCode(function(context: any) {

        const Given = context.Given;
        const When = context.When;
        const Then = context.Then;

        Given('I am on the main page', function (callback: any) {
            browser.get('http://alex.local');
            callback();
        });

        When('I click the add advertisement button', function (callback: any) {
            callback();
        });

        Then('I should see the form to add an advertisement', function (callback: any) {
            const el = browser.findElement(by.id('app-name'));
            el.getText().then(function (text) {
                console.log(text);
                callback();
            });
        });

    });

    export {};
</code>```

Everything is serve by the docker. docker-compose.yml:

```<code>version: '2'
services:
  proxy:
    image: jwilder/nginx-proxy
    container_name: nginx-proxy-alex
    ports:
      - "80:80"
    volumes:
      - /var/run/docker.sock:/tmp/docker.sock:ro
  app:
     build: .
     command: npm run build
     environment:
       - NODE_ENV=development
       - VIRTUAL_HOST=alex.local
     volumes:
       - .:/usr/src/app
       - /usr/src/app/node_modules
     ports:
      - "8080:3000"
  selenium-chrome:
    image: selenium/standalone-chrome
    environment:
      - VIRTUAL_HOST=selenium-standalone-chrome
    ports:
      - "4444:4444"
</code>```

答:
I solved this problem. All you have to do is run a dev server containing your app before tests. This works using webpack. I don't know how to run dev server in protractor using SystemJS. If you know how, please let me know;) Here is my protractor.conf.js:</p>

```<code>// Protractor configuration file, see link for more information
    // https://github.com/angular/protractor/blob/master/lib/config.ts
    var webpack = require('webpack');
    var WebpackDevServer = require('webpack-dev-server');
    var webpackConfig = require('./webpack.config');
    var deasync = require('deasync');
    var ip = require('ip');
    var server;
    var port = 5000;
    var baseUrl = 'http://' + ip.address() + ':' + port;
    function writeScreenShot(data, filename) {
        const stream = fs.createWriteStream(filename);
        stream.write(new Buffer(data, 'base64'));
        stream.end();
    }
    exports.config = {
        seleniumAddress: 'http://selenium-standalone-chrome:4444/wd/hub',
        baseUrl: baseUrl,
        useAllAngular2AppRoots: true,
        // directConnect: true,
        // chromeOnly:true,
        restartBrowserBetweenTests: true,
        ignoreUncaughtExceptions: true,
        beforeLaunch: () => {
            var isServerReady = false;
            var isBundleReady = false;
            var compiler = webpack(webpackConfig, () => {
                isBundleReady = true;
            });
            server = new WebpackDevServer(compiler, {});
            server.listen(port, () => {
                isServerReady = true;
            });
            deasync.loopWhile(() => !isServerReady || !isBundleReady);
        },
        afterLaunch: () => {
            server.close();
        },
        capabilities: {
            browserName: 'chrome',
        },
        framework: 'custom',
        frameworkPath: require.resolve('protractor-cucumber-framework'),
        specs: [
            './features/*.feature'
        ],
        cucumberOpts: {
            require: ['./features/step_definitions/*.ts'],
            tags: [],
            strict: false,
            format: ["pretty", "json:report/json/cucumber_report.json"],
            dryRun: false,
            compiler: ["ts:ts-node/register"],
        },
        onPrepare: function () {
            browser.ignoreSynchronization = true;
            browser.manage().window().setSize(1366, 768);
        }
    };
</code>```

Body:
OS: macOS Sierra 10.12.4

Node: v7.9.0

Npm: 5.0.3

Cucumber-js: 2.3.0

Protractor: 4.0.14

TypeScript: 2.2.2

webpack-dev-server: 2.4.5

i have a problem with running e2e tests. When I try to get an element from the page:

const el = browser.findElement(by.id('app-name'));
el.getText().then(function (text) {
    console.log(text);
    callback();
});

using 'browser' I get this error:

> test-app@0.0.1 bdd:test /Users/p24/PhpstormProjects/alex-angular2
> node ./node_modules/.bin/protractor

(node:28198) DeprecationWarning: os.tmpDir() is deprecated. Use os.tmpdir() instead.
[13:03:31] I/hosted - Using the selenium server at http://selenium-standalone-chrome:4444/wd/hub
[13:03:31] I/launcher - Running 1 instances of WebDriver
Feature: : adding an advertisement

  @web-test
  Scenario: : adding new advertisement
  ✔ Given I am on the main page
  ✔ When I click the add advertisement button
  ✖ Then I should see the form to add an advertisement

Failures:

1) Scenario: : adding new advertisement - features/adding_advertisement.feature:5
   Step: Then I should see the form to add an advertisement - features/adding_advertisement.feature:8
   Step Definition: features/step_definitions/advertisement.ts:32
   Message:
     Error: function timed out after 5000 milliseconds
         at Timeout._onTimeout (/Users/p24/PhpstormProjects/alex-angular2/node_modules/cucumber/lib/user_code_runner.js:91:22)
         at ontimeout (timers.js:386:14)
         at tryOnTimeout (timers.js:250:5)
         at Timer.listOnTimeout (timers.js:214:5)

1 scenario (1 failed)
3 steps (1 failed, 2 passed)
0m05.026s
Cucumber HTML report report/html/cucumber_report_hierarchy.html generated successfully.
Modified files:
[13:03:47] E/protractor - Could not find Angular on page http://alex.local/ : retries looking for angular exceeded
[13:03:47] E/launcher - Angular could not be found on the page http://alex.local/. If this is not an Angular application, you may need to turn off waiting for Angular. Please see https://github.com/angular/protractor/blob/master/docs/timeouts.md#waiting-for-angular-on-page-load
[13:03:47] E/launcher - Error: Angular could not be found on the page http://alex.local/. If this is not an Angular application, you may need to turn off waiting for Angular. Please see https://github.com/angular/protractor/blob/master/docs/timeouts.md#waiting-for-angular-on-page-load
    at /Users/p24/PhpstormProjects/alex-angular2/node_modules/protractor/built/browser.js:506:23
    at ManagedPromise.invokeCallback_ (/Users/p24/PhpstormProjects/alex-angular2/node_modules/protractor/node_modules/selenium-webdriver/lib/promise.js:1379:14)
    at TaskQueue.execute_ (/Users/p24/PhpstormProjects/alex-angular2/node_modules/protractor/node_modules/selenium-webdriver/lib/promise.js:2913:14)
    at TaskQueue.executeNext_ (/Users/p24/PhpstormProjects/alex-angular2/node_modules/protractor/node_modules/selenium-webdriver/lib/promise.js:2896:21)
    at asyncRun (/Users/p24/PhpstormProjects/alex-angular2/node_modules/protractor/node_modules/selenium-webdriver/lib/promise.js:2775:27)
    at /Users/p24/PhpstormProjects/alex-angular2/node_modules/protractor/node_modules/selenium-webdriver/lib/promise.js:639:7
    at process._tickCallback (internal/process/next_tick.js:109:7)
[13:03:47] E/launcher - Process exited with error code 199
npm ERR! code ELIFECYCLE
npm ERR! errno 199
npm ERR! test-app@0.0.1 bdd:test: `node ./node_modules/.bin/protractor`
npm ERR! Exit status 199
npm ERR!
npm ERR! Failed at the test-app@0.0.1 bdd:test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/p24/.npm/_logs/2017-06-10T11_03_47_694Z-debug.log

Here is my webpack.config:

'use strict';

const HtmlWebpack = require('html-webpack-plugin');
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const extractPlugin = new ExtractTextPlugin({
   filename: 'main.css'
});
const CleanWebpack = require('clean-webpack-plugin');

const rootDir = path.resolve(__dirname);

module.exports = {
    devServer: {
        contentBase: path.resolve(rootDir, 'dist'),
        port: 3000,
        host: '0.0.0.0',
        disableHostCheck: true,
        public: '172.23.0.1'
    },
    watchOptions: {
        poll: true
    },
    devtool: 'source-map',
    entry: {
        "bundle": "./src/webpack.main.js",
        "plugins": "./src/plugins.js"
    },
    output: {
        path: path.resolve(__dirname, "dist"),
        filename: "[name].js",
        // publicPath: "/dist"
    },
    resolve: {
        extensions: [ '.js', '.ts' ]
    },
    module: {
        exprContextCritical: false,
        rules: [
            {
                test: /\.html$/,
                use: [
                    {
                        loader: 'file-loader',
                        options: {
                            name: '[name].[ext]'
                        },
                    },
                    { loader: 'extract-loader' },
                    { loader: 'html-loader' }
                ],
                exclude: path.resolve(__dirname, 'src/index.html')
            },
            {
                test: /\index.html$/,
                loader: ['html-loader']
            },
            {
                test: /\.ts$/,
                loader: 'ts-loader',
                exclude: /node_modules/
            },
            {
                test: /\.(scss|css)$/,
                use: extractPlugin.extract({
                    use: ['css-loader', 'sass-loader']
                })
            },
            {
                test: /\.(jpg|png|gif|eot|ttf|svg|woff|woff2)$/,
                use: [{
                    loader: 'file-loader',
                    options: {
                        name: '[name].[ext]',
                        outputPath: 'img/',
                        publicPath: 'img/'
                    }
                }]
            },
        ],
    },
    plugins: [
        new CleanWebpack(['dist']),
        extractPlugin,
        new HtmlWebpack({
            template: 'src/index.html'
        }),
        new webpack.ProvidePlugin({
            $: "jquery",
            jQuery: "jquery",
            "window.jQuery": "jquery",
            "Tether": 'tether'
        })
    ],
};

My protractor.config:

// Protractor configuration file, see link for more information
// https://github.com/angular/protractor/blob/master/lib/config.ts

exports.config = {
    seleniumAddress: 'http://selenium-standalone-chrome:4444/wd/hub',

    baseUrl: 'http://alex.local',

    capabilities: {
        browserName:'chrome'
    },

    framework: 'custom',

    frameworkPath: require.resolve('protractor-cucumber-framework'),

    specs: [
        './features/*.feature'
    ],

    cucumberOpts: {
        require: ['./features/step_definitions/*.ts'],
        tags: [],
        strict: false,
        format: ["pretty", "json:report/json/cucumber_report.json"],
        dryRun: false,
        compiler: ["ts:ts-node/register"]
    },

    onPrepare: function () {
        browser.manage().window().maximize();
    }
};

And my step definition file where an error occurs:

'use strict';

import {browser, element, by, By, $, $$, ExpectedConditions} from 'protractor';

const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');

chai.use(chaiAsPromised);
const expect = chai.expect;

const {defineSupportCode} = require('cucumber');

    defineSupportCode(function(context: any) {

        const Given = context.Given;
        const When = context.When;
        const Then = context.Then;

        Given('I am on the main page', function (callback: any) {
            browser.get('http://alex.local');
            callback();
        });

        When('I click the add advertisement button', function (callback: any) {
            callback();
        });

        Then('I should see the form to add an advertisement', function (callback: any) {
            const el = browser.findElement(by.id('app-name'));
            el.getText().then(function (text) {
                console.log(text);
                callback();
            });
        });

    });

    export {};

Everything is serve by the docker. docker-compose.yml:

version: '2'
services:
  proxy:
    image: jwilder/nginx-proxy
    container_name: nginx-proxy-alex
    ports:
      - "80:80"
    volumes:
      - /var/run/docker.sock:/tmp/docker.sock:ro
  app:
     build: .
     command: npm run build
     environment:
       - NODE_ENV=development
       - VIRTUAL_HOST=alex.local
     volumes:
       - .:/usr/src/app
       - /usr/src/app/node_modules
     ports:
      - "8080:3000"
  selenium-chrome:
    image: selenium/standalone-chrome
    environment:
      - VIRTUAL_HOST=selenium-standalone-chrome
    ports:
      - "4444:4444"

Body:
I solved this problem. All you have to do is run a dev server containing your app before tests. This works using webpack. I don't know how to run dev server in protractor using SystemJS. If you know how, please let me know;) Here is my protractor.conf.js:

// Protractor configuration file, see link for more information
    // https://github.com/angular/protractor/blob/master/lib/config.ts
    var webpack = require('webpack');
    var WebpackDevServer = require('webpack-dev-server');
    var webpackConfig = require('./webpack.config');
    var deasync = require('deasync');
    var ip = require('ip');
    var server;
    var port = 5000;
    var baseUrl = 'http://' + ip.address() + ':' + port;
    function writeScreenShot(data, filename) {
        const stream = fs.createWriteStream(filename);
        stream.write(new Buffer(data, 'base64'));
        stream.end();
    }
    exports.config = {
        seleniumAddress: 'http://selenium-standalone-chrome:4444/wd/hub',
        baseUrl: baseUrl,
        useAllAngular2AppRoots: true,
        // directConnect: true,
        // chromeOnly:true,
        restartBrowserBetweenTests: true,
        ignoreUncaughtExceptions: true,
        beforeLaunch: () => {
            var isServerReady = false;
            var isBundleReady = false;
            var compiler = webpack(webpackConfig, () => {
                isBundleReady = true;
            });
            server = new WebpackDevServer(compiler, {});
            server.listen(port, () => {
                isServerReady = true;
            });
            deasync.loopWhile(() => !isServerReady || !isBundleReady);
        },
        afterLaunch: () => {
            server.close();
        },
        capabilities: {
            browserName: 'chrome',
        },
        framework: 'custom',
        frameworkPath: require.resolve('protractor-cucumber-framework'),
        specs: [
            './features/*.feature'
        ],
        cucumberOpts: {
            require: ['./features/step_definitions/*.ts'],
            tags: [],
            strict: false,
            format: ["pretty", "json:report/json/cucumber_report.json"],
            dryRun: false,
            compiler: ["ts:ts-node/register"],
        },
        onPrepare: function () {
            browser.ignoreSynchronization = true;
            browser.manage().window().setSize(1366, 768);
        }
    };


问:
Using importXML results in "Imported Content is Empty" error on Google Spreadsheets
What I'm trying to do:

Dynamically import the bitcoin/BTC price, from https://www.luno.com/en/price/, OR https://www.luno.com/en/price/BTC.

So I've read everything there is to read (on this site anyway) about importXML, and cannot find what I'm doing wrong. My method works on other websites, where I get a list of expected results, however, using importXML is not working. See below code I'm using (I've used other variants, but this is the one suggested using SelectorGadget:

```<code>=IMPORTXML("https://www.luno.com/en/price/", "//*[contains(concat( ' ', @class, ' ' ), concat( ' ', 'ng-binding', ' ' ))]")
</code>```

Of course, I get the dreaded " Imported Content is Empty " error.

Any help?

答:
You can load this ajax endpoint to get the current USD:

https://www.luno.com/ajax/1/display_ticker

or for all currency pairs:

https://www.luno.com/ajax/1/price_chart?currency=

if your want to parse the json - there is a wonderful - already written importJson script (https://github.com/bradjasper/ImportJSON/blob/master/ImportJSON.gs), you literally just copy paste it into your apps script and then call the url directly as such:

=importJSON("https://www.luno.com/ajax/1/price_chart?currency=")

or

=importJSON("https://www.luno.com/ajax/1/display_ticker?currency=XBT")

Body:
What I'm trying to do:

Dynamically import the bitcoin/BTC price, from https://www.luno.com/en/price/, OR https://www.luno.com/en/price/BTC.

So I've read everything there is to read (on this site anyway) about importXML, and cannot find what I'm doing wrong. My method works on other websites, where I get a list of expected results, however, using importXML is not working. See below code I'm using (I've used other variants, but this is the one suggested using SelectorGadget:

=IMPORTXML("https://www.luno.com/en/price/", "//*[contains(concat( ' ', @class, ' ' ), concat( ' ', 'ng-binding', ' ' ))]")

Of course, I get the dreaded " Imported Content is Empty " error.

Any help?


问:
vectorize this for loop (current row is dependent on row above)
Suppose I want to create n=3 random walk paths (pathlength = 100) given a pre-generated matrix (100x3) of plus/minus ones. The first path will start at 10, the second at 20, the third at 30:

set.seed(123)

given.rand.matrix <- replicate(3,sign(rnorm(100)))

path <- matrix(NA,101,3)

path[1,] = c(10,20,30)

for (j in 2:101) {

  path[j,]<-path[j-1,]+given.rand.matrix[j-1,]

}

The end values (given the seed and rand matrix) are 14, 6, 34... which is the desired result... but...

Question: Is there a way to vectorize the for loop? The problem is that the path matrix is not yet fully populated when calculating. Thus, replacing the loop with

path[2:101,]<-path[1:100,]+given.rand.matrix

returns mostly NAs. I just want to know if this type of for loop is avoidable in R.

Thank you very much in advance.

ContentLicense: CC BY-SA 2.5

Body:
Definitely vectorizable: Skip the initialization of path, and use cumsum over the matrix:

path <- apply( rbind(c(10,20,30),given.rand.matrix), 2, cumsum)

> head(path)
     [,1] [,2] [,3]
[1,]   10   20   30
[2,]    9   19   31
[3,]    8   20   32
[4,]    9   19   31
[5,]   10   18   32
[6,]   11   17   31
> tail(path)
       [,1] [,2] [,3]
[96,]    15    7   31
[97,]    14    8   32
[98,]    15    9   33
[99,]    16    8   32
[100,]   15    7   33
[101,]   14    6   34


问:
Continuously update marker when location changed on Android
I'm trying to implement an simple navigation app using Google maps. Initially I developed a code for marking two Geo points on map and showing route between them.
Now I am trying to move the first marker towards second marker (destination) based on users location.

For this I used LocationListener and implemented code in onLocationChanged.
The problem is onLocationChanged is not getting fired and marker is not moving based on user location.
Here is my code.

MapActivity.java

```<code>public class MapActivity extends FragmentActivity implements OnMapClickListener, LocationListener{

private GoogleMap gMap;
private ArrayList<LatLng> markersArray; //Marker points ArrayList
private ArrayList<Marker> markers;
private MarkerOptions options; //Marker options
String distance="";
String duration="";
private TextView travelDetails;
private ProgressDialog pDialog;
private double lattitude=0.0;
private double longitude=0.0;
Marker mMarker;
String bestAvailableProvider;
private LocationManager mLocationManager;

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

    //Loading Google Maps
    try{
        loadMapView();
        markersArray=new ArrayList<LatLng>();
        markers=new ArrayList<Marker>();
        gMap.setOnMapClickListener(this);
        gMap.setMyLocationEnabled(true);
        gMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
        travelDetails=(TextView) findViewById(R.id.lbl_traveldetails);
        pDialog=new ProgressDialog(MapActivity.this);
    }catch(Exception e){
        e.printStackTrace();
    }

}

/*
 * This method loads map
 *
 */

private void loadMapView(){

    if (gMap==null) {
        gMap=((SupportMapFragment)getSupportFragmentManager()
                .findFragmentById(R.id.map_fragment)).getMap();
    }

    mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);

    // Specify Location Provider criteria
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setAltitudeRequired(false);
    criteria.setBearingRequired(false);
    criteria.setCostAllowed(true);
    criteria.setSpeedRequired(false);
    mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,this);

}

/*
 * catches onclick event of map
 * @see com.google.android.gms.maps.GoogleMap.OnMapClickListener#onMapClick(com.google.android.gms.maps.model.LatLng)
 */

@Override
public void onMapClick(LatLng point) {

    //Clearing markers in map

    if (markersArray.size()>1) {
        markersArray.clear();
        gMap.clear();

    }

    //Adding  marker to array
    markersArray.add(point);

    //marking point on Map
    addMarkerOnMap(point);

    //Drawing route when two markers are placed

    if(markersArray.size() >= 2){
        LatLng origin = markersArray.get(0);
        LatLng dest = markersArray.get(1);

        String url = getDirectionsUrl(origin, dest);

        DownloadTask downloadTask = new DownloadTask();

        downloadTask.execute(url);
    }

}

/*
 * This method places markers on map
 */

private void addMarkerOnMap(LatLng point){

    //Marking points on map
    options=new MarkerOptions();
    options.position(point);

    //Setting marker icons

    if (markersArray.size()==1) {

        //Source marker point
        options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));

    }else if(markersArray.size()==2){

        //Destination marker point
        options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
    }

    //adding marker point to map
    try{
        Marker mMarker=gMap.addMarker(options);

        markers.add(mMarker);
    }catch(Exception e){
        e.printStackTrace();
    }

}

/*
 * Getting direction url between two points
 *
 */

private String getDirectionsUrl(LatLng origin,LatLng dest){

    // Origin of route
    String str_origin = "origin="+origin.latitude+","+origin.longitude;

    // Destination of route
    String str_dest = "destination="+dest.latitude+","+dest.longitude;

    // Sensor enabled
    String sensor = "sensor=false";

    // Building the parameters to the web service
    String parameters = str_origin+"&"+str_dest+"&"+sensor;

    // Output format
    String output = "json";

    String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;

    return url;
}

/*
 * passing the direction url
 *
 */

private class DownloadTask extends AsyncTask<String, Void, String>{

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog.show();
        pDialog.setMessage("Loading route...");
        pDialog.setCancelable(false);
    }

    // Downloading data in non-ui thread
    @Override
    protected String doInBackground(String... url) {

        // For storing data from web service
        String data = "";

        try{
            // Fetching the data from web service
            data = downloadUrl(url[0]);
        }catch(Exception e){
            Log.d("Background Task",e.toString());
        }
        return data;
    }

    // Executes in UI thread, after the execution of
    // doInBackground()
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        ParserTask parserTask = new ParserTask();

        // Invokes the thread for parsing the JSON data
        parserTask.execute(result);
    }
}

/*
 * downloading from url
 *
 */

private String downloadUrl(String strUrl) throws IOException{
    String data = "";
    InputStream iStream = null;
    HttpURLConnection urlConnection = null;
    try{
        URL url = new URL(strUrl);

        urlConnection = (HttpURLConnection) url.openConnection();

        // Connecting to url
        urlConnection.connect();

        // Reading data from url
        iStream = urlConnection.getInputStream();

        BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

        StringBuffer sb  = new StringBuffer();

        String line = "";
        while( ( line = br.readLine())  != null){
            sb.append(line);
        }

        data = sb.toString();

        br.close();

    }catch(Exception e){
        Log.d("Exception while downloading url", e.toString());
    }finally{
        iStream.close();
        urlConnection.disconnect();
    }
    return data;
}

private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String,String>>>>{

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {

        JSONObject jObject;
        List<List<HashMap<String, String>>> routes = null;

        try{
            jObject = new JSONObject(jsonData[0]);
            DirectionsJsonParser parser = new DirectionsJsonParser();

            // Starts parsing data
            routes = parser.parse(jObject);
        }catch(Exception e){
            e.printStackTrace();
        }
        return routes;
    }

    @Override
    protected void onPostExecute(List<List<HashMap<String, String>>> result) {
        ArrayList<LatLng> points = null;
        PolylineOptions lineOptions = null;
        //  MarkerOptions markerOptions = new MarkerOptions();

        // Traversing through all the routes
        for(int i=0;i<result.size();i++){
            points = new ArrayList<LatLng>();
            lineOptions = new PolylineOptions();

            // Fetching i-th route
            List<HashMap<String, String>> path = result.get(i);

            // Fetching all the points in i-th route
            for(int j=0;j<path.size();j++){
                HashMap<String,String> point = path.get(j);

                if(j==0){    // Get distance from the list
                    distance = (String)point.get("distance");
                    continue;
                }else if(j==1){ // Get duration from the list
                    duration = (String)point.get("duration");
                    continue;
                }

                double lat = Double.parseDouble(point.get("lat"));
                double lng = Double.parseDouble(point.get("lng"));
                LatLng position = new LatLng(lat, lng);

                points.add(position);
            }

            // Adding all the points in the route to LineOptions
            lineOptions.addAll(points);
            lineOptions.width(5);
            lineOptions.color(Color.BLUE);
        }

        // Drawing polyline in the Google Map for the i-th route
        try{
            gMap.addPolyline(lineOptions);
            travelDetails.setText("Distance:"+distance+"Duration:"+duration);
            pDialog.dismiss();
        }catch (Exception e) {
            if (pDialog.isShowing()) {
                pDialog.dismiss();
            }
            Toast.makeText(getApplicationContext(), "No Road route found.", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }
}

@Override
protected void onResume() {
    super.onResume();

    loadMapView();
}

@Override
protected void onPause() {
    super.onPause();
    mLocationManager.removeUpdates(this);
}

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

/*
 * (non-Javadoc)
 * @see com.google.android.gms.maps.LocationSource.OnLocationChangedListener#onLocationChanged(android.location.Location)
 */

@Override
public void onLocationChanged(Location location) {
    Log.e("loca", ""+location.getLatitude());

    try {

        if(markersArray.size()>0){

            lattitude=location.getLatitude();
            longitude=location.getLongitude();

            LatLng mLatLng=new LatLng(lattitude, longitude);
            Marker newMarker=markers.get(0);
            newMarker.setPosition(mLatLng);
            gMap.animateCamera(CameraUpdateFactory.newLatLng(mLatLng));
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

}

@Override
public void onProviderDisabled(String provider) {
    // TODO Auto-generated method stub

}

@Override
public void onProviderEnabled(String provider) {
    // TODO Auto-generated method stub
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub
}

}
</code>```

DirectionsJsonParser.java

```<code>public class DirectionsJsonParser {
public List<List<HashMap<String,String>>> parse(JSONObject jObject){

    List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String,String>>>() ;
    JSONArray jRoutes = null;
    JSONArray jLegs = null;
    JSONArray jSteps = null;
    JSONObject jDistance = null;
    JSONObject jDuration = null;

    try {

        jRoutes = jObject.getJSONArray("routes");

        for(int i=0;i<jRoutes.length();i++){
            jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs");
            List path = new ArrayList<HashMap<String, String>>();

            for(int j=0;j<jLegs.length();j++){
                jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray("steps");

                /** Getting distance from the json data */
                jDistance = ((JSONObject) jLegs.get(j)).getJSONObject("distance");
                HashMap<String, String> hmDistance = new HashMap<String, String>();
                hmDistance.put("distance", jDistance.getString("text"));

                /** Getting duration from the json data */
                jDuration = ((JSONObject) jLegs.get(j)).getJSONObject("duration");
                HashMap<String, String> hmDuration = new HashMap<String, String>();
                hmDuration.put("duration", jDuration.getString("text"));

                /** Adding distance object to the path */
                path.add(hmDistance);

                /** Adding duration object to the path */
                path.add(hmDuration);

                /** Getting poly points */
                for(int k=0;k<jSteps.length();k++){
                    String polyline = "";
                    polyline = (String)((JSONObject)((JSONObject)jSteps.get(k)).get("polyline")).get("points");
                    List<LatLng> list = decodePoly(polyline);

                    for(int l=0;l<list.size();l++){
                        HashMap<String, String> hm = new HashMap<String, String>();
                        hm.put("lat", Double.toString(((LatLng)list.get(l)).latitude) );
                        hm.put("lng", Double.toString(((LatLng)list.get(l)).longitude) );
                        path.add(hm);
                    }
                }
                /** Adding poly points */
                routes.add(path);
            }
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }catch (Exception e){
    }
    return routes;
}

private List<LatLng> decodePoly(String encoded) {

    List<LatLng> poly = new ArrayList<LatLng>();
    int index = 0, len = encoded.length();
    int lat = 0, lng = 0;

    while (index < len) {
        int b, shift = 0, result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lat += dlat;

        shift = 0;
        result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lng += dlng;

        LatLng p = new LatLng((((double) lat / 1E5)),
                (((double) lng / 1E5)));
        poly.add(p);
    }
    return poly;
}

}
</code>```

答:
I think you have not used location provider ,  use googleapiclient

and read about this topic , it allows you to show your current position on map when location  changed, that provides you your current locations.

Hint

Implements GoogleApiClient.ConnectionCallbacks , GoogleApiClient.OnConnectionFailedListener
in your activity then you can easily do that.

Body:
I'm trying to implement an simple navigation app using Google maps. Initially I developed a code for marking two Geo points on map and showing route between them.
Now I am trying to move the first marker towards second marker (destination) based on users location.

For this I used LocationListener and implemented code in onLocationChanged.
The problem is onLocationChanged is not getting fired and marker is not moving based on user location.
Here is my code.

MapActivity.java

public class MapActivity extends FragmentActivity implements OnMapClickListener, LocationListener{

private GoogleMap gMap;
private ArrayList<LatLng> markersArray; //Marker points ArrayList
private ArrayList<Marker> markers;
private MarkerOptions options; //Marker options
String distance="";
String duration="";
private TextView travelDetails;
private ProgressDialog pDialog;
private double lattitude=0.0;
private double longitude=0.0;
Marker mMarker;
String bestAvailableProvider;
private LocationManager mLocationManager;

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

    //Loading Google Maps
    try{
        loadMapView();
        markersArray=new ArrayList<LatLng>();
        markers=new ArrayList<Marker>();
        gMap.setOnMapClickListener(this);
        gMap.setMyLocationEnabled(true);
        gMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
        travelDetails=(TextView) findViewById(R.id.lbl_traveldetails);
        pDialog=new ProgressDialog(MapActivity.this);
    }catch(Exception e){
        e.printStackTrace();
    }

}

/*
 * This method loads map
 *
 */

private void loadMapView(){

    if (gMap==null) {
        gMap=((SupportMapFragment)getSupportFragmentManager()
                .findFragmentById(R.id.map_fragment)).getMap();
    }

    mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);

    // Specify Location Provider criteria
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setAltitudeRequired(false);
    criteria.setBearingRequired(false);
    criteria.setCostAllowed(true);
    criteria.setSpeedRequired(false);
    mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,this);

}

/*
 * catches onclick event of map
 * @see com.google.android.gms.maps.GoogleMap.OnMapClickListener#onMapClick(com.google.android.gms.maps.model.LatLng)
 */

@Override
public void onMapClick(LatLng point) {

    //Clearing markers in map

    if (markersArray.size()>1) {
        markersArray.clear();
        gMap.clear();

    }

    //Adding  marker to array
    markersArray.add(point);

    //marking point on Map
    addMarkerOnMap(point);

    //Drawing route when two markers are placed

    if(markersArray.size() >= 2){
        LatLng origin = markersArray.get(0);
        LatLng dest = markersArray.get(1);

        String url = getDirectionsUrl(origin, dest);

        DownloadTask downloadTask = new DownloadTask();

        downloadTask.execute(url);
    }

}

/*
 * This method places markers on map
 */

private void addMarkerOnMap(LatLng point){

    //Marking points on map
    options=new MarkerOptions();
    options.position(point);

    //Setting marker icons

    if (markersArray.size()==1) {

        //Source marker point
        options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));

    }else if(markersArray.size()==2){

        //Destination marker point
        options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
    }

    //adding marker point to map
    try{
        Marker mMarker=gMap.addMarker(options);

        markers.add(mMarker);
    }catch(Exception e){
        e.printStackTrace();
    }

}

/*
 * Getting direction url between two points
 *
 */

private String getDirectionsUrl(LatLng origin,LatLng dest){

    // Origin of route
    String str_origin = "origin="+origin.latitude+","+origin.longitude;

    // Destination of route
    String str_dest = "destination="+dest.latitude+","+dest.longitude;

    // Sensor enabled
    String sensor = "sensor=false";

    // Building the parameters to the web service
    String parameters = str_origin+"&"+str_dest+"&"+sensor;

    // Output format
    String output = "json";

    String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;

    return url;
}

/*
 * passing the direction url
 *
 */

private class DownloadTask extends AsyncTask<String, Void, String>{

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog.show();
        pDialog.setMessage("Loading route...");
        pDialog.setCancelable(false);
    }

    // Downloading data in non-ui thread
    @Override
    protected String doInBackground(String... url) {

        // For storing data from web service
        String data = "";

        try{
            // Fetching the data from web service
            data = downloadUrl(url[0]);
        }catch(Exception e){
            Log.d("Background Task",e.toString());
        }
        return data;
    }

    // Executes in UI thread, after the execution of
    // doInBackground()
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        ParserTask parserTask = new ParserTask();

        // Invokes the thread for parsing the JSON data
        parserTask.execute(result);
    }
}

/*
 * downloading from url
 *
 */

private String downloadUrl(String strUrl) throws IOException{
    String data = "";
    InputStream iStream = null;
    HttpURLConnection urlConnection = null;
    try{
        URL url = new URL(strUrl);

        urlConnection = (HttpURLConnection) url.openConnection();

        // Connecting to url
        urlConnection.connect();

        // Reading data from url
        iStream = urlConnection.getInputStream();

        BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

        StringBuffer sb  = new StringBuffer();

        String line = "";
        while( ( line = br.readLine())  != null){
            sb.append(line);
        }

        data = sb.toString();

        br.close();

    }catch(Exception e){
        Log.d("Exception while downloading url", e.toString());
    }finally{
        iStream.close();
        urlConnection.disconnect();
    }
    return data;
}

private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String,String>>>>{

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {

        JSONObject jObject;
        List<List<HashMap<String, String>>> routes = null;

        try{
            jObject = new JSONObject(jsonData[0]);
            DirectionsJsonParser parser = new DirectionsJsonParser();

            // Starts parsing data
            routes = parser.parse(jObject);
        }catch(Exception e){
            e.printStackTrace();
        }
        return routes;
    }

    @Override
    protected void onPostExecute(List<List<HashMap<String, String>>> result) {
        ArrayList<LatLng> points = null;
        PolylineOptions lineOptions = null;
        //  MarkerOptions markerOptions = new MarkerOptions();

        // Traversing through all the routes
        for(int i=0;i<result.size();i++){
            points = new ArrayList<LatLng>();
            lineOptions = new PolylineOptions();

            // Fetching i-th route
            List<HashMap<String, String>> path = result.get(i);

            // Fetching all the points in i-th route
            for(int j=0;j<path.size();j++){
                HashMap<String,String> point = path.get(j);

                if(j==0){    // Get distance from the list
                    distance = (String)point.get("distance");
                    continue;
                }else if(j==1){ // Get duration from the list
                    duration = (String)point.get("duration");
                    continue;
                }

                double lat = Double.parseDouble(point.get("lat"));
                double lng = Double.parseDouble(point.get("lng"));
                LatLng position = new LatLng(lat, lng);

                points.add(position);
            }

            // Adding all the points in the route to LineOptions
            lineOptions.addAll(points);
            lineOptions.width(5);
            lineOptions.color(Color.BLUE);
        }

        // Drawing polyline in the Google Map for the i-th route
        try{
            gMap.addPolyline(lineOptions);
            travelDetails.setText("Distance:"+distance+"Duration:"+duration);
            pDialog.dismiss();
        }catch (Exception e) {
            if (pDialog.isShowing()) {
                pDialog.dismiss();
            }
            Toast.makeText(getApplicationContext(), "No Road route found.", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }
}

@Override
protected void onResume() {
    super.onResume();

    loadMapView();
}

@Override
protected void onPause() {
    super.onPause();
    mLocationManager.removeUpdates(this);
}

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

/*
 * (non-Javadoc)
 * @see com.google.android.gms.maps.LocationSource.OnLocationChangedListener#onLocationChanged(android.location.Location)
 */

@Override
public void onLocationChanged(Location location) {
    Log.e("loca", ""+location.getLatitude());

    try {

        if(markersArray.size()>0){

            lattitude=location.getLatitude();
            longitude=location.getLongitude();

            LatLng mLatLng=new LatLng(lattitude, longitude);
            Marker newMarker=markers.get(0);
            newMarker.setPosition(mLatLng);
            gMap.animateCamera(CameraUpdateFactory.newLatLng(mLatLng));
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

}

@Override
public void onProviderDisabled(String provider) {
    // TODO Auto-generated method stub

}

@Override
public void onProviderEnabled(String provider) {
    // TODO Auto-generated method stub
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub
}

}

DirectionsJsonParser.java

public class DirectionsJsonParser {
public List<List<HashMap<String,String>>> parse(JSONObject jObject){

    List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String,String>>>() ;
    JSONArray jRoutes = null;
    JSONArray jLegs = null;
    JSONArray jSteps = null;
    JSONObject jDistance = null;
    JSONObject jDuration = null;

    try {

        jRoutes = jObject.getJSONArray("routes");

        for(int i=0;i<jRoutes.length();i++){
            jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs");
            List path = new ArrayList<HashMap<String, String>>();

            for(int j=0;j<jLegs.length();j++){
                jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray("steps");

                /** Getting distance from the json data */
                jDistance = ((JSONObject) jLegs.get(j)).getJSONObject("distance");
                HashMap<String, String> hmDistance = new HashMap<String, String>();
                hmDistance.put("distance", jDistance.getString("text"));

                /** Getting duration from the json data */
                jDuration = ((JSONObject) jLegs.get(j)).getJSONObject("duration");
                HashMap<String, String> hmDuration = new HashMap<String, String>();
                hmDuration.put("duration", jDuration.getString("text"));

                /** Adding distance object to the path */
                path.add(hmDistance);

                /** Adding duration object to the path */
                path.add(hmDuration);

                /** Getting poly points */
                for(int k=0;k<jSteps.length();k++){
                    String polyline = "";
                    polyline = (String)((JSONObject)((JSONObject)jSteps.get(k)).get("polyline")).get("points");
                    List<LatLng> list = decodePoly(polyline);

                    for(int l=0;l<list.size();l++){
                        HashMap<String, String> hm = new HashMap<String, String>();
                        hm.put("lat", Double.toString(((LatLng)list.get(l)).latitude) );
                        hm.put("lng", Double.toString(((LatLng)list.get(l)).longitude) );
                        path.add(hm);
                    }
                }
                /** Adding poly points */
                routes.add(path);
            }
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }catch (Exception e){
    }
    return routes;
}

private List<LatLng> decodePoly(String encoded) {

    List<LatLng> poly = new ArrayList<LatLng>();
    int index = 0, len = encoded.length();
    int lat = 0, lng = 0;

    while (index < len) {
        int b, shift = 0, result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lat += dlat;

        shift = 0;
        result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lng += dlng;

        LatLng p = new LatLng((((double) lat / 1E5)),
                (((double) lng / 1E5)));
        poly.add(p);
    }
    return poly;
}

}


问:
Angular 4 host header request not set
I am trying to send a request to a server, and I want to change the host. The code is the following:

```<code>let headers = new HttpHeaders({'Host': 'www.test.com'});
    console.log(headers.get('Host'));

this.http.post("/test",headers);
</code>```

The host is still localhost:8080. I am using Angular 4 and HttpClient.
 How can I set the host?

答:
Second parameter should be data..Please try this.</p>

```<code>var headers = new Headers();
headers.append('Host', 'www.test.com');
headers.append('X-SCOPE-ID', '27JM38');
this.http.post("/test",data,{headers: headers});
</code>```

Title: Angular 4 host header request not set

Body:
I am trying to send a request to a server, and I want to change the host. The code is the following:

let headers = new HttpHeaders({'Host': 'www.test.com'});
    console.log(headers.get('Host'));

this.http.post("/test",headers);

The host is still localhost:8080. I am using Angular 4 and HttpClient.
 How can I set the host?

Body:
Second parameter should be data..Please try this.

var headers = new Headers();
headers.append('Host', 'www.test.com');
headers.append('X-SCOPE-ID', '27JM38');
this.http.post("/test",data,{headers: headers});