问:
App Splash Screen Takes Time After Clearing Cache Data
I am newbie in Android Application Development.My Splash screen takes 19s to load when the app data is cleared from settings.
When App launches the Splash Screen takes 5s.I have no idea why it is taking time
Below is my android AndroidManifest file code:

```<code>   <activity android:name=".activity.SplashActivity"
            android:screenOrientation="portrait"
            android:theme="@style/SplashTheme"
            >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
</code>```

My Splash Activity is as follows

```<code>public class SplashActivity extends AppCompatActivity {

public final int SPLASH_DISPLAY_LENGTH=1000;

@Override
protected void onCreate(Bundle savedInstanceState) {
   setTheme(R.style.SplashTheme);
   super.onCreate(savedInstanceState);
   // setContentView(R.layout.activity_splash);

    new Handler().postDelayed(new Runnable(){
        @Override
        public void run() {
            /* Create an Intent that will start the Menu-Activity. */
            Intent mainIntent = new Intent(SplashActivity.this,MainActivity.class);
            startActivity(mainIntent);
            finish();
        }
    }, SPLASH_DISPLAY_LENGTH);
}
}
</code>```

My Splash theme is as follows:

```<code><style name="SplashTheme" parent="Theme.AppCompat.NoActionBar">
    <item name="android:windowDisablePreview">true</item>
    <item name="android:windowBackground">@drawable/splash_screen_drawable</item>
</style>
</code>```

My Splash screen drawable is as follows:

```<code><layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:drawable="@color/icons"

        />

    <item
        android:left="65dp"
        android:right="65dp">
        <bitmap
            android:gravity="center"
            android:src="@drawable/placeholder_splash"

             />

    </item>
    <item android:drawable="@android:color/transparent"></item>
</layer-list>
</code>```

答:
The problem is with Instant Run feature which takes too much time to load the Application just disable that feature.

For Windows : File → Settings → Build, Execution, Deployment → Instant
Run and uncheck Enable Instant Run.

For Mac : Android Studio → Preferences → Build, Execution, Deployment → Instant
Run and uncheck Enable Instant Run.

See the Below Screenshot and uncheck that two options. After that uninstall the application and then run the project again.

Body:
I am newbie in Android Application Development.My Splash screen takes 19s to load when the app data is cleared from settings.
When App launches the Splash Screen takes 5s.I have no idea why it is taking time
Below is my android AndroidManifest file code:

   <activity android:name=".activity.SplashActivity"
            android:screenOrientation="portrait"
            android:theme="@style/SplashTheme"
            >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

My Splash Activity is as follows

public class SplashActivity extends AppCompatActivity {

public final int SPLASH_DISPLAY_LENGTH=1000;

@Override
protected void onCreate(Bundle savedInstanceState) {
   setTheme(R.style.SplashTheme);
   super.onCreate(savedInstanceState);
   // setContentView(R.layout.activity_splash);

    new Handler().postDelayed(new Runnable(){
        @Override
        public void run() {
            /* Create an Intent that will start the Menu-Activity. */
            Intent mainIntent = new Intent(SplashActivity.this,MainActivity.class);
            startActivity(mainIntent);
            finish();
        }
    }, SPLASH_DISPLAY_LENGTH);
}
}

My Splash theme is as follows:

My Splash screen drawable is as follows:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:drawable="@color/icons"

        />

    <item
        android:left="65dp"
        android:right="65dp">
        <bitmap
            android:gravity="center"
            android:src="@drawable/placeholder_splash"

             />

    </item>
    <item android:drawable="@android:color/transparent"></item>
</layer-list>


来源: stackexchange

问:
java.lang. RuntimeException No Retrofit annotation found. (parameter #3)
I'm trying to update this RetroFit + Otto tutorial, so my code updated is:

IWeather.java

RetroFit 2.+ doesn't allow to return void, so instead of void getWeather(...) I added Call<Weather> getWeather(...).

```<code>public interface IWeather {

    @GET("/{latitude},{longitude}")
    Call<Weather> getWeather(@Path("latitude") String latitude,
                             @Path("longitude") String longitude,
                             Callback<Weather> callback);
}
</code>```

ForecastClient.java

RetroFit 2.+ has changed his constructor, so the new ForecastClient has the next form. The IllegalArgumentException points to the weather.getWeather(...) method.

```<code>public class ForecastClient {

    private static final String BASE_URL = "https://api.darksky.net/forecast/";
    private static final String API_KEY = "******************";
    public static final String API_URL = BASE_URL + API_KEY + "/";

    private static ForecastClient mForecastClient;
    private static Retrofit mRetroAdapter;

    public static ForecastClient getClient() {
        if (mForecastClient == null) {
            mForecastClient = new ForecastClient();
        }
        return mForecastClient;
    }

    private ForecastClient() {
        mRetroAdapter = new Retrofit.Builder()
                .baseUrl(API_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(new OkHttpClient())
                .build();
    }

    public void getWeather(String latitude, String longitude, Callback<Weather> callback) {
        IWeather weather = mRetroAdapter.create(IWeather.class);
        weather.getWeather(latitude, longitude, callback);
    }
}
</code>```

ForecastManager.java

```<code>public class ForecastManager {

    private Context mContext;
    private Bus mBus;
    private ForecastClient sForecastClient;

    public ForecastManager(Context context, Bus bus) {
        this.mContext = context;
        this.mBus = bus;
        sForecastClient = ForecastClient.getClient();
    }

    @Subscribe
    public void onGetWeatherEvent(GetWeatherEvent getWeatherEvent) {
        String latitude = Double.toString(getWeatherEvent.getLatitude()).trim();
        String longitude = Double.toString(getWeatherEvent.getLongitude()).trim();

        Callback<Weather> callback = new Callback<Weather>() {
            @Override
            public void onResponse(Call<Weather> call, Response<Weather> response) {
                Log.d(ForecastManager.class.getSimpleName(), response.body().toString());
                mBus.post(new SendWeatherEvent(response.body()));
            }

            @Override
            public void onFailure(Call<Weather> call, Throwable t) {
                Log.e(ForecastManager.class.getSimpleName(), t.getMessage());
            }
        };

        sForecastClient.getWeather(latitude, longitude, callback);
    }
}
</code>```

I'm receiving a No Retrofit annotation found and I guess the reason is something related with my callback, but it is a RetroFit callback, so I don't understand why the error.

The stacktrace points to the MainActivity, in particular to the Otto's method post() with a java.lang.RuntimeException: Could not dispatch event, caused by the error previously mentioned java.lang.IllegalArgumentException: No Retrofit annotation found. (parameter #3):

MainActivity.java

```<code>public class MainActivity extends AppCompatActivity {

    @BindView(R.id.activity_main_textView)
    TextView textView;
    @BindView(R.id.activity_main_button)
    Button button;

    private static final double LATITUDE = **.******;
    private static final double LONGITUDE = **.******;

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

        ButterKnife.bind(this);
    }

    @OnClick(R.id.activity_main_button)
    public void onClick(View view) {
        BusProvider.getInstace().post(new GetWeatherEvent(LATITUDE, LONGITUDE));
    }

    @Subscribe
    public void onSendWeatherEvent(SendWeatherEvent sendWeatherEvent) {
        Weather weather = sendWeatherEvent.getWeather();
        Currently currently = weather.getCurrently();
        textView.setText(currently.getSummary());
    }
</code>```

Any clue about where is the error or how should I handle the bus subscriptions, the callback, etcetera?

答:
```<code>java.lang.IllegalArgumentException: No Retrofit annotation found. (parameter #3)
</code>```

As the error says, the problem is that the third parameter of the getWeather method does not have an annotation. The Callback class is used for the Call#enqueue(Callback) method.

Simply change

```<code>sForecastClient.getWeather(latitude, longitude, callback)
</code>```

to

```<code>sForecastClient.getWeather(latitude, longitude).enqueue(callback)
</code>```

and remove the third parameter.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to update this RetroFit + Otto tutorial, so my code updated is:

IWeather.java

RetroFit 2.+ doesn't allow to return void, so instead of void getWeather(...) I added Call<Weather> getWeather(...).

public interface IWeather {

    @GET("/{latitude},{longitude}")
    Call<Weather> getWeather(@Path("latitude") String latitude,
                             @Path("longitude") String longitude,
                             Callback<Weather> callback);
}

ForecastClient.java

RetroFit 2.+ has changed his constructor, so the new ForecastClient has the next form. The IllegalArgumentException points to the weather.getWeather(...) method.

public class ForecastClient {

    private static final String BASE_URL = "https://api.darksky.net/forecast/";
    private static final String API_KEY = "******************";
    public static final String API_URL = BASE_URL + API_KEY + "/";

    private static ForecastClient mForecastClient;
    private static Retrofit mRetroAdapter;

    public static ForecastClient getClient() {
        if (mForecastClient == null) {
            mForecastClient = new ForecastClient();
        }
        return mForecastClient;
    }

    private ForecastClient() {
        mRetroAdapter = new Retrofit.Builder()
                .baseUrl(API_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(new OkHttpClient())
                .build();
    }

    public void getWeather(String latitude, String longitude, Callback<Weather> callback) {
        IWeather weather = mRetroAdapter.create(IWeather.class);
        weather.getWeather(latitude, longitude, callback);
    }
}

ForecastManager.java

public class ForecastManager {

    private Context mContext;
    private Bus mBus;
    private ForecastClient sForecastClient;

    public ForecastManager(Context context, Bus bus) {
        this.mContext = context;
        this.mBus = bus;
        sForecastClient = ForecastClient.getClient();
    }

    @Subscribe
    public void onGetWeatherEvent(GetWeatherEvent getWeatherEvent) {
        String latitude = Double.toString(getWeatherEvent.getLatitude()).trim();
        String longitude = Double.toString(getWeatherEvent.getLongitude()).trim();

        Callback<Weather> callback = new Callback<Weather>() {
            @Override
            public void onResponse(Call<Weather> call, Response<Weather> response) {
                Log.d(ForecastManager.class.getSimpleName(), response.body().toString());
                mBus.post(new SendWeatherEvent(response.body()));
            }

            @Override
            public void onFailure(Call<Weather> call, Throwable t) {
                Log.e(ForecastManager.class.getSimpleName(), t.getMessage());
            }
        };

        sForecastClient.getWeather(latitude, longitude, callback);
    }
}

I'm receiving a No Retrofit annotation found and I guess the reason is something related with my callback, but it is a RetroFit callback, so I don't understand why the error.

The stacktrace points to the MainActivity, in particular to the Otto's method post() with a java.lang.RuntimeException: Could not dispatch event, caused by the error previously mentioned java.lang.IllegalArgumentException: No Retrofit annotation found. (parameter #3):

MainActivity.java

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.activity_main_textView)
    TextView textView;
    @BindView(R.id.activity_main_button)
    Button button;

    private static final double LATITUDE = **.******;
    private static final double LONGITUDE = **.******;

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

        ButterKnife.bind(this);
    }

    @OnClick(R.id.activity_main_button)
    public void onClick(View view) {
        BusProvider.getInstace().post(new GetWeatherEvent(LATITUDE, LONGITUDE));
    }

    @Subscribe
    public void onSendWeatherEvent(SendWeatherEvent sendWeatherEvent) {
        Weather weather = sendWeatherEvent.getWeather();
        Currently currently = weather.getCurrently();
        textView.setText(currently.getSummary());
    }

Any clue about where is the error or how should I handle the bus subscriptions, the callback, etcetera?

Body:
java.lang.IllegalArgumentException: No Retrofit annotation found. (parameter #3)

As the error says, the problem is that the third parameter of the getWeather method does not have an annotation. The Callback class is used for the Call#enqueue(Callback) method.

Simply change

sForecastClient.getWeather(latitude, longitude, callback)

to

sForecastClient.getWeather(latitude, longitude).enqueue(callback)

and remove the third parameter.

ContentLicense: CC BY-SA 4.0


问:
FTP connection through PHP always ask for username & password
So I have an FTP server with bulk of large files (mostly satellite imagery data). I am building a system with PHP to serve users to download the files. The system can show the list of files in FTP server, so they can download the files. Typically, the list is not from the FTP server, I stored the list in the database.

For FTP connection, I have stored the details (ftp user, ftp password, and ftp server) in a config file. So here I don't want user input anything, just click the download button, and get the files.

The flow of my system is:

Check if the requested data is available.

If available, then do FTP connection with ftp_connect

If connection succeed, then login to FTP using ftp_login

Insert new record to the log table in the database.

Redirect user to the requested file using PHP header('Location:')

Close the FTP connection

It works actually!

But it always asks for FTP username and password for every user download requests.

So what is wrong? Or is there any better approach?

Edit:
Here is the code in download.php:

```<code>    <?php
    include "config.php";
    include "query_user.php";
    include "function.php";

    $data_id = $_GET['data_id'];

    $user_id = $query_user['user_id'];

    $query = mysqli_query($link, "SELECT count(*) as jumlah, data_url FROM lord_data WHERE data_id='".$data_id."'");
    $query_data = mysqli_fetch_array($query);

    if($query_data['jumlah'] > 0){
        $name= $query_data['data_url'];
        set_time_limit(20);
        $conn_id = ftp_connect($ftp_server, 21, 10);
        if($conn_id){
            $conn_login = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
            $query = mysqli_query($link, "INSERT INTO lord_download_log (user_id, data_id) VALUES ('$user_id', '$data_id')");
            header('Location: ftp://'.$ftp_server.'/foldername/'.$name.'');
            // close the connection
            ftp_close($conn_id);
        }else{
            $ftp_server = "172.xx.xx.xx";
            $change_ip = ftp_connect($ftp_server, 21, 10);
            if($change_ip){
                $conn_login = ftp_login($change_ip, $ftp_user_name,        $ftp_user_pass);
                $query = mysqli_query($link, "INSERT INTO lord_download_log (user_id, data_id) VALUES ('$user_id', '$data_id')");
                header('Location: ftp://'.$ftp_server.'/foldername/'.$name.'');
                // close the connection
                ftp_close($change_ip);
            }else{
                echo "Couldn't establish a connection.";
            }
        }

    }else{
        echo "<script>alert('Download failed! Data is not available');document.location='index.php?p=data_download';</script>";
    }
    ?>
</code>```

答:
@dileep-kumar It works now!

I change the code as follows:

```<code><?php
include 'config.php';
// connect and login to FTP server
$conn_id = ftp_connect($ftp_server, 21, 10);
$login = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
// turn passive mode on
ftp_pasv($conn_id, true);

if($login){
    $chdir = ftp_chdir($conn_id, "lisatstor01");
    $local_file = "local.zip";
    $server_file = "LA3_2016-10-19_Lumajang.zip";

    // download server file
    if (ftp_nb_get($conn_id, $local_file, $server_file, FTP_BINARY))
      {
          $quoted = sprintf('"%s"', addcslashes(basename($local_file), '"\\'));
          $size   = filesize($local_file);

          header('Content-Description: File Transfer');
          header('Content-Type: application/octet-stream');
          header('Content-Disposition: attachment; filename=' . $quoted);
          header('Content-Transfer-Encoding: binary');
          header('Connection: Keep-Alive');
          header('Expires: 0');
          header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
          header('Pragma: public');
          header('Content-Length: ' . $size);

        echo "Successfully written to $local_file.";
      }
    else
      {
      echo "Error downloading $server_file.";
    }
}else{
    echo "login failed";
}
// close connection
ftp_close($conn_id);
?>
</code>```

I change the directory where the files are located. I use ftp_nb_get instead of simple ftp_get.

The file is downloaded. But it is damaged/corrupted.

Body:
So I have an FTP server with bulk of large files (mostly satellite imagery data). I am building a system with PHP to serve users to download the files. The system can show the list of files in FTP server, so they can download the files. Typically, the list is not from the FTP server, I stored the list in the database.

For FTP connection, I have stored the details (ftp user, ftp password, and ftp server) in a config file. So here I don't want user input anything, just click the download button, and get the files.

The flow of my system is:

Check if the requested data is available.

If available, then do FTP connection with ftp_connect

If connection succeed, then login to FTP using ftp_login

Insert new record to the log table in the database.

Redirect user to the requested file using PHP header('Location:')

Close the FTP connection

It works actually!

But it always asks for FTP username and password for every user download requests.

So what is wrong? Or is there any better approach?

Edit:
Here is the code in download.php:

    <?php
    include "config.php";
    include "query_user.php";
    include "function.php";

    $data_id = $_GET['data_id'];

    $user_id = $query_user['user_id'];

    $query = mysqli_query($link, "SELECT count(*) as jumlah, data_url FROM lord_data WHERE data_id='".$data_id."'");
    $query_data = mysqli_fetch_array($query);

    if($query_data['jumlah'] > 0){
        $name= $query_data['data_url'];
        set_time_limit(20);
        $conn_id = ftp_connect($ftp_server, 21, 10);
        if($conn_id){
            $conn_login = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
            $query = mysqli_query($link, "INSERT INTO lord_download_log (user_id, data_id) VALUES ('$user_id', '$data_id')");
            header('Location: ftp://'.$ftp_server.'/foldername/'.$name.'');
            // close the connection
            ftp_close($conn_id);
        }else{
            $ftp_server = "172.xx.xx.xx";
            $change_ip = ftp_connect($ftp_server, 21, 10);
            if($change_ip){
                $conn_login = ftp_login($change_ip, $ftp_user_name,        $ftp_user_pass);
                $query = mysqli_query($link, "INSERT INTO lord_download_log (user_id, data_id) VALUES ('$user_id', '$data_id')");
                header('Location: ftp://'.$ftp_server.'/foldername/'.$name.'');
                // close the connection
                ftp_close($change_ip);
            }else{
                echo "Couldn't establish a connection.";
            }
        }

    }else{
        echo "";
    }
    ?>

Body:
@dileep-kumar It works now!

I change the code as follows:

<?php
include 'config.php';
// connect and login to FTP server
$conn_id = ftp_connect($ftp_server, 21, 10);
$login = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
// turn passive mode on
ftp_pasv($conn_id, true);

if($login){
    $chdir = ftp_chdir($conn_id, "lisatstor01");
    $local_file = "local.zip";
    $server_file = "LA3_2016-10-19_Lumajang.zip";

    // download server file
    if (ftp_nb_get($conn_id, $local_file, $server_file, FTP_BINARY))
      {
          $quoted = sprintf('"%s"', addcslashes(basename($local_file), '"\\'));
          $size   = filesize($local_file);

          header('Content-Description: File Transfer');
          header('Content-Type: application/octet-stream');
          header('Content-Disposition: attachment; filename=' . $quoted);
          header('Content-Transfer-Encoding: binary');
          header('Connection: Keep-Alive');
          header('Expires: 0');
          header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
          header('Pragma: public');
          header('Content-Length: ' . $size);

        echo "Successfully written to $local_file.";
      }
    else
      {
      echo "Error downloading $server_file.";
    }
}else{
    echo "login failed";
}
// close connection
ftp_close($conn_id);
?>

I change the directory where the files are located. I use ftp_nb_get instead of simple ftp_get.

The file is downloaded. But it is damaged/corrupted.


问:
eBay Kleinanzeigen API access (eBay Classifieds Germany)
For a mobile app we would love to integrate the eBay Kleinanzeigen (www.ebay-kleinanzeigen.de) API. Goal is to (API GET) get all the classifieds in a certain (German) zip code.

However the documentation is not very useful.

The API under https://api.ebay-kleinanzeigen.de/api/ads request login and password for this API. We used the username and password from www.ebay-kleinanzeigen.de and the eBay Partner (Developer) login credentials but both are not working.

Does anyone know how to use it and what credentials we need to use it or has experience with this API?

答:
The eBay Kleinanzeigen API is not public available and is used internally for some applications, including their own apps.

Still, some third parties have access to it, but this is always based on business reasons and contractually regulated. There is no regular developer program to access the API.

If you think you have a product which would work great with eBay Kleinanzeigens inventory, and for that also want to have access to the API you should contact their business development team.


问:
Multiple foreground colors in PowerShell in one command
I want to output many different foreground colors with one statement.

```<code>PS C:\> Write-Host "Red" -ForegroundColor Red
Red
</code>```

This output is red.

```<code>PS C:\> Write-Host "Blue" -ForegroundColor Blue
Blue
</code>```

This output is blue.

```<code>PS C:\> Write-Host "Red", "Blue" -ForegroundColor Red, Blue
Red Blue
</code>```

This output is magenta, but I want the color to be red for the word red, and blue for the word blue via the one command. How can I do that?

答:
This code is available with a different number of arguments: Text, ForeGroundColor, and BackGroundColor.

Each colorlist is used with a rotate implementation:

```<code>function Write-Color([String[]]$Text, [ConsoleColor[]]$ForeGroundColor, [ConsoleColor[]]$BackGroundColor) {
    for ($i = 0; $i -lt $Text.Length; $i++) {
        $Color = @{}
        if ($ForeGroundColor -and $BackGroundColor){
            $Color = @{
                ForegroundColor = $ForeGroundColor[$i%($ForeGroundColor.count)]
                BackgroundColor = $BackGroundColor[$i%($BackGroundColor.count)]
            }
        } elseif ($ForeGroundColor) {
            $Color = @{
                ForegroundColor = $ForeGroundColor[$i%($ForeGroundColor.count)]
            }
        } elseif ($BackGroundColor) {
            $Color = @{
                BackgroundColor = $BackGroundColor[$i%($BackGroundColor.count)]
            }
        }
        Write-Host $Text[$i] @color -NoNewLine
    }
    Write-Host
}
</code>```

Log usage:

```<code>Write-Color "Check color list...".PadRight(50), '[', '   OK   ', ']' -fore cyan, White, green, white
Write-Color "Red Check is good...".PadRight(50), '[' ,' ERROR! ', ']' -fore cyan, White, red, white
Write-Color "Write-Color is cool !".PadRight(50), '[', '  WARN  ', ']' -fore cyan, White, Yellow, white
</code>```

List Usage (just 2 backGroundColor and 4 foreGroundColor):

```<code>Write-Color (@(100..115) | %{" -> $_ : ".PadRight(30) + "`n"}) -ForeGroundColor cyan, yellow, magenta, red -BackGroundColor gray, black
</code>```

Standard Write-Host

```<code>Write-Host (@(100..115) | %{" -> $_ : ".PadRight(30) + "`n"}) -BackgroundColor gray
</code>```

Body:
I want to output many different foreground colors with one statement.

PS C:\> Write-Host "Red" -ForegroundColor Red
Red

This output is red.

PS C:\> Write-Host "Blue" -ForegroundColor Blue
Blue

This output is blue.

PS C:\> Write-Host "Red", "Blue" -ForegroundColor Red, Blue
Red Blue

This output is magenta, but I want the color to be red for the word red, and blue for the word blue via the one command. How can I do that?

Body:
This code is available with a different number of arguments: Text, ForeGroundColor, and BackGroundColor.

Each colorlist is used with a rotate implementation:

function Write-Color([String[]]$Text, [ConsoleColor[]]$ForeGroundColor, [ConsoleColor[]]$BackGroundColor) {
    for ($i = 0; $i -lt $Text.Length; $i++) {
        $Color = @{}
        if ($ForeGroundColor -and $BackGroundColor){
            $Color = @{
                ForegroundColor = $ForeGroundColor[$i%($ForeGroundColor.count)]
                BackgroundColor = $BackGroundColor[$i%($BackGroundColor.count)]
            }
        } elseif ($ForeGroundColor) {
            $Color = @{
                ForegroundColor = $ForeGroundColor[$i%($ForeGroundColor.count)]
            }
        } elseif ($BackGroundColor) {
            $Color = @{
                BackgroundColor = $BackGroundColor[$i%($BackGroundColor.count)]
            }
        }
        Write-Host $Text[$i] @color -NoNewLine
    }
    Write-Host
}

Log usage:

Write-Color "Check color list...".PadRight(50), '[', '   OK   ', ']' -fore cyan, White, green, white
Write-Color "Red Check is good...".PadRight(50), '[' ,' ERROR! ', ']' -fore cyan, White, red, white
Write-Color "Write-Color is cool !".PadRight(50), '[', '  WARN  ', ']' -fore cyan, White, Yellow, white

List Usage (just 2 backGroundColor and 4 foreGroundColor):

Write-Color (@(100..115) | %{" -> $_ : ".PadRight(30) + "`n"}) -ForeGroundColor cyan, yellow, magenta, red -BackGroundColor gray, black

Standard Write-Host

Write-Host (@(100..115) | %{" -> $_ : ".PadRight(30) + "`n"}) -BackgroundColor gray


问:
Javascript - Change Button function once I click it
I have a button and 3 functions.
change each funtion once I click it
Please Help me.</p>

答:
Try this,

Pass the this with in a function .It will target the same clicked button element

function change(that){
that.value="changed"
that.innerHTML="changed" //for inner html change
console.log(that.outerHTML)
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="btn" type="button" onclick="change()">click</button></code>```

For single line code

    <button id="btn" type="button" onclick="this.innerHTML='changed'">click</button>```

Body:
Try this,

Pass the this with in a function .It will target the same clicked button element

function change(that){
that.value="changed"
that.innerHTML="changed" //for inner html change
console.log(that.outerHTML)
}

<button id="btn" type="button" onclick="change()">click</button>

For single line code

    <button id="btn" type="button" onclick="this.innerHTML='changed'">click</button>


问:
How to write Join and where in Spark DataFrame (Converting SQL to DataFrame)
I need to write SQL Query into DataFrame

SQL Query

A_join_Deals = sqlContext.sql("SELECT * FROM A_transactions LEFT
JOIN Deals ON (Deals.device = A_transactions.device_id) WHERE
A_transactions.device_id IS NOT NULL AND A_transactions.device_id != '' AND
A_transactions.advertiser_app_object_id = '%s'"%(adv_id))
```

<p><strong>Code written up to now</strong></p>

<pre class="lang-scala prettyprint-override"><code>val A_join_Deals = Deals.join(A_transactions,Deals("device") === A_transactions("device_id"),"left")
</code>```

Now I am stuck how to write the where Clause.

Any Suggestion or Help is Highly appreciated.

答:
you can try as below </p>

```<code>val A_join_Deals = Deals.join(A_transactions,Deals("device") === A_transactions("device_id"),"left")
      .where(A_transactions("device_id").isNotNull && A_transactions("device_id") =!= "" && A_transactions("advertiser_app_object_id") === s"${adv_id}")
</code>```

Body:
I need to write SQL Query into DataFrame

SQL Query

A_join_Deals = sqlContext.sql("SELECT * FROM A_transactions LEFT
JOIN Deals ON (Deals.device = A_transactions.device_id) WHERE
A_transactions.device_id IS NOT NULL AND A_transactions.device_id != '' AND
A_transactions.advertiser_app_object_id = '%s'"%(adv_id))

Code written up to now

val A_join_Deals = Deals.join(A_transactions,Deals("device") === A_transactions("device_id"),"left")

Now I am stuck how to write the where Clause.

Any Suggestion or Help is Highly appreciated.

Body:
you can try as below

val A_join_Deals = Deals.join(A_transactions,Deals("device") === A_transactions("device_id"),"left")
      .where(A_transactions("device_id").isNotNull && A_transactions("device_id") =!= "" && A_transactions("advertiser_app_object_id") === s"${adv_id}")


问:
File system that uses tags rather than folders?
My files are a mess, I try to structure them into folders with names that describe what they are in a recursive class break-down sense but later on I have trouble finding the file again when I go looking for it (the one file can possibly exist in many folders).

What file system will allow me to find my files by a combination of tags instead of using folders?

If there was such a file system, I'm not sure how OSes would cope, being so deeply dependent on the folder system. I came across tag2find, which isn't too bad; it solves my problem with finding stuff for now but it is an application, not a file system.

答:
I came across this question while asking myself the same question about filesystem file tags. I then came across this application for Windows XP/Vista called TaggedFrog that may do the trick. Haven't tried it yet, but it looks promising.

Not looking forward to going through 1000s of files though! At any rate, I'll be forced to upgrade to Win7 at some point and can try its native tagging.

ContentLicense: CC BY-SA 2.5


答:
```<code><button type="button" onclick="a()">click</button>
</code>```

javascript

```<code>var a = (function() {
    var clicked = 0;
    return function() {
        clicked++;
        if (clicked == 1) f1(); // improve this part
        if (clicked == 2) f2();
        if (clicked == 3) f3();
    }

})()

function f1() {
    alert(1)
}

function f2() {
    alert(2)
}

function f3() {
    alert(3)
}
</code>```

demo

Title: Javascript - Change Button function once I click it

Body:
I have a button and 3 functions.
change each funtion once I click it
Please Help me.

Body:
<button type="button" onclick="a()">click</button>

javascript

var a = (function() {
    var clicked = 0;
    return function() {
        clicked++;
        if (clicked == 1) f1(); // improve this part
        if (clicked == 2) f2();
        if (clicked == 3) f3();
    }

})()

function f1() {
    alert(1)
}

function f2() {
    alert(2)
}

function f3() {
    alert(3)
}

demo


问:
Using column value if column exist
I am trying to select the values from column, if the column exist.

This table is going under some modification and some columns are removed and values are extracted to another table.

Query I am using is below. At this stage column can be presented or may be already dropped, so I am doing a column check

```<code>IF COL_LENGTH('MyTableName', 'MyColumnName') IS NOT NULL
BEGIN
    INSERT INTO SOMETABLE VALUES(TITLE,TYPEID)
    SELECT DISTINCT MyColumnName,2
    FROM MyTableName
END
</code>```

Also tried

```<code>IF EXISTS(SELECT 1 FROM sys.columns
          WHERE Name = N'MyColumnName'
          AND Object_ID = Object_ID(N'dbo.MyTableName'))
BEGIN
    INSERT INTO SOMETABLE VALUES(TITLE,TYPEID)
    SELECT DISTINCT MyColumnName,2
    FROM MyTableName
END
</code>```

But this give me error when the Column is dropped even with the column exist check

Invalid column name 'MyColumnName'

Is there a way to get around this

答:
Try with:</p>

```<code>IF EXISTS(SELECT 1 FROM sys.columns
          WHERE Name = N'MyColumnName'
          AND Object_ID = Object_ID(N'dbo.MyTableName'))
BEGIN
    INSERT INTO SOMETABLE VALUES(TITLE,TYPEID)
    SELECT DISTINCT MyColumnName,2
    FROM MyTableName
END
</code>```

Title: Using column value if column exist

Body:
I am trying to select the values from column, if the column exist.

This table is going under some modification and some columns are removed and values are extracted to another table.

Query I am using is below. At this stage column can be presented or may be already dropped, so I am doing a column check

IF COL_LENGTH('MyTableName', 'MyColumnName') IS NOT NULL
BEGIN
    INSERT INTO SOMETABLE VALUES(TITLE,TYPEID)
    SELECT DISTINCT MyColumnName,2
    FROM MyTableName
END

Also tried

IF EXISTS(SELECT 1 FROM sys.columns
          WHERE Name = N'MyColumnName'
          AND Object_ID = Object_ID(N'dbo.MyTableName'))
BEGIN
    INSERT INTO SOMETABLE VALUES(TITLE,TYPEID)
    SELECT DISTINCT MyColumnName,2
    FROM MyTableName
END

But this give me error when the Column is dropped even with the column exist check

Invalid column name 'MyColumnName'

Is there a way to get around this

Body:
Try with:

IF EXISTS(SELECT 1 FROM sys.columns
          WHERE Name = N'MyColumnName'
          AND Object_ID = Object_ID(N'dbo.MyTableName'))
BEGIN
    INSERT INTO SOMETABLE VALUES(TITLE,TYPEID)
    SELECT DISTINCT MyColumnName,2
    FROM MyTableName
END


问:
iOS8 How dynamically fixed UITableViewHeaderFooterView height size?
I use the method as follows

I have just tried below lines of code, dynamically set the UITableViewHeaderFooterView height size.

self.tableView.estimatedSectionHeaderHeight = 100
self.tableView.sectionHeaderHeight = UITableViewAutomaticDimension

I have the following problems

In iOS9, iOS10 can run normally, and can display properly. But can not be displayed correctly in iOS8, and the following error is displayed:

My analysis is as follows:

From the error prompt, I can see that the problem is NSLayoutConstraint: 0x7f8498d7b890 _UITableViewHeaderFooterContentView: 0x7f8498cb9200.height == 0

But I have never made any Constraints to UITableViewHeaderFooterContentView

How should I fit iOS8?

答:
You need to use the UIView systemLayoutSizeFittingSize:</p>

```<code>-(void)viewDidLayoutSubviews
    {
        [super viewDidLayoutSubviews];

        [ViewHeader setNeedsLayout];
        [ViewHeader layoutIfNeeded];
        CGFloat height = [ViewHeader systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;

        CGRect headerFrame = ViewHeader.frame;
        headerFrame.size.height = height;
        ViewHeader.frame = headerFrame;
        [tbl setTableHeaderView:ViewHeader];
    }
</code>```

Body:
You need to use the UIView systemLayoutSizeFittingSize:

-(void)viewDidLayoutSubviews
    {
        [super viewDidLayoutSubviews];

        [ViewHeader setNeedsLayout];
        [ViewHeader layoutIfNeeded];
        CGFloat height = [ViewHeader systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;

        CGRect headerFrame = ViewHeader.frame;
        headerFrame.size.height = height;
        ViewHeader.frame = headerFrame;
        [tbl setTableHeaderView:ViewHeader];
    }


问:
pythonic way of extracting desired substring from a bigger string
I have a string like this

```<code>msg = b'@\x06string\x083http://schemas.microsoft.com/2003/10/Serialization/\x9a\x05\x18{"PUID":"9279565","Title":"Risk Manager","Description":"<strong>Risk Manager </strong><br />\\n<br />\\nLentech, Inc. is currently seekinga Risk Manager inGreenbelt,"}\x01'
</code>```

The string {"PUID":"9279565","Title":"Risk Manager","Description":"Risk Manager
\\n
\\nLentech, Inc. is currently seekinga Risk Manager inGreenbelt,"} is json parsable. So I come up with the following code to remove garbage strings from the above msg

```<code>x1 =  msg.split(b'{"',1)[1]
>>>
>>> x1
b'PUID":"9279565","Title":"Risk Manager","Description":"<strong>Risk Manager </strong><br />\\n<br />\\nLentech, Inc. is currently seekinga Risk Manager inGreenbelt,"}\x01'
x2 = x1[::-1].split(b'}"', 1)[1][::-1]
>>> x2
b'PUID":"9279565","Title":"Risk Manager","Description":"<strong>Risk Manager </strong><br />\\n<br />\\nLentech, Inc. is currently seekinga Risk Manager inGreenbelt,'
>>> final_msg = b'{"%s"}'%x2
>>> final_msg
b'{"PUID":"9279565","Title":"Risk Manager","Description":"<strong>Risk Manager </strong><br />\\n<br />\\nLentech, Inc. is currently seekinga Risk Manager inGreenbelt,"}'
>>> import json
>>> json.loads(final_msg)
{'Description': "<strong>Risk Manager </strong><br />\\n<br />\\nLentech, Inc. is currently seekinga Risk Manager inGreenbelt,'", 'Title': 'Risk Manager', "b'PUID": '9279565'}
</code>```

Its a bad way of doing what is required, I would like to know a more optimized way of achieving the result. I think regex can be helpful here but I have a very limited knowledge of regular expressions.

Thanks in advance

答:
There you go:</p>

```<code>import re
final_msg = re.search("{.*}", msg).group(0)
</code>```

Body:
I have a string like this

msg = b'@\x06string\x083http://schemas.microsoft.com/2003/10/Serialization/\x9a\x05\x18{"PUID":"9279565","Title":"Risk Manager","Description":"Risk Manager
\\n
\\nLentech, Inc. is currently seekinga Risk Manager inGreenbelt,"}\x01'

The string {"PUID":"9279565","Title":"Risk Manager","Description":"Risk Manager
\\n
\\nLentech, Inc. is currently seekinga Risk Manager inGreenbelt,"} is json parsable. So I come up with the following code to remove garbage strings from the above msg

x1 =  msg.split(b'{"',1)[1]
>>>
>>> x1
b'PUID":"9279565","Title":"Risk Manager","Description":"Risk Manager
\\n
\\nLentech, Inc. is currently seekinga Risk Manager inGreenbelt,"}\x01'
x2 = x1[::-1].split(b'}"', 1)[1][::-1]
>>> x2
b'PUID":"9279565","Title":"Risk Manager","Description":"Risk Manager
\\n
\\nLentech, Inc. is currently seekinga Risk Manager inGreenbelt,'
>>> final_msg = b'{"%s"}'%x2
>>> final_msg
b'{"PUID":"9279565","Title":"Risk Manager","Description":"Risk Manager
\\n
\\nLentech, Inc. is currently seekinga Risk Manager inGreenbelt,"}'
>>> import json
>>> json.loads(final_msg)
{'Description': "Risk Manager
\\n
\\nLentech, Inc. is currently seekinga Risk Manager inGreenbelt,'", 'Title': 'Risk Manager', "b'PUID": '9279565'}

Its a bad way of doing what is required, I would like to know a more optimized way of achieving the result. I think regex can be helpful here but I have a very limited knowledge of regular expressions.

Thanks in advance

Body:
There you go:

import re
final_msg = re.search("{.*}", msg).group(0)


问:
VS Code integrated terminal shows path twice
Snapshot of the problem described in Title

After the latest update of VS Code today, I noticed this strange behavior.
I have iTerm2 and zsh installed. iTerm2 is working fine. Only in integrated terminal of VS Code, this issue is there.

UPDATE : This issue has been opened on github.
https://github.com/Microsoft/vscode/issues/28359

答:
This was a VSCode bug which should be fixed in VSCode 1.13.1

Here is the original bug tracking the issue: https://github.com/Microsoft/vscode/issues/26038


问:
How can I access a GET request in CAKEPHP?
How can I access a GET request in CAKEPHP ?

If I am passing a variable in the url

```<code>http://samplesite.com/page?key1=value1&key2=value2
</code>```

Should I use $_GET or $this->params to get the values in controller?
What is the standard in CAKEPHP ?

答:
You can do this only to get URL params,</p>

```<code>$this->request->pass;  //Array of all parameters in URL
</code>```

Body:
How can I access a GET request in CAKEPHP ?

If I am passing a variable in the url

http://samplesite.com/page?key1=value1&key2=value2

Should I use $_GET or $this->params to get the values in controller?
What is the standard in CAKEPHP ?

Body:
You can do this only to get URL params,

$this->request->pass;  //Array of all parameters in URL


问:
Android app is not running on other device
i just made a simple android app with 6 buttons. Each button on click opens a new activity. I installed the app on my device via USB cable from Android studio and it runs fine on my device.

But here rises the problem, when I installed the app on my friends device after sharing via SHAREit the app installed on his device but did not run.

What could be the reason for this? And how can I solve this?

Please help. Thank you

答:
Make sure instance run in android studio is disabled.

Because if Instance run is enabled when you debug the app on real device through usb debugging it will work properly . but if u share the apk from your device to other device it will not work. It might show an error . App Name Unfortunately Stoped.

If Instance run is enable. you must disable the instance run first. If you don't know how to disable it just google it. After disable the instance run, you must clean project and Build new apk. It will work on all the other devices without generating signed apk.

Hope it may help you.


问:
My login script doesn't properly query the database
Whenever I login with a registered user my script fails with the following message:

Warning: mysqli_query() expects at least 2 parameters, 1 given in C:\xampp\htdocs\login\login.php on line 9

  Notice: Undefined variable: sql in C:\xampp\htdocs\login\login.php on line 10

  Warning: mysqli_query() expects at least 2 parameters, 1 given

The script should query the database to see if the user is valid, but it never comes that far. The actual code is listed below.

connect.php

```<code><?php
    mysqli_connect ("localhost","root", "");
    $db = mysqli_select_db("login");
?>
</code>```

login.php

```<code><?php
    error_reporting(E_ALL);
    ini_set('display_errors', 1);

    require_once('connect.php');
    extract($_POST);

    $result = mysqli_query("select * from users where username = '$username' and password = '$password'");
    $result = mysqli_query( $sql);

    if ( $password == $row['password']) {
        header("location : home.php");
    }
    else {
        echo "failed to login! try again";
    }
?>

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Login page</title>
        <link href="style.css" type="text/css" rel="stylesheet">
    </head>
    <body>
        <div id="frm">
            <form action="login.php" method="POST" style="width: 232px; padding-left: 490px;">
                <h1>Login</h1>

                <p>
                    <label>Username</label>
                    <input type="text" id="username" name="username"/>
                </p>

                <p>
                    <label>password</label>
                    <input type="password" id="password" name="password"/>
                </p>

                <p>
                    <input type="submit" id="btn" value="login" style="border-radius: 30%; background-color: gold; box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24), 0 17px 50px 0 rgba(0,0,0,0.19);"/>
                </p>

                <p>
                    Not yet a member <a href="register.php">Register here</a>
                </p>
            </form>
        </div>
    </body>
</html>
</code>```

答:
Aside from the points that you should use PDO, prepared statements and generally never using variables directly from user input, there are a few things that needs attention:

connect.php

mysqli_connect can connect directly to the database, no need for mysqli_select_db

you should check if a connection was actually established

mysqli_select_db returns true or false, so storing that in $db only serves to know if the database was successfully selected

if you actually need a separate database and not just a table for the login, you should select the login database from login.php

when there nothing after the closing PHP tag it should be omitted, as this can only lead to confusing and hard-to-track-down bugs

login.php

extract puts everything into variables, potentially overwriting existing variables such as $db and $sql

using uppercase for SQL keywords makes the queries much more readable in terms of what is structure and what is names and data

$result is immediately overwritten after the first mysqli_query call

the second mysqli_query call runs the query in the undefined variable $sql and thus it fails

comparing $password to $row['password'] will never be true, as you store the query results in the $result variable but check the undefined $row variable

after setting the location header on successful login, you might as well stop the script, i.e. by adding exit(0);

on login failure, you should set a variable for use in the HTML output instead of outputting "failed to login! try again" in front of the markup for the login page

there should never be any characters between the closing PHP tag and the start of the HTML output, as this can only lead to confusing and hard-to-track-down bugs

Cleaning the code a bit according to the above will result in something like this:

connect.php

```<code><?php
    $db = mysqli_connect("localhost", "root", "", "login");

    if (!$db) {
        echo "Error: Unable to connect to MySQL." . PHP_EOL;
        echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
        echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
        exit;
    }
</code>```

login.php

```<code><?php
    error_reporting(E_ALL);
    ini_set('display_errors', 1);

    require_once('connect.php');

    $username = mysqli_real_escape_string($db, $_POST['username']);
    $password = mysqli_real_escape_string($db, $_POST['password']);

    $result = mysqli_query($db, "SELECT * FROM users WHERE username = '$username' AND password = '$password'");
    $row = mysqli_fetch_assoc($result);

    if ($password == $row['password']) {
        header("location: home.php");
        exit(0);
    }
    else {
        $feedback = "failed to login! try again";
    }
?><!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Login page</title>
        <link href="style.css" type="text/css" rel="stylesheet">
    </head>
    <body>
        <div id="frm">
            <form action="login.php" method="POST" style="width: 232px; padding-left: 490px;">
                <h1>Login</h1>

                <?php
                    if ($feedback) {
                        echo "<p>" . $feedback . "</p>";
                    }
                ?>

                <p>
                    <label>Username</label>
                    <input type="text" id="username" name="username"/>
                </p>

                <p>
                    <label>password</label>
                    <input type="password" id="password" name="password"/>
                </p>

                <p>
                    <input type="submit" id="btn" value="login" style="border-radius: 30%; background-color: gold; box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24), 0 17px 50px 0 rgba(0,0,0,0.19);"/>
                </p>

                <p>
                    Not yet a member <a href="register.php">Register here</a>
                </p>
            </form>
        </div>
    </body>
</html>
</code>```

Body:
Whenever I login with a registered user my script fails with the following message:

Warning: mysqli_query() expects at least 2 parameters, 1 given in C:\xampp\htdocs\login\login.php on line 9

  Notice: Undefined variable: sql in C:\xampp\htdocs\login\login.php on line 10

  Warning: mysqli_query() expects at least 2 parameters, 1 given

The script should query the database to see if the user is valid, but it never comes that far. The actual code is listed below.

connect.php

<?php
    mysqli_connect ("localhost","root", "");
    $db = mysqli_select_db("login");
?>

login.php

<?php
    error_reporting(E_ALL);
    ini_set('display_errors', 1);

    require_once('connect.php');
    extract($_POST);

    $result = mysqli_query("select * from users where username = '$username' and password = '$password'");
    $result = mysqli_query( $sql);

    if ( $password == $row['password']) {
        header("location : home.php");
    }
    else {
        echo "failed to login! try again";
    }
?>

<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Login page</title>
        <link href="style.css" type="text/css" rel="stylesheet">

            <form action="login.php" method="POST" style="width: 232px; padding-left: 490px;">

Login

                    Username
                    <input type="text" id="username" name="username"/>

                    password
                    <input type="password" id="password" name="password"/>

                    <input type="submit" id="btn" value="login" style="border-radius: 30%; background-color: gold; box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24), 0 17px 50px 0 rgba(0,0,0,0.19);"/>

                    Not yet a member Register here

            </form>

Body:
Aside from the points that you should use PDO, prepared statements and generally never using variables directly from user input, there are a few things that needs attention:

connect.php

mysqli_connect can connect directly to the database, no need for mysqli_select_db

you should check if a connection was actually established

mysqli_select_db returns true or false, so storing that in $db only serves to know if the database was successfully selected

if you actually need a separate database and not just a table for the login, you should select the login database from login.php

when there nothing after the closing PHP tag it should be omitted, as this can only lead to confusing and hard-to-track-down bugs

login.php

extract puts everything into variables, potentially overwriting existing variables such as $db and $sql

using uppercase for SQL keywords makes the queries much more readable in terms of what is structure and what is names and data

$result is immediately overwritten after the first mysqli_query call

the second mysqli_query call runs the query in the undefined variable $sql and thus it fails

comparing $password to $row['password'] will never be true, as you store the query results in the $result variable but check the undefined $row variable

after setting the location header on successful login, you might as well stop the script, i.e. by adding exit(0);

on login failure, you should set a variable for use in the HTML output instead of outputting "failed to login! try again" in front of the markup for the login page

there should never be any characters between the closing PHP tag and the start of the HTML output, as this can only lead to confusing and hard-to-track-down bugs

Cleaning the code a bit according to the above will result in something like this:

connect.php

<?php
    $db = mysqli_connect("localhost", "root", "", "login");

    if (!$db) {
        echo "Error: Unable to connect to MySQL." . PHP_EOL;
        echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
        echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
        exit;
    }

login.php

<?php
    error_reporting(E_ALL);
    ini_set('display_errors', 1);

    require_once('connect.php');

    $username = mysqli_real_escape_string($db, $_POST['username']);
    $password = mysqli_real_escape_string($db, $_POST['password']);

    $result = mysqli_query($db, "SELECT * FROM users WHERE username = '$username' AND password = '$password'");
    $row = mysqli_fetch_assoc($result);

    if ($password == $row['password']) {
        header("location: home.php");
        exit(0);
    }
    else {
        $feedback = "failed to login! try again";
    }
?><!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Login page</title>
        <link href="style.css" type="text/css" rel="stylesheet">
    </head>
    <body>
        <div id="frm">
            <form action="login.php" method="POST" style="width: 232px; padding-left: 490px;">
                <h1>Login</h1>

                <?php
                    if ($feedback) {
                        echo "<p>" . $feedback . "</p>";
                    }
                ?>

                <p>
                    <label>Username</label>
                    <input type="text" id="username" name="username"/>
                </p>

                <p>
                    <label>password</label>
                    <input type="password" id="password" name="password"/>
                </p>

                <p>
                    <input type="submit" id="btn" value="login" style="border-radius: 30%; background-color: gold; box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24), 0 17px 50px 0 rgba(0,0,0,0.19);"/>
                </p>

                <p>
                    Not yet a member <a href="register.php">Register here</a>
                </p>
            </form>
        </div>
    </body>
</html>


问:
How to use *ngIf for async http.get data request - Angular 2
I have a web application that is retrieving data from multiple api and is supposed to use the data into some charts. The problem is that when the charts get rendered the data from the api are not in yet. I tried using .then() method but it tells me that property then does not exist on type void. Furthermore I tried using the ngIf method, following this answer, but is not working either. Do you know how could I solve this please?

Below are my component and my component template.

app.component.ts

```<code>import { Component } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/Rx';

import * as moment from 'moment';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Mimesi dashboard graphs';

  //COUNTS
  public countIndexerMetaApi; //array of one number populated from http.get
  public countIndexerMetaNumber; //number extracted into array and stored as an int
  public countIndexerMetaArray; //array to store countNumber afterwards

  public countIndexerServedApi;
  public countIndexerServedNumber;
  public countIndexerServedArray;

  public countRealTimeServedApi;
  public countRealTimeServedNumber;
  public countRealTimeServedArray;

  //DATES
  public dateIndexerMetaToStore; //date got from moment method that needs to be stored
  public dateIndexerMetaArray; //array to store dates for graph label

  public dateIndexerServedToStore;
  public dateIndexerServedArray;

  public dateRealTimeServedToStore;
  public dateRealTimeServedArray;

  //API LINKS
  private apiCountIndexerMetaUrl: string = 'http://localhost:3000/api/countIndexerMetaApi';
  /*      TODO - API FOR COUNT OF OTHER TWO TABLES      */
  private apiCountIndexerServedUrl: string = 'http://localhost:3000/api/countIndexerServedApi';
  private apiCountRealTimeServedUrl: string = 'http://localhost:3000/api/countRealTimeServedApi';

  //VARIABLE FOR TIMEOUT
  public isDataAvailable:boolean = false;

  constructor(private http:Http) {
    let now = moment.locale("it");

    //COUNT
    this.countIndexerMetaApi = 0;
    this.countIndexerMetaNumber = 0;
    this.countIndexerMetaArray = [];

    this.countIndexerServedApi = 0;
    this.countIndexerServedNumber = 0;
    this.countIndexerServedArray = []

    this.countRealTimeServedApi = 0;
    this.countRealTimeServedNumber = 0;
    this.countRealTimeServedArray = []

    //DATES
    this.dateIndexerMetaToStore = "";
    this.dateIndexerMetaArray = [];

    this.dateIndexerServedToStore = "";
    this.dateIndexerServedArray = [];

    this.dateRealTimeServedToStore = "";
    this.dateRealTimeServedArray = [];
  }

  ngOnInit() {
    this.getIndexerMetaCount();
    this.getIndexerServedCount();
    this.getRealTimeServedCount();
  }

  //COUNT
  getIndexerMetaCount(){
    this.http.get(this.apiCountIndexerMetaUrl)
        .map((res: Response) => res.json())
        .subscribe(
            data => {
                console.log(this.countIndexerMetaApi = data.map(countIndexerMetaApiObj => countIndexerMetaApiObj.countIndexerMetaApi))
            },
        );
    //this.countIndexerMetaNumber = this.countIndexerMetaApi[0]; //<-- timing problem since this.count is not yet got from http.get() so it seems undefined
    //this.countIndexerMetaArray.push(this.countIndexerMetaNumber); // problem follows through
  }
  printCountIndexerMetaArray(){
    this.countIndexerMetaApi.forEach(element => {
      console.log(element);
    });
  }

  getIndexerServedCount(){
    this.http.get(this.apiCountIndexerServedUrl)
        .map((res: Response) => res.json())
        .subscribe(
            data => {
                console.log(this.countIndexerServedApi = data.map(countObj => countObj.countIndexerServedApi))
            },
        );
    //this.countIndexerServedNumber = this.countIndexerServedApi[0]; //<-- timing problem since this.count is not yet got from http.get() so it seems undefined
    //this.countIndexerServedArray.push(this.countIndexerServedNumber); // problem follows through
  }
  printCountIndexerServedArray(){
    this.countIndexerServedApi.forEach(element => {
      console.log(element);
    });
  }

  getRealTimeServedCount(){
    this.http.get(this.apiCountRealTimeServedUrl)
        .map((res: Response) => res.json())
        .subscribe(
            data => {
                console.log(this.countRealTimeServedApi = data.map(countObj => countObj.countRealTimeServedApi))
            },
        );
    //this.countRealTimeServedNumber = this.countRealTimeServedApi[0]; //<-- timing problem since this.count is not yet got from http.get() so it seems undefined
    //this.countRealTimeServedArray.push(this.countRealTimeServedNumber); // problem follows through
  }
  printRealTimeServedArray(){
    this.countRealTimeServedApi.forEach(element => {
      console.log(element);
    });
  }

  //DATES
  dateIndexerMeta() {
    this.dateIndexerMetaToStore = moment().add(-122, 'days');
    this.dateIndexerMetaArray.push(this.dateIndexerMetaToStore);
  }

  dateIndexerServed() {
    this.dateIndexerServedToStore = moment().add(-122, 'days');
    this.dateIndexerServedArray.push(this.dateIndexerServedToStore);
  }

  dateRealTimeServed() {
    this.dateRealTimeServedToStore = moment().add(-122, 'days');
    this.dateRealTimeServedArray.push(this.dateRealTimeServedToStore);
  }

  //TIMEOUT TRIAL
  timeoutTrial(){
    console.log(this.isDataAvailable);
    setTimeout(function() {this.isDataAvailable = true;
      console.log(this.isDataAvailable);
    }, 5000); //<-- timeout works but other functions don't refresh even if isDataAvailable changed
  }

  /*      CHARTS      */

  //DATA
  public lineChartData:Array<any> = [
    {data: this.countIndexerMetaArray, label: 'Indexer meta served links'},
  ];

  public lineChartData1:Array<any> = [
    {data: this.countIndexerServedArray, label: 'Indexer served links'},
  ];

  public lineChartData2:Array<any> = [
    {data: this.countRealTimeServedArray, label: 'Real-Time served links'},
  ];

  //LABELS
  public lineChartLabels:Array<any> = this.dateIndexerMetaArray;

  public lineChartLabels1:Array<any> = this.dateIndexerServedArray;

  public lineChartLabels2:Array<any> = this.dateRealTimeServedArray;

  //OPTIONS
  public lineChartOptions:any = {
    responsive: true,

    scales: {
      xAxes: [{
        type: 'time',
        time: {
          displayFormats: {
            'millisecond': 'DD MMM',
            'second': 'DD MMM',
            'minute': 'DD MMM',
            'hour': 'DD MMM',
            'day': 'DD MMM',
            'week': 'DD MMM',
            'month': 'DD MMM',
            'quarter': 'DD MMM',
            'year': 'DD MMM',
          }
        }
      }],
    },

  };

  public lineChartLegend:boolean = true;
  public lineChartType:string = 'line';

  //COLORS
  public lineChartColors:Array<any> = [
    { // grey
      backgroundColor: 'rgba(255,55,55,0.2)',
      borderColor: 'rgba(255,55,55,1)',
      pointBackgroundColor: 'rgba(255,55,55,1)',
      pointBorderColor: '#fff',
      pointHoverBackgroundColor: '#fff',
      pointHoverBorderColor: 'rgba(255,55,55,0.8)'
    },
  ];

  //EVENTS
  public chartClicked(e:any):void {
    console.log(e);
  }

  public chartHovered(e:any):void {
    console.log(e);
  }
}
</code>```

app.component.html

```<code><div class="container">

<div class="front-end-app">
    <ul>
      <h3>Count Indexer Meta:</h3>
      <li *ngFor="let countIndexerMetaNumber of countIndexerMetaApi">
        {{countIndexerMetaNumber}}
      </li>
      <h3>Count Indexer Served:</h3>
      <li *ngFor="let countIndexerServedNumber of countIndexerServedApi">
        {{countIndexerServedNumber}}
      </li>
      <h3>Count Real Time Served:</h3>
      <li *ngFor="let countRealTimeServedNumber of countRealTimeServedApi">
        {{countRealTimeServedNumber}}
      </li>
    </ul>
    <hr>

    <div class="head">
      <h1>{{title}}</h1>
    </div>
    <hr>
    <div class="row">
      <div class="col-md-6">
        <div class="card">
          <div class="card-block">
            <canvas baseChart width="600" height="400"
                  [datasets]="lineChartData"
                  [labels]="lineChartLabels"
                  [options]="lineChartOptions"
                  [colors]="lineChartColors"
                  [legend]="lineChartLegend"
                  [chartType]="lineChartType"
                  (chartHover)="chartHovered($event)"
                  (chartClick)="chartClicked($event)"></canvas>
          </div>
        </div>
      </div>
      <div class="col-md-6">
        <div class="card">
          <div class="card-block">
            <canvas baseChart width="600" height="400"
                    [datasets]="lineChartData1"
                    [labels]="lineChartLabels1"
                    [options]="lineChartOptions"
                    [colors]="lineChartColors"
                    [legend]="lineChartLegend"
                    [chartType]="lineChartType"
                    (chartHover)="chartHovered($event)"
                    (chartClick)="chartClicked($event)"></canvas>
          </div>
        </div>
      </div>
      <div class="col-md-6 offset-md-3">
        <div class="card">
          <div class="card-block">
            <canvas baseChart width="600" height="400"
                    [datasets]="lineChartData2"
                    [labels]="lineChartLabels2"
                    [options]="lineChartOptions"
                    [colors]="lineChartColors"
                    [legend]="lineChartLegend"
                    [chartType]="lineChartType"
                    (chartHover)="chartHovered($event)"
                    (chartClick)="chartClicked($event)"></canvas>
          </div>
        </div>
      </div>
    </div>
  </div>
  <button type="button" class="btn btn-primary" (click)="printCountIndexerMetaArray()"> Click to print count indexer meta array</button>
  <button type="button" class="btn btn-primary" (click)="printCountIndexerServedArray()"> Click to print count indexer served array</button>
  <button type="button" class="btn btn-primary" (click)="printRealTimeServedArray()"> Click to print count real time served array</button>
</div>
</code>```

For any question or further explanation just comment and I'll answer straight away. Thanks!

答:
U forget  implements OnInit [https://angular.io/guide/lifecycle-hooks][1]

```<code>export class AppComponent implements OnInit{
</code>```

Try use Resolver for this component
[https://angular.io/api/router/Resolve][2]

Body:
I have a web application that is retrieving data from multiple api and is supposed to use the data into some charts. The problem is that when the charts get rendered the data from the api are not in yet. I tried using .then() method but it tells me that property then does not exist on type void. Furthermore I tried using the ngIf method, following this answer, but is not working either. Do you know how could I solve this please?

Below are my component and my component template.

app.component.ts

import { Component } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/Rx';

import * as moment from 'moment';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Mimesi dashboard graphs';

  //COUNTS
  public countIndexerMetaApi; //array of one number populated from http.get
  public countIndexerMetaNumber; //number extracted into array and stored as an int
  public countIndexerMetaArray; //array to store countNumber afterwards

  public countIndexerServedApi;
  public countIndexerServedNumber;
  public countIndexerServedArray;

  public countRealTimeServedApi;
  public countRealTimeServedNumber;
  public countRealTimeServedArray;

  //DATES
  public dateIndexerMetaToStore; //date got from moment method that needs to be stored
  public dateIndexerMetaArray; //array to store dates for graph label

  public dateIndexerServedToStore;
  public dateIndexerServedArray;

  public dateRealTimeServedToStore;
  public dateRealTimeServedArray;

  //API LINKS
  private apiCountIndexerMetaUrl: string = 'http://localhost:3000/api/countIndexerMetaApi';
  /*      TODO - API FOR COUNT OF OTHER TWO TABLES      */
  private apiCountIndexerServedUrl: string = 'http://localhost:3000/api/countIndexerServedApi';
  private apiCountRealTimeServedUrl: string = 'http://localhost:3000/api/countRealTimeServedApi';

  //VARIABLE FOR TIMEOUT
  public isDataAvailable:boolean = false;

  constructor(private http:Http) {
    let now = moment.locale("it");

    //COUNT
    this.countIndexerMetaApi = 0;
    this.countIndexerMetaNumber = 0;
    this.countIndexerMetaArray = [];

    this.countIndexerServedApi = 0;
    this.countIndexerServedNumber = 0;
    this.countIndexerServedArray = []

    this.countRealTimeServedApi = 0;
    this.countRealTimeServedNumber = 0;
    this.countRealTimeServedArray = []

    //DATES
    this.dateIndexerMetaToStore = "";
    this.dateIndexerMetaArray = [];

    this.dateIndexerServedToStore = "";
    this.dateIndexerServedArray = [];

    this.dateRealTimeServedToStore = "";
    this.dateRealTimeServedArray = [];
  }

  ngOnInit() {
    this.getIndexerMetaCount();
    this.getIndexerServedCount();
    this.getRealTimeServedCount();
  }

  //COUNT
  getIndexerMetaCount(){
    this.http.get(this.apiCountIndexerMetaUrl)
        .map((res: Response) => res.json())
        .subscribe(
            data => {
                console.log(this.countIndexerMetaApi = data.map(countIndexerMetaApiObj => countIndexerMetaApiObj.countIndexerMetaApi))
            },
        );
    //this.countIndexerMetaNumber = this.countIndexerMetaApi[0]; //<-- timing problem since this.count is not yet got from http.get() so it seems undefined
    //this.countIndexerMetaArray.push(this.countIndexerMetaNumber); // problem follows through
  }
  printCountIndexerMetaArray(){
    this.countIndexerMetaApi.forEach(element => {
      console.log(element);
    });
  }

  getIndexerServedCount(){
    this.http.get(this.apiCountIndexerServedUrl)
        .map((res: Response) => res.json())
        .subscribe(
            data => {
                console.log(this.countIndexerServedApi = data.map(countObj => countObj.countIndexerServedApi))
            },
        );
    //this.countIndexerServedNumber = this.countIndexerServedApi[0]; //<-- timing problem since this.count is not yet got from http.get() so it seems undefined
    //this.countIndexerServedArray.push(this.countIndexerServedNumber); // problem follows through
  }
  printCountIndexerServedArray(){
    this.countIndexerServedApi.forEach(element => {
      console.log(element);
    });
  }

  getRealTimeServedCount(){
    this.http.get(this.apiCountRealTimeServedUrl)
        .map((res: Response) => res.json())
        .subscribe(
            data => {
                console.log(this.countRealTimeServedApi = data.map(countObj => countObj.countRealTimeServedApi))
            },
        );
    //this.countRealTimeServedNumber = this.countRealTimeServedApi[0]; //<-- timing problem since this.count is not yet got from http.get() so it seems undefined
    //this.countRealTimeServedArray.push(this.countRealTimeServedNumber); // problem follows through
  }
  printRealTimeServedArray(){
    this.countRealTimeServedApi.forEach(element => {
      console.log(element);
    });
  }

  //DATES
  dateIndexerMeta() {
    this.dateIndexerMetaToStore = moment().add(-122, 'days');
    this.dateIndexerMetaArray.push(this.dateIndexerMetaToStore);
  }

  dateIndexerServed() {
    this.dateIndexerServedToStore = moment().add(-122, 'days');
    this.dateIndexerServedArray.push(this.dateIndexerServedToStore);
  }

  dateRealTimeServed() {
    this.dateRealTimeServedToStore = moment().add(-122, 'days');
    this.dateRealTimeServedArray.push(this.dateRealTimeServedToStore);
  }

  //TIMEOUT TRIAL
  timeoutTrial(){
    console.log(this.isDataAvailable);
    setTimeout(function() {this.isDataAvailable = true;
      console.log(this.isDataAvailable);
    }, 5000); //<-- timeout works but other functions don't refresh even if isDataAvailable changed
  }

  /*      CHARTS      */

  //DATA
  public lineChartData:Array<any> = [
    {data: this.countIndexerMetaArray, label: 'Indexer meta served links'},
  ];

  public lineChartData1:Array<any> = [
    {data: this.countIndexerServedArray, label: 'Indexer served links'},
  ];

  public lineChartData2:Array<any> = [
    {data: this.countRealTimeServedArray, label: 'Real-Time served links'},
  ];

  //LABELS
  public lineChartLabels:Array<any> = this.dateIndexerMetaArray;

  public lineChartLabels1:Array<any> = this.dateIndexerServedArray;

  public lineChartLabels2:Array<any> = this.dateRealTimeServedArray;

  //OPTIONS
  public lineChartOptions:any = {
    responsive: true,

    scales: {
      xAxes: [{
        type: 'time',
        time: {
          displayFormats: {
            'millisecond': 'DD MMM',
            'second': 'DD MMM',
            'minute': 'DD MMM',
            'hour': 'DD MMM',
            'day': 'DD MMM',
            'week': 'DD MMM',
            'month': 'DD MMM',
            'quarter': 'DD MMM',
            'year': 'DD MMM',
          }
        }
      }],
    },

  };

  public lineChartLegend:boolean = true;
  public lineChartType:string = 'line';

  //COLORS
  public lineChartColors:Array<any> = [
    { // grey
      backgroundColor: 'rgba(255,55,55,0.2)',
      borderColor: 'rgba(255,55,55,1)',
      pointBackgroundColor: 'rgba(255,55,55,1)',
      pointBorderColor: '#fff',
      pointHoverBackgroundColor: '#fff',
      pointHoverBorderColor: 'rgba(255,55,55,0.8)'
    },
  ];

  //EVENTS
  public chartClicked(e:any):void {
    console.log(e);
  }

  public chartHovered(e:any):void {
    console.log(e);
  }
}

app.component.html

Count Indexer Meta:

        {{countIndexerMetaNumber}}

Count Indexer Served:

        {{countIndexerServedNumber}}

Count Real Time Served:

        {{countRealTimeServedNumber}}

{{title}}

            <canvas baseChart width="600" height="400"
                  [datasets]="lineChartData"
                  [labels]="lineChartLabels"
                  [options]="lineChartOptions"
                  [colors]="lineChartColors"
                  [legend]="lineChartLegend"
                  [chartType]="lineChartType"
                  (chartHover)="chartHovered($event)"
                  (chartClick)="chartClicked($event)"></canvas>

            <canvas baseChart width="600" height="400"
                    [datasets]="lineChartData1"
                    [labels]="lineChartLabels1"
                    [options]="lineChartOptions"
                    [colors]="lineChartColors"
                    [legend]="lineChartLegend"
                    [chartType]="lineChartType"
                    (chartHover)="chartHovered($event)"
                    (chartClick)="chartClicked($event)"></canvas>

            <canvas baseChart width="600" height="400"
                    [datasets]="lineChartData2"
                    [labels]="lineChartLabels2"
                    [options]="lineChartOptions"
                    [colors]="lineChartColors"
                    [legend]="lineChartLegend"
                    [chartType]="lineChartType"
                    (chartHover)="chartHovered($event)"
                    (chartClick)="chartClicked($event)"></canvas>

  <button type="button" class="btn btn-primary" (click)="printCountIndexerMetaArray()"> Click to print count indexer meta array</button>
  <button type="button" class="btn btn-primary" (click)="printCountIndexerServedArray()"> Click to print count indexer served array</button>
  <button type="button" class="btn btn-primary" (click)="printRealTimeServedArray()"> Click to print count real time served array</button>

For any question or further explanation just comment and I'll answer straight away. Thanks!

Body:
U forget  implements OnInit [https://angular.io/guide/lifecycle-hooks][1]

export class AppComponent implements OnInit{

Try use Resolver for this component
[https://angular.io/api/router/Resolve][2]


问:
Android Sqlite Query syntax query error.Help need
Pls check my syntax and correct me..

Am getting error
 Caused by: android.database.sqlite.SQLiteException: near "BETWEEN30": syntax error (code 1): , while compiling: SELECT * FROM TABLE_ITEMS WHERE date BETWEEN30/06/2017'AND'07/07/2017'

```<code> String query = " SELECT * FROM " + TABLE + " WHERE date BETWEEN" + past_date + "'AND'" + current_date + "' " ;
</code>```

答:
A SQLite exception that indicates there was an error with SQL parsing
  or execution.

Rectify your Statement using BLANK SPACE & Single-Double Character .

```<code>String query = " SELECT * FROM " + TABLE_ITEMS + " WHERE date BETWEEN " + past_date + " AND " + current_date + "  ;
</code>```

You can try with

```<code> "SELECT * FROM " + TABLE_NAME+ " WHERE  date "+ BETWEEN past_date('"+DATE_STR_FORMAT+"') + " AND current_date " ('"+DATE_STR_FORMAT_CURRENT+"')"";
</code>```

Body:
Pls check my syntax and correct me..

Am getting error
 Caused by: android.database.sqlite.SQLiteException: near "BETWEEN30": syntax error (code 1): , while compiling: SELECT * FROM TABLE_ITEMS WHERE date BETWEEN30/06/2017'AND'07/07/2017'

 String query = " SELECT * FROM " + TABLE + " WHERE date BETWEEN" + past_date + "'AND'" + current_date + "' " ;

Body:
A SQLite exception that indicates there was an error with SQL parsing
  or execution.

Rectify your Statement using BLANK SPACE & Single-Double Character .

String query = " SELECT * FROM " + TABLE_ITEMS + " WHERE date BETWEEN " + past_date + " AND " + current_date + "  ;

You can try with

 "SELECT * FROM " + TABLE_NAME+ " WHERE  date "+ BETWEEN past_date('"+DATE_STR_FORMAT+"') + " AND current_date " ('"+DATE_STR_FORMAT_CURRENT+"')"";


问:
ASP MVC3 with razor running on Azure
I would like to create a simple ASP MVC3 web applications for learning and have this hosted. I am familiar with ASP MVC but don't yet know much about the Azure cloud. If possible I would like to have these hosted on the cloud but I'm not sure where to start.

Can anyone give me any advice. For example for something very very low usage and making use of a SQL CE database what kind of azure account do I need and approximately how much would it cost.

Thanks in advance for your help.

答:
For ASP.NET MVC 3 the thing to do is "bin deploy" it - Scott Hanselman has a post on doing exactly that on his blog:
http://www.hanselman.com/blog/BINDeployingASPNETMVC3WithRazorToAWindowsServerWithoutMVCInstalled.aspx

I recommend you download the Windows Azure platform training kit and work through the first few labs just to get the feel of Azure.
http://www.microsoft.com/downloads/en/details.aspx?FamilyID=413E88F8-5966-4A83-B309-53B7B77EDF78&displaylang=en

I agree with Nathan and XIII - you have to ditch SQL CE it just doesn't work in the elastic cloud model, look at Azure table storage instead, it's cheap and scalable. (And it's in the first lab)

If you're just playing around then grab the introductory offer on Nathan's link, it's a free start. Unfortunately you can't use it to run something permanently as there aren't enough hours. (Apparently that may change in the new year). If you want to run a very small instance for a month it's about $40, a small is $90.

If you're more serious than that, join Bizspark and get free access to more resources.

Title: ASP MVC3 with razor running on Azure


问:
Get or inject Lagom application context LagomApplicationContext
Exist any way to get LagomApplicationContext? I would like to use play configuration object play.api.Configuration form playContext - composition:

```<code>sealed trait LagomApplicationContext {
  /**
   * The Play application loader context.
   */
  val playContext: Context
}
</code>```

Any ideas or suggestion how to do it? Is Exist some DI?

I need to use values from application.conf the same like in this example:
https://www.webkj.com/play-framework/play-scala-2.5-reading-config-using-di

答:
Yes it is true - but only it is possible to inject in controller level:</p>

```<code>class OnlineDiscountTagImpl @Inject() (cache : CacheApi) extends Controller
</code>```

Body:
Exist any way to get LagomApplicationContext? I would like to use play configuration object play.api.Configuration form playContext - composition:

sealed trait LagomApplicationContext {
  /**
   * The Play application loader context.
   */
  val playContext: Context
}

Any ideas or suggestion how to do it? Is Exist some DI?

I need to use values from application.conf the same like in this example:
https://www.webkj.com/play-framework/play-scala-2.5-reading-config-using-di

Body:
Yes it is true - but only it is possible to inject in controller level:

class OnlineDiscountTagImpl @Inject() (cache : CacheApi) extends Controller


问:
How to pass form data from node server to extrenal server?
Here is my code. How to send my form data to external server? Can anyone solve my trouble?
Thanks in advance.</p>

```<code>var http = require('http');
var FormData = require('form-data');

var form = new FormData();

form.append('books', ['book1', 'book2']); // my form data

var options = {
  host: 'http://localhost',
  port: 8080,
  path: '/app/updateBooks',
  method: 'POST'
};

http.request(options, function(resp){
    console.log(resp);
}).on("error", function(err){
    console.log(err);
});
</code>```

答:
Request module can be used for sending data to external server:
https://www.npmjs.com/package/request

For example:

```<code>const request = require('request')
request({
    uri: 'https://www.example.com/',
    qs: { access_token: token },  // object containing querystring values to be appended to the uri
    method: 'POST',
    json: messageData //json - sets body to JSON representation of value and adds Content-type: application/json header

  }, function (error, response, body) {
    if (!error && response.statusCode == 200) {
        //success condition
    } else {
      // failure condition
    }
  })
</code>```

Body:
Here is my code. How to send my form data to external server? Can anyone solve my trouble?
Thanks in advance.

var http = require('http');
var FormData = require('form-data');

var form = new FormData();

form.append('books', ['book1', 'book2']); // my form data

var options = {
  host: 'http://localhost',
  port: 8080,
  path: '/app/updateBooks',
  method: 'POST'
};

http.request(options, function(resp){
    console.log(resp);
}).on("error", function(err){
    console.log(err);
});

Body:
Request module can be used for sending data to external server:
https://www.npmjs.com/package/request

For example:

const request = require('request')
request({
    uri: 'https://www.example.com/',
    qs: { access_token: token },  // object containing querystring values to be appended to the uri
    method: 'POST',
    json: messageData //json - sets body to JSON representation of value and adds Content-type: application/json header

  }, function (error, response, body) {
    if (!error && response.statusCode == 200) {
        //success condition
    } else {
      // failure condition
    }
  })


问:
Python - check if site is blacklisted by google
Is it possible to check if site is blacklisted by google using python? I tried:

```<code>    try:
            opener = requests.get(strona['url'], headers={
                'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) \
                AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 \
                Safari/537.36'
            })
            tekst_html = opener.text
</code>```

and search tekst_html for "You are entering the misleading page" or something like that. I realized there is no such phrases in html source. I think it is external script that shows warning.

This is an example of blacklisted site: http://www.forum.dietaproteinowa.eu/

答:
User agent doesn't control what browser displays, it controls what content site sends. Site is blocked by chrome, so chrome engine has to do the blocking. If it was controled by site server, it would be pretty ridiculous: "Hey, look this guy seems to be using chrome, but google said we are blacklisted so we better not send him content, and send that specific blocklisted webpage google gave us"

To check if such site is blacklisted in chrome you basically need to physically run chrome. Thankfully, python can do that for you using selenium module with chrome driver.

With selenium you need to run chrome driver, then request driver to open given site, after it is loaded you request source code that selenium received and check if  tag has blacklisted class.

If you do not want browser popping up you can use some selenium specific tricks. For example on linux, you can create virtual display in python and run chrome driver inside that virtual display.

Body:
Is it possible to check if site is blacklisted by google using python? I tried:

    try:
            opener = requests.get(strona['url'], headers={
                'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) \
                AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 \
                Safari/537.36'
            })
            tekst_html = opener.text

and search tekst_html for "You are entering the misleading page" or something like that. I realized there is no such phrases in html source. I think it is external script that shows warning.

This is an example of blacklisted site: http://www.forum.dietaproteinowa.eu/

Body:
User agent doesn't control what browser displays, it controls what content site sends. Site is blocked by chrome, so chrome engine has to do the blocking. If it was controled by site server, it would be pretty ridiculous: "Hey, look this guy seems to be using chrome, but google said we are blacklisted so we better not send him content, and send that specific blocklisted webpage google gave us"

To check if such site is blacklisted in chrome you basically need to physically run chrome. Thankfully, python can do that for you using selenium module with chrome driver.

With selenium you need to run chrome driver, then request driver to open given site, after it is loaded you request source code that selenium received and check if <html> tag has blacklisted class.

If you do not want browser popping up you can use some selenium specific tricks. For example on linux, you can create virtual display in python and run chrome driver inside that virtual display.


问:
How to resize images in org-mode
Is there a general way to define the size, in percent or pixels, for an image that is linked in org-mode?

Say I have the following link in my .org file:

```<code>[[~/images/example.jpg]]
</code>```

This JPG is way too large, so if I export it to HTML or LaTeX or open it in org-mode with C-c C-o i will only see a fraction of the image.

答:
For LaTeX, to remove the default width=.9\linewidth, set the org-latex-image-default-width to empty string. By this way, the image will have its natural size.

To do that on the fly use the set-variable emacs command. Or to set this variable permanently, add the following line in your init.el :
(setq org-latex-image-default-width "")

Title: How to resize images in org-mode

Body:
Is there a general way to define the size, in percent or pixels, for an image that is linked in org-mode?

Say I have the following link in my .org file:

[[~/images/example.jpg]]

This JPG is way too large, so if I export it to HTML or LaTeX or open it in org-mode with C-c C-o i will only see a fraction of the image.


问:
Bottom button bar in android
I am wondering how it's possible to create bottom bar buttons in android,

I read something about this U.I. solution, are there any controls that can be used?

答:
I create a simple AndroidBottomMenu View using custom view. It is simple and light, you can easy copy to your project

```<code><com.toong.androidbottombar.bottommenu.BottomMenu
    android:id="@+id/bottom_menu"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    />
</code>```

Title: Bottom button bar in android

Body:
I create a simple AndroidBottomMenu View using custom view. It is simple and light, you can easy copy to your project

<com.toong.androidbottombar.bottommenu.BottomMenu
    android:id="@+id/bottom_menu"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    />


问:
Python Google Vision python script syntax errors
I am having some issues using the cloudvisreq python script for the Google Vision Python API. I get this error when I run the code:

```<code>File "newvisreq.py", line 46
    api_key, *image_filenames = argv[1:]
             ^
SyntaxError: invalid syntax
</code>```

I am running the script through Python2.7, as it told me to in the tutorial I'm using to set this up. I found when I ran it through Python3 it was slightly more successful, as it managed to write as it was supposed to, but it received no data. The code can be found here, and the line the error complains about is about half way through the file (line 46).

Thanks in advance,

Connor

答:
This advanced form of iterable unpacking (PEP-3132), is only available from python-3.x (and further versions). You can however use the following code to make it equivalent:

```<code>api_key = argv[1]
image_filenames = argv[2:]
</code>```

In case argv is not a list (if it is imported from sys, it is a list), you can use:

```<code>api_key = argv[1]
image_filenames = <b>list(</b>argv[2:]<b>)</b></code>```

Body:
I am having some issues using the cloudvisreq python script for the Google Vision Python API. I get this error when I run the code:

File "newvisreq.py", line 46
    api_key, *image_filenames = argv[1:]
             ^
SyntaxError: invalid syntax

I am running the script through Python2.7, as it told me to in the tutorial I'm using to set this up. I found when I ran it through Python3 it was slightly more successful, as it managed to write as it was supposed to, but it received no data. The code can be found here, and the line the error complains about is about half way through the file (line 46).

Thanks in advance,

Connor

Body:
This advanced form of iterable unpacking (PEP-3132), is only available from python-3.x (and further versions). You can however use the following code to make it equivalent:

api_key = argv[1]
image_filenames = argv[2:]

In case argv is not a list (if it is imported from sys, it is a list), you can use:

api_key = argv[1]
image_filenames = list(argv[2:])


问:
Different between keyword "new" and "default" in create instance of class
I have class like:

```<code> class foo
    {
        public foo(string Text)
        {
        }
    }
</code>```

After run this code for create instance of class the obj1 set to null:

```<code>foo obj1 = default(foo);
</code>```

And by blow code everything work fine:

```<code>foo obj2= new foo("bla bla");
</code>```

I have 2 Question :

Whats happen to default contractor when run default(foo);?

Is foo obj1 = default(foo); equal the foo obj1 = null?

Thanks in advance.

答: According to documentation, default sets the variable to its default value. That means nullable types will be set to null, numeric types set to 0.</p>

Body:
I have class like:

 class foo
    {
        public foo(string Text)
        {
        }
    }

After run this code for create instance of class the obj1 set to null:

foo obj1 = default(foo);

And by blow code everything work fine:

foo obj2= new foo("bla bla");

I have 2 Question :

Whats happen to default contractor when run default(foo);?

Is foo obj1 = default(foo); equal the foo obj1 = null?

Thanks in advance.


问:
How to hit axios request from Jest test page
I am trying to hit an axios request from my code.test.js file here:

```<code>import axios from 'axios'
import sinon from 'sinon';

describe('get-data', () => {

let data = {start_date:"2017-06-30",end_date:"2017-07-07",graph:"all"}

let sandbox;
let server;
beforeEach(() => {
    sandbox = sinon.sandbox.create();
    server = sandbox.useFakeServer();
});
afterEach(() => {
    server.restore();
    sandbox.restore();
});

it('should display a blankslate', (done) => {
    axios.get('/api/get/data?data='+JSON.stringify(data))
        .then((response.data) => {
        console.log(response)
            /*expect($('#users').innerHTML)
            .to.equal('The list is empty.')*/ })
        .then(done, done);
    setTimeout(() => server.respond([200,
        { 'Content-Type': 'application/json' },
    '[]']), 0);
});
})
</code>```

But I get console.log(response.data) as undefined.

Can anyone tell me how to get data here in response ?

答:
Technically in your tests you shouldn't be actually doing a request, but rather mocking it and testing side effects.

However if I remember correctly jest mocks everything by default unless told not too. In your package.json add the following section and contents:

{
  "jest": {
    "unmockedModulePathPatterns": [
      "axios",
    ]
  }
}

This should allow you to do your actual network request as necessary in the test. You could also pass the "automock": true, property into the jest section if you wanted to disable automocking.

Documentation:

https://facebook.github.io/jest/docs/configuration.html#automock-boolean

https://facebook.github.io/jest/docs/configuration.html#unmockedmodulepathpatterns-array-string

Body:
I am trying to hit an axios request from my code.test.js file here:

import axios from 'axios'
import sinon from 'sinon';

describe('get-data', () => {

let data = {start_date:"2017-06-30",end_date:"2017-07-07",graph:"all"}

let sandbox;
let server;
beforeEach(() => {
    sandbox = sinon.sandbox.create();
    server = sandbox.useFakeServer();
});
afterEach(() => {
    server.restore();
    sandbox.restore();
});

it('should display a blankslate', (done) => {
    axios.get('/api/get/data?data='+JSON.stringify(data))
        .then((response.data) => {
        console.log(response)
            /*expect($('#users').innerHTML)
            .to.equal('The list is empty.')*/ })
        .then(done, done);
    setTimeout(() => server.respond([200,
        { 'Content-Type': 'application/json' },
    '[]']), 0);
});
})

But I get console.log(response.data) as undefined.

Can anyone tell me how to get data here in response ?