问:
how to pass key-value pair into a user-defined table type?
How do I pass a Dictionary or any other tuple type into a stored procedure?

The stored procedure is defined as:

```<code>CREATE PROCEDURE [dbo].[Components]
(
  @OrderTypeID INT = NULL,
  @OrderTypeKey VARCHAR(40) = NULL,
  @SegmentID INT = NULL,
  @SegmentKey VARCHAR(40) = NULL,
  @FilterPairs KeyValuePair READONLY
)
AS
BEGIN
..
</code>```

Where KeyValuePair is defined as:

This is how I am calling the sproc:

```<code>context.Database.SqlQuery<EntityType>(
    @"declare param1 int = --some logic
      declare param2 varchar = --some logic
      EXEC Components @param1=@param1,@param2=@param2"
);
</code>```

How do I pass a Dictionary or any other tuple type into a stored procedure for a user-defined table-type parameter?

Please note that I do not want to use SqlParameter for this implementation if possible.

答:
As you tag the question Entity Framework, I assume you have a DbContext.

This DbContext represents (the access to) your database. It has DbSets for all tables in the database. It knows the relations between the tables, and it should also know how to call the stored procedures.

After all, should a user of the dbContext need to do something very different when calling a stored procedure than when handling a table?

Therefore the call to your stored procedure ought to be a function in your DbCntext

```<code>class MyDbContext : DbContext
{
    public DbSet<...> Table1 {get; set;}
    public DbSet<...> Table2 {get; set;}

    #region stored procedures
    public void Components(int orderTypeId, string orderTypeKey, ...
         KeyValuePair<string, string> pair, ...)
    {
        // TODO: fill code
    }
}
</code>```

Change your stored procedure. @FilterPairs should be two parameters:

```<code>@FilterKey,
@FilterValue,
</code>```

Now it will be easy to implement procedure Components:

```<code>public void Components(int orderTypeId, string orderTypeKey, ...
    KeyValuePair<string, string> pair, ...)
{
    object[] functionParameters = new object[]
    {
        new SqlParameter(@"OrderTypeId", orderTypeId),
        new SqlParameter(@"OrderTypeKey", orderTypeKey),
        ...
        // The KeyValuePair: in your store procedure two parameters:
        new SqlParameter(@"FilterKey", pair.Key),
        new SqlParameter(@"FilterValue", pair.Value),
    };
    const string sqlCommans = @"Exec ...
        @OrderTypeId, @OrderTypeKey, ...
        @FilterKey, @FilterValue, ...";
    this.Database.ExecuteSqlCommand(sqlComman, functionParameters);
}
</code>```

You'll know what to do if you want a function that takes a Dictionary, or any other class that implements IEnumerable<KeyValuePair<string, string>>

Body:
How do I pass a Dictionary or any other tuple type into a stored procedure?

The stored procedure is defined as:

CREATE PROCEDURE [dbo].[Components]
(
  @OrderTypeID INT = NULL,
  @OrderTypeKey VARCHAR(40) = NULL,
  @SegmentID INT = NULL,
  @SegmentKey VARCHAR(40) = NULL,
  @FilterPairs KeyValuePair READONLY
)
AS
BEGIN
..

Where KeyValuePair is defined as:

This is how I am calling the sproc:

context.Database.SqlQuery<EntityType>(
    @"declare param1 int = --some logic
      declare param2 varchar = --some logic
      EXEC Components @param1=@param1,@param2=@param2"
);

How do I pass a Dictionary or any other tuple type into a stored procedure for a user-defined table-type parameter?

Please note that I do not want to use SqlParameter for this implementation if possible.

Body:
As you tag the question Entity Framework, I assume you have a DbContext.

This DbContext represents (the access to) your database. It has DbSets for all tables in the database. It knows the relations between the tables, and it should also know how to call the stored procedures.

After all, should a user of the dbContext need to do something very different when calling a stored procedure than when handling a table?

Therefore the call to your stored procedure ought to be a function in your DbCntext

class MyDbContext : DbContext
{
    public DbSet<...> Table1 {get; set;}
    public DbSet<...> Table2 {get; set;}

    #region stored procedures
    public void Components(int orderTypeId, string orderTypeKey, ...
         KeyValuePair<string, string> pair, ...)
    {
        // TODO: fill code
    }
}

Change your stored procedure. @FilterPairs should be two parameters:

@FilterKey,
@FilterValue,

Now it will be easy to implement procedure Components:

public void Components(int orderTypeId, string orderTypeKey, ...
    KeyValuePair<string, string> pair, ...)
{
    object[] functionParameters = new object[]
    {
        new SqlParameter(@"OrderTypeId", orderTypeId),
        new SqlParameter(@"OrderTypeKey", orderTypeKey),
        ...
        // The KeyValuePair: in your store procedure two parameters:
        new SqlParameter(@"FilterKey", pair.Key),
        new SqlParameter(@"FilterValue", pair.Value),
    };
    const string sqlCommans = @"Exec ...
        @OrderTypeId, @OrderTypeKey, ...
        @FilterKey, @FilterValue, ...";
    this.Database.ExecuteSqlCommand(sqlComman, functionParameters);
}

You'll know what to do if you want a function that takes a Dictionary, or any other class that implements IEnumerable<KeyValuePair<string, string>>


来源: stackexchange

问:
Gradle sync Error on Android Studio 3.1 Canary 3
Hey fellows after update Android Studio to 3.1 Canary 3 I've just created fresh project but gradle synchronization failed due:

Error:com.android.tools.idea.gradle.project.model.AndroidModuleModel.getMainArtifact()Lcom/android/tools/idea/gradle/project/model/ide/android/IdeAndroidArtifact;com.android.tools.idea.gradle.project.model.AndroidModuleModel.getMainArtifact()Lcom/android/tools/idea/gradle/project/model/ide/android/IdeAndroidArtifact;

My gradle file is:

```<code>> buildscript {
>     ext.kotlin_version = '1.2.0-rc-39'
>     repositories {
>         google()
>         jcenter()
>         maven { url "https://dl.bintray.com/kotlin/kotlin-dev"}
>     }
>     dependencies {
>         classpath 'com.android.tools.build:gradle:3.1.0-alpha03'
>         classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
>         classpath 'com.google.gms:google-services:3.1.0'
>     } }
>
> allprojects {
>     repositories {
>         google()
>         jcenter()
>         maven { url "https://dl.bintray.com/kotlin/kotlin-dev"}
>     } }
>
> task clean(type: Delete) {
>     delete rootProject.buildDir }
>
</code>```

And the second build.gradle

```<code>apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

android {

    compileSdkVersion 27
    buildToolsVersion '26.0.2'
    defaultConfig {
        applicationId "xxx"
        minSdkVersion 21
        targetSdkVersion 27
        versionCode 1
        versionName "0.0.1"
        setProperty("archivesBaseName", "xxx v$versionName")
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

        vectorDrawables.useSupportLibrary = true
        multiDexEnabled true

        buildConfigField 'String', 'apiEndpointUrl', '"https://xxx.xxx.xxx"'
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

ext {
    supportLibrary = '26.1.0'
    playServices = '11.2.2'
    androidLifecycle = '1.0.0-alpha9'
    androidLifecycleCompiler = '1.0.0-alpha8'
    jackson = '2.9.0'
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    testImplementation 'junit:junit:4.12'
    androidTestImplementation('com.android.support.test.espresso:espresso-core:3.0.1', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"

    // RxJava
    implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
    implementation 'io.reactivex.rxjava2:rxjava:2.1.1'
    implementation 'io.reactivex.rxjava2:rxkotlin:2.1.0'

    // Retrofit
    implementation 'com.squareup.okhttp3:okhttp:3.8.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.6.0'
    implementation 'com.squareup.retrofit2:retrofit:2.3.0'
    implementation 'com.squareup.retrofit2:adapter-rxjava2:2.2.0'

    implementation 'com.squareup.retrofit2:converter-jackson:2.3.0'
    implementation "com.fasterxml.jackson.core:jackson-core:${jackson}"
    implementation "com.fasterxml.jackson.core:jackson-annotations:${jackson}"
    implementation "com.fasterxml.jackson.core:jackson-databind:${jackson}"

    // Google Play / Firebase services
    implementation 'com.google.android.gms:play-services-maps:11.6.0'

    // Widgets / Views
    implementation "com.android.support:appcompat-v7:$supportLibrary"
    implementation "com.android.support:design:${supportLibrary}"
    implementation "com.android.support:support-v4:${supportLibrary}"
    implementation "com.android.support:cardview-v7:${supportLibrary}"
    implementation "com.android.support:recyclerview-v7:${supportLibrary}"
    implementation "com.android.support:support-vector-drawable:${supportLibrary}"
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'

    // EventBus
    implementation 'org.greenrobot:eventbus:3.0.0'

    //    Android Architecture
    implementation "android.arch.lifecycle:runtime:${androidLifecycle}"
    implementation "android.arch.lifecycle:extensions:${androidLifecycle}"
    annotationProcessor "android.arch.lifecycle:compiler:${androidLifecycleCompiler}"
    kapt "android.arch.lifecycle:compiler:${androidLifecycleCompiler}"

    // Room - DB ORM
    implementation "android.arch.persistence.room:runtime:$androidLifecycle"
    implementation "android.arch.persistence.room:rxjava2:${androidLifecycle}"
    annotationProcessor "android.arch.persistence.room:compiler:${androidLifecycleCompiler}"
    kapt "android.arch.persistence.room:compiler:${androidLifecycleCompiler}"
}
</code>```

答: Same problem here. Uninstalling the Kotlin plugin (Preferences > Plugins > Kotlin > Uninstall) and using the version that comes with the IDE solved the problem for me.</p>

ContentLicense: CC BY-SA 3.0

Body:
Hey fellows after update Android Studio to 3.1 Canary 3 I've just created fresh project but gradle synchronization failed due:

Error:com.android.tools.idea.gradle.project.model.AndroidModuleModel.getMainArtifact()Lcom/android/tools/idea/gradle/project/model/ide/android/IdeAndroidArtifact;com.android.tools.idea.gradle.project.model.AndroidModuleModel.getMainArtifact()Lcom/android/tools/idea/gradle/project/model/ide/android/IdeAndroidArtifact;

My gradle file is:

> buildscript {
>     ext.kotlin_version = '1.2.0-rc-39'
>     repositories {
>         google()
>         jcenter()
>         maven { url "https://dl.bintray.com/kotlin/kotlin-dev"}
>     }
>     dependencies {
>         classpath 'com.android.tools.build:gradle:3.1.0-alpha03'
>         classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
>         classpath 'com.google.gms:google-services:3.1.0'
>     } }
>
> allprojects {
>     repositories {
>         google()
>         jcenter()
>         maven { url "https://dl.bintray.com/kotlin/kotlin-dev"}
>     } }
>
> task clean(type: Delete) {
>     delete rootProject.buildDir }
>

And the second build.gradle

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

android {

    compileSdkVersion 27
    buildToolsVersion '26.0.2'
    defaultConfig {
        applicationId "xxx"
        minSdkVersion 21
        targetSdkVersion 27
        versionCode 1
        versionName "0.0.1"
        setProperty("archivesBaseName", "xxx v$versionName")
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

        vectorDrawables.useSupportLibrary = true
        multiDexEnabled true

        buildConfigField 'String', 'apiEndpointUrl', '"https://xxx.xxx.xxx"'
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

ext {
    supportLibrary = '26.1.0'
    playServices = '11.2.2'
    androidLifecycle = '1.0.0-alpha9'
    androidLifecycleCompiler = '1.0.0-alpha8'
    jackson = '2.9.0'
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    testImplementation 'junit:junit:4.12'
    androidTestImplementation('com.android.support.test.espresso:espresso-core:3.0.1', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"

    // RxJava
    implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
    implementation 'io.reactivex.rxjava2:rxjava:2.1.1'
    implementation 'io.reactivex.rxjava2:rxkotlin:2.1.0'

    // Retrofit
    implementation 'com.squareup.okhttp3:okhttp:3.8.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.6.0'
    implementation 'com.squareup.retrofit2:retrofit:2.3.0'
    implementation 'com.squareup.retrofit2:adapter-rxjava2:2.2.0'

    implementation 'com.squareup.retrofit2:converter-jackson:2.3.0'
    implementation "com.fasterxml.jackson.core:jackson-core:${jackson}"
    implementation "com.fasterxml.jackson.core:jackson-annotations:${jackson}"
    implementation "com.fasterxml.jackson.core:jackson-databind:${jackson}"

    // Google Play / Firebase services
    implementation 'com.google.android.gms:play-services-maps:11.6.0'

    // Widgets / Views
    implementation "com.android.support:appcompat-v7:$supportLibrary"
    implementation "com.android.support:design:${supportLibrary}"
    implementation "com.android.support:support-v4:${supportLibrary}"
    implementation "com.android.support:cardview-v7:${supportLibrary}"
    implementation "com.android.support:recyclerview-v7:${supportLibrary}"
    implementation "com.android.support:support-vector-drawable:${supportLibrary}"
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'

    // EventBus
    implementation 'org.greenrobot:eventbus:3.0.0'

    //    Android Architecture
    implementation "android.arch.lifecycle:runtime:${androidLifecycle}"
    implementation "android.arch.lifecycle:extensions:${androidLifecycle}"
    annotationProcessor "android.arch.lifecycle:compiler:${androidLifecycleCompiler}"
    kapt "android.arch.lifecycle:compiler:${androidLifecycleCompiler}"

    // Room - DB ORM
    implementation "android.arch.persistence.room:runtime:$androidLifecycle"
    implementation "android.arch.persistence.room:rxjava2:${androidLifecycle}"
    annotationProcessor "android.arch.persistence.room:compiler:${androidLifecycleCompiler}"
    kapt "android.arch.persistence.room:compiler:${androidLifecycleCompiler}"
}


问:
Getting started with an iPad application
I have an iPhone application fully finished and it doesn't rely on any specific iPhone functionality that would not be used on an iPad (for example, my iPhone app doesn't use Text Messaging). I use xcode and I use the iPhone simulator to test my app.

How would I go about making an iPad version? Do I need to make a fully new xcode project? I know there is an iPad simulator, but how do I create an iPad version. Also, when I submit to apple, how do I specify the iPhone version and the iPad version.

For instance, in my code I have a UITableView in a particular controller that is size 320x480 (to fit the iPhone). How would I specify an iPad version of that UITableView?

Can anyone explain/give me insight? Thanks!

答:
I would start off creating iPad versions of your existing XIB files.

As far as code, I have something like this setup:

```<code>#define IDIOM   UI_USER_INTERFACE_IDIOM()
#define IPAD     UIUserInterfaceIdiomPad
</code>```

and I use it like something this:

```<code>if(IDIOM == IPAD) {
    /* iPad Interface */
    tbleView.frame = CGRectMake(0,0,1024,768);
} else {
    /* iPhone Interface */
    tbleView.frame = CGRectMake(0,0,320,480);
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I would start off creating iPad versions of your existing XIB files.

As far as code, I have something like this setup:

#define IDIOM   UI_USER_INTERFACE_IDIOM()
#define IPAD     UIUserInterfaceIdiomPad

and I use it like something this:

if(IDIOM == IPAD) {
    /* iPad Interface */
    tbleView.frame = CGRectMake(0,0,1024,768);
} else {
    /* iPhone Interface */
    tbleView.frame = CGRectMake(0,0,320,480);
}


问:
Error:(52, 14) error: cannot find symbol method onPreExecute() on Android Studio
I'm trying out a login tutorial (Create an Android login system using MySQL) on Android Studio 3.0. I ran into these errors:

import android.os.AsyncTask; (Click here to see the error)

When I hover on it, it says:

Unused import statement

onPreExecute() (Click here to see the error)

The message shows:

Error:(52, 14) error: cannot find symbol method onPreExecute()

Can anybody help me out? I'm new to this. I'm sorry if the question is not that clear.

答:
Ok i understand your problem, when you create class extend Asyntask, you should Override three methods (onPreExecute, doInBackground and onPostExecute). In order to Override methods, any position mouse in class extend Asyntask you right click and choise Generate...(or shortKey: Alt + Insert) --> Override Methods --> choise onPreExecute, doInBackground and onPostExecute). See all step with images below:

finish Override for Asyntask.


问:
How many times the last statement of a recursive function block gets executed?
Consider the below code snippet demonstrating recursion :

```<code><?php
  function test() {
    static $count = 0;

    $count++;
    echo $count."<br>";
    if($count < 10) {
      test();
    }
    echo "Count Value : ".$count--;
  }

  test();
?>
</code>```

Output of above code is as below :

```<code>1
2
3
4
5
6
7
8
9
10
Count Value : 10
Count Value : 9
Count Value : 8
Count Value : 7
Count Value : 6
Count Value : 5
Count Value : 4
Count Value : 3
Count Value : 2
Count Value : 1
</code>```

I expected the last code statement of the function test() i.e. echo "Count Value : ".$count--; will get execute only once when the if condition returns false upon $count = 10; and everything would be finish.

But unexpectedly, I'm getting it executed ten times with decreasing value of variable $count. I'm not understanding how it's happening? How is the code flow getting manipulated here unexpectedly?

As the recursive function call is made inside the if condition how can it get called subsequently for 10 more times even after failing the if condition?

Please explain me.

Note :  I haven't forgot to add else and I don't want it. Just explain why and how the last statement is getting executed only after printing nos. from 1 to 10 and only after the failing of if condition. When the if condition was returning true it was not getting executed. How?

答:
Your code runs 9 times the recursion + 1 from outside, so it should be ok to have 10 total executions.
Here a commented version:</p>

```<code><?php
  function test() {
    static $count = 0; // initialize only the first run

    $count++;
    echo $count."<br>"; // Current $count status
    if($count < 10) {   // goes on until 9
      test();           // This function will run before everything else
    }
    // regardless the value of $count print $count then decreases it
    echo "Count Value : ".$count--;
    //only the other calls in the stack will see by the -- operator effect

  }
  test();
?>
</code>```

Body:
Consider the below code snippet demonstrating recursion :

<?php
  function test() {
    static $count = 0;

    $count++;
    echo $count."
";
    if($count < 10) {
      test();
    }
    echo "Count Value : ".$count--;
  }

  test();
?>

Output of above code is as below :

1
2
3
4
5
6
7
8
9
10
Count Value : 10
Count Value : 9
Count Value : 8
Count Value : 7
Count Value : 6
Count Value : 5
Count Value : 4
Count Value : 3
Count Value : 2
Count Value : 1

I expected the last code statement of the function test() i.e. echo "Count Value : ".$count--; will get execute only once when the if condition returns false upon $count = 10; and everything would be finish.

But unexpectedly, I'm getting it executed ten times with decreasing value of variable $count. I'm not understanding how it's happening? How is the code flow getting manipulated here unexpectedly?

As the recursive function call is made inside the if condition how can it get called subsequently for 10 more times even after failing the if condition?

Please explain me.

Note :  I haven't forgot to add else and I don't want it. Just explain why and how the last statement is getting executed only after printing nos. from 1 to 10 and only after the failing of if condition. When the if condition was returning true it was not getting executed. How?

Body:
Your code runs 9 times the recursion + 1 from outside, so it should be ok to have 10 total executions.
Here a commented version:

<?php
  function test() {
    static $count = 0; // initialize only the first run

    $count++;
    echo $count."<br>"; // Current $count status
    if($count < 10) {   // goes on until 9
      test();           // This function will run before everything else
    }
    // regardless the value of $count print $count then decreases it
    echo "Count Value : ".$count--;
    //only the other calls in the stack will see by the -- operator effect

  }
  test();
?>


问:
Microsoft SQL Server, increasing price by percentage, rounded up
let's say I have a table called products_tbl, and a price column called price. I need a script to update the prices by 3% rounded up, so if the result of a cell is 41.3, it has to become 42.
Is it possible?</p>

答:
Test this using select query first if it is achieving as expected,
Use ceiling instead, i assume your data type is int

```<code>SELECT
   ceiling(price+ ( price/100*3),0) RoundedpercentValue
  ,price+ ( price/100*3)      PercentValue
 , price
FROM PRODUCTS
</code>```

--Update the table

```<code>UPDATE products
set price = ceiling(price+ ( price/100*3),0)
</code>```

or if there is truncation issue

```<code>Update Products
set price = ceiling(price + price *0.03)
</code>```

Body:
Test this using select query first if it is achieving as expected,
Use ceiling instead, i assume your data type is int

SELECT
   ceiling(price+ ( price/100*3),0) RoundedpercentValue
  ,price+ ( price/100*3)      PercentValue
 , price
FROM PRODUCTS

--Update the table

UPDATE products
set price = ceiling(price+ ( price/100*3),0)

or if there is truncation issue

Update Products
set price = ceiling(price + price *0.03)


问:
Lock a ToggleButton after checking
I have a GUI which is built with the MVVM-Pattern. In the View there is a Toggle-Button, which IsChecked property is bound to a bool property in the ViewModel.

Now it is only allowed to turn the ToggleButton (and the bool property in the ViewModel) from false to true over the View. A method resets the bool property in the ViewModel, so the user can switch the Toggle-Button again from false to true.

How can I lock the Toggle-Button in the View, without using the IsEnabled Property?

Thanks.

答:
I don't know why you don't want to use the IsEnabled property, but just for the heck of it, here is an extension property that could easily be done in one line of code-behind (but that wouldn't be very MVVM and would be less fun):

Disclaimer

This works exactly as you described but there are a lot easier ways to do this. If you want to avoid using IsEnabled because of the grayed out look, simply re-style the button any nobody will notice the difference.

```<code>public static class ToggleButtonExtensions
{
    public static readonly DependencyProperty CanNotUncheckByHandProperty = DependencyProperty.RegisterAttached(
        "CanNotUncheckByHand", typeof(bool), typeof(ToggleButtonExtensions), new PropertyMetadata(default(bool), OnCanNotUncheckByHandPropertyChangedCallback));

    private static void OnCanNotUncheckByHandPropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs eventArgs)
    {
        if (!(dependencyObject is ToggleButton)) return;

        if ((bool)eventArgs.NewValue)
            ((ToggleButton)dependencyObject).Click += OnClick;
        else
            ((ToggleButton)dependencyObject).Click -= OnClick;
    }

    public static void SetCanNotUncheckByHand(DependencyObject element, bool value)
    {
        element.SetValue(CanNotUncheckByHandProperty, value);
    }

    private static void OnClick(object sender, RoutedEventArgs routedEventArgs)
    {
        ((ToggleButton) sender).IsChecked = true;
    }

    public static bool GetCanNotUncheckByHand(DependencyObject element)
    {
        return (bool) element.GetValue(CanNotUncheckByHandProperty);
    }
}
</code>```

<ToggleButton local:ToggleButtonExtensions.CanNotUncheckByHand="True"/>
```

Basically what this does is making sure that the ToggleButton stays Checked whenever it is unchecked by hand.

Title: Lock a ToggleButton after checking

Body:
I don't know why you don't want to use the IsEnabled property, but just for the heck of it, here is an extension property that could easily be done in one line of code-behind (but that wouldn't be very MVVM and would be less fun):

Disclaimer

This works exactly as you described but there are a lot easier ways to do this. If you want to avoid using IsEnabled because of the grayed out look, simply re-style the button any nobody will notice the difference.

public static class ToggleButtonExtensions
{
    public static readonly DependencyProperty CanNotUncheckByHandProperty = DependencyProperty.RegisterAttached(
        "CanNotUncheckByHand", typeof(bool), typeof(ToggleButtonExtensions), new PropertyMetadata(default(bool), OnCanNotUncheckByHandPropertyChangedCallback));

    private static void OnCanNotUncheckByHandPropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs eventArgs)
    {
        if (!(dependencyObject is ToggleButton)) return;

        if ((bool)eventArgs.NewValue)
            ((ToggleButton)dependencyObject).Click += OnClick;
        else
            ((ToggleButton)dependencyObject).Click -= OnClick;
    }

    public static void SetCanNotUncheckByHand(DependencyObject element, bool value)
    {
        element.SetValue(CanNotUncheckByHandProperty, value);
    }

    private static void OnClick(object sender, RoutedEventArgs routedEventArgs)
    {
        ((ToggleButton) sender).IsChecked = true;
    }

    public static bool GetCanNotUncheckByHand(DependencyObject element)
    {
        return (bool) element.GetValue(CanNotUncheckByHandProperty);
    }
}

<ToggleButton local:ToggleButtonExtensions.CanNotUncheckByHand="True"/>

Basically what this does is making sure that the ToggleButton stays Checked whenever it is unchecked by hand.


问:
Yii2- unable to redirect from one view to another with dataprovider
I have a view in which I have a a tag button. On the click of the button a an ajax request is sent to the given action view controller and in that action view some values are saved in the database. After that I am redirecting the view to another view.

What I have done?

My View

```<code><a href="<?= URL::toRoute(['ogpheader/viewsetpdf', 'id'=>$model->id])?>"  name="redirect" class="btn btn-primary" id="myid">Set PDF</a>
//this is the a tag button
</code>```

Ajax call in same view

```<code><?php
$url = Url::toRoute(['/ogpheader/viewsetpdf','id'=>$model->id]);
$script = <<< JS
$(document).ready(function () {

$('#myid').on('click',function(e) {
e.preventDefault();
 var strValue = "";
    $('input[name="selection[]"]:checked').each(function() {

    if(strValue!="")
        {
        strValue = strValue + " , " + this.value;

        }
    else
       strValue = this.value;

});
    //alert(strValue);
$.ajax({
     url: '$url',
     type: 'POST',
     dataType: 'json',
     data: {data:strValue},
     success: function(data) {
        alert(data);
      },
     });
    })
  });
  JS;
  $this->registerJs($script, static::POS_END);
  ?>
</code>```

My action Controller

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

        foreach($data as $value)
        {
            $m = new Ogpdetail;
            $m -> load(Yii::$app->request->post());
            $m->ogp_id = $ogp_id;
            $m->created_at = date('Y-m-d h:i:s');
            $m->meter_id = $value;
            $m->meter_serial = \common\models\Meters::idTomsn($value);

            if($m->save())
            {
                $model->status = Ogpheader::$status_titles[1];
                $model->update();
                //echo "All data is saved";
                //exit();
            }
            else{
                $this->renderAjax('viewcreated');
            }
        }

        //print_r($data);
    }
    else{
        $this->renderAjax('viewcreated');
    }
$query = "SELECT DISTINCT  ogpd.`meter_serial` AS 'Meter_Serial_Number', IFNULL(ogpd.`remarks`,'') AS 'Remarks' FROM `ogp_detail` ogpd
                        INNER JOIN `ogp_header` ogph ON ogpd.`ogp_id` = ogph.`id`";

    $count = Yii::$app->db->createCommand("SELECT COUNT(DISTINCT ogpd.`meter_serial`) FROM `ogp_detail` ogpd
                         INNER JOIN `ogp_header` ogph ON ogpd.`ogp_id` = ogph.`id`")->queryScalar();

    $dataProvider = new SqlDataProvider([
        'sql' => $query,
        'totalCount' => $count,
        'pagination' => [
            'pageSize' => 5,
        ],
    ]);

    return $this->redirect('viewsetpdf',[
        'dataProvider' => $dataProvider,
        'model' => $this->findModel($id),
        'id' => $model->id
    ]);
</code>```

When i click on my Set PDF button I am getting Not Found (#404). While all the records are saved into my desired tables.

Also the URL is http://localhost:225/inventory-web/backend/web/ogpheader/viewcreated/viewsetpdf but it should be http://localhost:225/inventory-web/backend/web/ogpheader/viewsetpdf

I don't know what is the problem and I am stuck to it.

Any help would be highly appreciated.

答:
You are generating a Route, not a URL. Try replacing this:

```<code><a href="<?= URL::toRoute(['ogpheader/viewsetpdf', 'id'=>$model->id])?>"  name="redirect" class="btn btn-primary" id="myid">Set PDF</a>
</code>```

With this:

```<code>Html::a('Set PDF', ['ogpheader/viewsetpdf', 'id'=>$model->id], ['id' => 'myid', 'name'=>'redirect', 'class'='btn btn-primary'])
</code>```

Body:
I have a view in which I have a a tag button. On the click of the button a an ajax request is sent to the given action view controller and in that action view some values are saved in the database. After that I am redirecting the view to another view.

What I have done?

My View

<a href="<?= URL::toRoute(['ogpheader/viewsetpdf', 'id'=>$model->id])?>"  name="redirect" class="btn btn-primary" id="myid">Set PDF
//this is the a tag button

Ajax call in same view

<?php
$url = Url::toRoute(['/ogpheader/viewsetpdf','id'=>$model->id]);
$script = <<< JS
$(document).ready(function () {

$('#myid').on('click',function(e) {
e.preventDefault();
 var strValue = "";
    $('input[name="selection[]"]:checked').each(function() {

    if(strValue!="")
        {
        strValue = strValue + " , " + this.value;

        }
    else
       strValue = this.value;

});
    //alert(strValue);
$.ajax({
     url: '$url',
     type: 'POST',
     dataType: 'json',
     data: {data:strValue},
     success: function(data) {
        alert(data);
      },
     });
    })
  });
  JS;
  $this->registerJs($script, static::POS_END);
  ?>

My action Controller

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

        foreach($data as $value)
        {
            $m = new Ogpdetail;
            $m -> load(Yii::$app->request->post());
            $m->ogp_id = $ogp_id;
            $m->created_at = date('Y-m-d h:i:s');
            $m->meter_id = $value;
            $m->meter_serial = \common\models\Meters::idTomsn($value);

            if($m->save())
            {
                $model->status = Ogpheader::$status_titles[1];
                $model->update();
                //echo "All data is saved";
                //exit();
            }
            else{
                $this->renderAjax('viewcreated');
            }
        }

        //print_r($data);
    }
    else{
        $this->renderAjax('viewcreated');
    }
$query = "SELECT DISTINCT  ogpd.`meter_serial` AS 'Meter_Serial_Number', IFNULL(ogpd.`remarks`,'') AS 'Remarks' FROM `ogp_detail` ogpd
                        INNER JOIN `ogp_header` ogph ON ogpd.`ogp_id` = ogph.`id`";

    $count = Yii::$app->db->createCommand("SELECT COUNT(DISTINCT ogpd.`meter_serial`) FROM `ogp_detail` ogpd
                         INNER JOIN `ogp_header` ogph ON ogpd.`ogp_id` = ogph.`id`")->queryScalar();

    $dataProvider = new SqlDataProvider([
        'sql' => $query,
        'totalCount' => $count,
        'pagination' => [
            'pageSize' => 5,
        ],
    ]);

    return $this->redirect('viewsetpdf',[
        'dataProvider' => $dataProvider,
        'model' => $this->findModel($id),
        'id' => $model->id
    ]);

When i click on my Set PDF button I am getting Not Found (#404). While all the records are saved into my desired tables.

Also the URL is http://localhost:225/inventory-web/backend/web/ogpheader/viewcreated/viewsetpdf but it should be http://localhost:225/inventory-web/backend/web/ogpheader/viewsetpdf

I don't know what is the problem and I am stuck to it.

Any help would be highly appreciated.

Body:
You are generating a Route, not a URL. Try replacing this:

<a href="<?= URL::toRoute(['ogpheader/viewsetpdf', 'id'=>$model->id])?>"  name="redirect" class="btn btn-primary" id="myid">Set PDF</a>

With this:

Html::a('Set PDF', ['ogpheader/viewsetpdf', 'id'=>$model->id], ['id' => 'myid', 'name'=>'redirect', 'class'='btn btn-primary'])


问:
Execute SQL*Plus script via Jenkins and bat command
In my Jenkins Pipeline script, I have a map named orderedScripts which contains Integer keys (1-11) and the values for each key are lists. The items within the lists are absolute paths to sql scripts.

I loop through the map and then loop through the list of each key, executing the items in the list via sqlplus. Code snippet below, where <credentials> are the DB credentials used.

```<code>orderedScripts.each {
        key, value -> for(item in value){
            bat "sqlplus <credentials> @'${item}'"
        }
    }
</code>```

However, when Jenkins runs the job I get the following Serilizable error:

```<code>Caused: java.io.NotSerializableException: hudson.scm.SubversionChangeLogSet
at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:860)
at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:569)
at org.jboss.marshalling.river.BlockMarshaller.doWriteObject(BlockMarshaller.java:65)
at org.jboss.marshalling.river.BlockMarshaller.writeObject(BlockMarshaller.java:56)
at org.jboss.marshalling.MarshallerObjectOutputStream.writeObjectOverride(MarshallerObjectOutputStream.java:50)
at org.jboss.marshalling.river.RiverObjectOutputStream.writeObjectOverride(RiverObjectOutputStream.java:179)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at java.util.HashMap.internalWriteEntries(Unknown Source)
at java.util.HashMap.writeObject(Unknown Source)
at sun.reflect.GeneratedMethodAccessor95.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
</code>```

If I print out the ${item} variable with a normal println() then it shows the correct script path. So the loop is working, and identifying the correct scripts to run, Jenkins just won't run them via the bat command. If I print out the path in the script and then copy and paste it into a sqlplus session manually, it executes as expected.

From what I can find, it seems to be how I'm referencing the ${item} variable within the bat command. But I can't get it to execute, with different variations of quotations. Anyone experience this before, or know what I'm doing wrong?

答:
Answering my own question here..

The issue was related to Serialization Problems In Global Function

Which points to the following Jenkinsfile example on Github:
Jenkins File example

Body:
In my Jenkins Pipeline script, I have a map named orderedScripts which contains Integer keys (1-11) and the values for each key are lists. The items within the lists are absolute paths to sql scripts.

I loop through the map and then loop through the list of each key, executing the items in the list via sqlplus. Code snippet below, where <credentials> are the DB credentials used.

orderedScripts.each {
        key, value -> for(item in value){
            bat "sqlplus <credentials> @'${item}'"
        }
    }

However, when Jenkins runs the job I get the following Serilizable error:

Caused: java.io.NotSerializableException: hudson.scm.SubversionChangeLogSet
at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:860)
at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:569)
at org.jboss.marshalling.river.BlockMarshaller.doWriteObject(BlockMarshaller.java:65)
at org.jboss.marshalling.river.BlockMarshaller.writeObject(BlockMarshaller.java:56)
at org.jboss.marshalling.MarshallerObjectOutputStream.writeObjectOverride(MarshallerObjectOutputStream.java:50)
at org.jboss.marshalling.river.RiverObjectOutputStream.writeObjectOverride(RiverObjectOutputStream.java:179)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at java.util.HashMap.internalWriteEntries(Unknown Source)
at java.util.HashMap.writeObject(Unknown Source)
at sun.reflect.GeneratedMethodAccessor95.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)

If I print out the ${item} variable with a normal println() then it shows the correct script path. So the loop is working, and identifying the correct scripts to run, Jenkins just won't run them via the bat command. If I print out the path in the script and then copy and paste it into a sqlplus session manually, it executes as expected.

From what I can find, it seems to be how I'm referencing the ${item} variable within the bat command. But I can't get it to execute, with different variations of quotations. Anyone experience this before, or know what I'm doing wrong?


问:
I want to animate, in fact fade, "within" drawRect
Is there a way to make drawRect animate FROM THE PREVIOUS SCENE to the next one?

(Amazingly) you can animate inside drawRect - try it.  You can fade, translate or animate any other property.

However, it starts "from fresh", from blank.  So for example if you put a fade-in animation block in drawRect, the previous scene with disappear and the new scene will fade up from white.

I want the screen to fade from the previous image (drawn in the previous cycle of drawRect) to the new image I have just drawn ... err, am drawing.

Is there a way to do that, perhaps trickily by manipulating what's going on with drawRect?

This would seem to be a very common use case - blending from one scene to the next.

Does anyone know the secret?

Of course, obviously this can be done in the core animation milieu or in many other ways, but having drawRect fade from one drawRect to the next is an obvious idea. Cheers.

Astounding update thanks to the genius of WrightCS.....

Thanks only to WrightCS, we now know that drawRect handles animations perfectly. Simply paste this code at the end of any drawRect and try it:

```<code>self.alpha = 0.0;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:2];
self.alpha = 1.0;
[UIView commitAnimations];
</code>```

it treats the entire drawRect, no matter how complex, as one enormous block and it wraps it in that animation.  Yes, it even includes painted in offscreen areas, bitmap rendering or anything else. Everything gets animated. Who knew?

The problem at hand - how to make it start the animation from the previous scene rather than start from blank?

答:
Drawrect Is invisible. It happens in the 'backbuffer' which the iOS displays on screen only when you're ready with drawRect. So you can definitely not animate while in drawrect. However, you can commit animation instrucions from just about anywhere, including drawrect. But the animation will be performed afterwards.

Animation requires timing and showing different frames to the user.

You CAN do that all by yourself (constantly forcing a redraw and doing something slightly different in drawrect each the time) but that's a lot of work, especialy if you want it done right.

Luckily iOS has many animation effects programmed for you. Either using Core Animation, or the (more simple and basic) animation in UIKit. But since it works by animating certain properties of views (eg the alpha of a whole view, or the rotation of a whole view, ...) you might need to rearrange your views and subviews to make good use of it.

E.g. Each horse limb is separate subview and you animate their transformations (no redraw needed, iOS will do the rest)

E.g. The old and new frame are two separate views and you animate the new frame (which is on top) from alpha 0 to alpha 1.

Body:
Is there a way to make drawRect animate FROM THE PREVIOUS SCENE to the next one?

(Amazingly) you can animate inside drawRect - try it.  You can fade, translate or animate any other property.

However, it starts "from fresh", from blank.  So for example if you put a fade-in animation block in drawRect, the previous scene with disappear and the new scene will fade up from white.

I want the screen to fade from the previous image (drawn in the previous cycle of drawRect) to the new image I have just drawn ... err, am drawing.

Is there a way to do that, perhaps trickily by manipulating what's going on with drawRect?

This would seem to be a very common use case - blending from one scene to the next.

Does anyone know the secret?

Of course, obviously this can be done in the core animation milieu or in many other ways, but having drawRect fade from one drawRect to the next is an obvious idea. Cheers.

Astounding update thanks to the genius of WrightCS.....

Thanks only to WrightCS, we now know that drawRect handles animations perfectly. Simply paste this code at the end of any drawRect and try it:

self.alpha = 0.0;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:2];
self.alpha = 1.0;
[UIView commitAnimations];

it treats the entire drawRect, no matter how complex, as one enormous block and it wraps it in that animation.  Yes, it even includes painted in offscreen areas, bitmap rendering or anything else. Everything gets animated. Who knew?

The problem at hand - how to make it start the animation from the previous scene rather than start from blank?


问:
Convert CSV format as text in email body
I have a cron job which when run gives me a csv file which looks like below:

I have another cron job where I am trying to display the csv data directly in an email body and the output of that is as below:

As you can see above, the output from email is distorted and looks ugly. WHat changes should I make for the email format to be similar with the csv format?.

I am using the below bash commands in my cron :

```<code>EMAILBODY="$(${RUNDIR}/${DEV1} ${FILELOCATION} ${FILENAME})"

echo "$EMAILBODY" | mailx -r ${SENDER} -s "Alerts Email for $(date +%Y-%m-%d_%H:%M)" abcd@xyz.com
</code>```

I tried the below change to the script:

```<code>echo "$EMAILBODY" | column -s, -t | mailx -r ${SENDER} -s "Alerts Email for $(date +%Y-%m-%d_%H:%M)" abcd@xyz.com
</code>```

and now I see this in the email:

As you can notice, the format is little better than before. But how can I align the data perfectly with the headers?

答:
Firstly, it's not accurate to say you have "a csv file which looks like below". You have a CSV file which looks like that when you open it in a spreadsheet program.

You have a few problems to address here. Using columns was a good idea, but columns (like many Unix command-line utilities) thinks that everyone still lives in a Unix console with fixed-width fonts. The slight misalignments you're seeing are down to you viewing the email using a proportional font, so not all characters are the same width.

You could try separating the output with tabs. That will look better - but there will still be cases that don't work (because you don't always need exactly one tab between columns in order to get them to line up.

The only way to guarantee the appearance you want is to create a MIME email with content-type of "text/html" and to create an HTML table containing your data. But that's a lot more work that what you're currently doing.

Body:
I have a cron job which when run gives me a csv file which looks like below:

I have another cron job where I am trying to display the csv data directly in an email body and the output of that is as below:

As you can see above, the output from email is distorted and looks ugly. WHat changes should I make for the email format to be similar with the csv format?.

I am using the below bash commands in my cron :

EMAILBODY="$(${RUNDIR}/${DEV1} ${FILELOCATION} ${FILENAME})"

echo "$EMAILBODY" | mailx -r ${SENDER} -s "Alerts Email for $(date +%Y-%m-%d_%H:%M)" abcd@xyz.com

I tried the below change to the script:

echo "$EMAILBODY" | column -s, -t | mailx -r ${SENDER} -s "Alerts Email for $(date +%Y-%m-%d_%H:%M)" abcd@xyz.com

and now I see this in the email:

As you can notice, the format is little better than before. But how can I align the data perfectly with the headers?


问:
sed escaping error for a Jenkins build
I am trying to use sed to replace a line in a json file. Here is the original;

sed -i 's/"development": "s3://dev.server.com/pentlands/atg"/"development": "new-bucket-here"/g' file.txt

I have tried this;

sed -i 's/"development": "s3://dev\.server\.com/pentlands/atg"/"development": "new-bucket-here"/g' file.txt

Here is the error;

WorkflowScript: 37: unexpected char: '\' @ line 37, column 47.
   -i 's/"development": "s3://dev\./server

答:
The best way to update json file is to use a json parser like jq.

However if you want to perform a simple string change, you can try this:

```<code>sed -i 's,"development": "s3://dev\.server\.com/pentlands/atg","development": "new-bucket-here",g' file.txt
</code>```

Note the , replaces the / and is used as separator in the sed command.

Title: sed escaping error for a Jenkins build

Body:
The best way to update json file is to use a json parser like jq.

However if you want to perform a simple string change, you can try this:

sed -i 's,"development": "s3://dev\.server\.com/pentlands/atg","development": "new-bucket-here",g' file.txt

Note the , replaces the / and is used as separator in the sed command.


问:
In delphi, how do you embed Excel in a form and show excel components on the component pallette?
Years ago I remember installing excel and office components onto the component palette in delphi 5.  It was either through activeX or COM, or a typelib, there was some way to install the components.   the components I think you could drag and drop onto the form and then a spreadsheet would be embedded into your app (or microsoft word, etc.).

The only information I can find on the internet is about using OLEcontainers... which is a component in the system tab of delphi 5.  However I do not remember it being an OLEcontainer when I used components for embedding excel, I rather remember installing actual excel and office components onto the component palette somehow... the components may have been generated from an ocx file or a typelib, I do not remember.  Where does one find or obtain the files to generate the excel and office components on the component palette?  are they ocx and do they come with my copy of MS Office that I have on my computer?

Are there excel COM or activex components that one can install? Am I remembering correctly, or is the only way to use excel through OLEcontainer component?

Edit: it may have also been an automation server component for excel or office

答:
You can do this:

In FormCreate (or OnActivate..)

```<code>OleContainer1.CreateLinkToFile( Edit1.Text, false );
</code>```

This is the result:

Body:
You can do this:

In FormCreate (or OnActivate..)

OleContainer1.CreateLinkToFile( Edit1.Text, false );

This is the result:


问:
How to make switch tab content fixed?
I have switch tab but my problem is how can make a content fixed?
Example if I switch tabs my content is still fixed even short or long content

On this code when I have long content my layout will go long and my content is short my content also will be long.

How can set layout be fixed?

.tabs{
     margin-bottom:25px;
    }
    .nav-tabs{
    }
    .nav-tabs li{
     position:relative;
     display:block;
     float:left;
     margin-right:1px;
    }
    .nav-tabs li a{
     display:block;
     padding:10px 20px;
     background:#efefef;
     text-decoration:none;
    }
    .nav-tabs li > i{
     color:#efefef;
    }
    .nav-tabs li > i{
     position: absolute;
     bottom: -10px;
     font-size: 16px;
     width: 20px;
     left: 50%;
     margin-left: -10px;
    }
    .nav-tabs li a:hover{
     color:#fff;
     background:#666;
     text-decoration:none;
    }
    .nav-tabs li a:active, .nav-tabs li.active a{
     color:#fff;
     background:#666;
    }
    .tab-content{
     padding:20px 0;
     background:#ffffff;
    }
    .tab-content > .tab-pane{
     display:none;
    }
    .tab-content > .active{
     display:block;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="tabs">
                    <ul class="nav nav-tabs">
                      <li class="active">  Sample Tab #1  </li>
                      <li>  Sample Tab #2  </li>
                      <li>  Sample Tab #3  </li>
                    </ul>
                    <div class="tab-content">
                      <div id="sampletab1" class="tab-pane active">
                        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce velit tortor, dictum in gravida nec, aliquet non lorem. Donec vestibulum justo a diam ultricies pellentesque. Quisque mattis diam vel lacus tincidunt elementum. Sed vitae adipiscing turpis. Aenean ligula nibh, molestie id viverra a, dapibus at dolor.</p>
                      </div>
                      <div id="sampletab2" class="tab-pane">
                        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce velit tortor, dictum in gravida nec, aliquet non lorem. Donec vestibulum justo a diam ultricies pellentesque.</p>
                      </div>
                      <div id="sampletab3" class="tab-pane">
                        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce velit tortor, dictum in gravida nec, aliquet non lorem. Donec vestibulum justo a diam ultricies pellentesque. Quisque mattis diam vel lacus tincidunt elementum. Sed vitae adipiscing turpis. Aenean ligula nibh, molestie id viverra a, dapibus at dolor. In iaculis viverra neque, ac eleifend ante lobortis id. In viverra ipsum ac eros tristique dignissim. Donec aliquam velit vitae mi dictum. </p>
                      </div>
                    </div>
                  </div></code>```

Thankyou

答:
Add this css code to your .tab-content to make this fixed height with scroll

```<code>.tab-content{
height: 80px;//change this value
overflow-y: scroll;
}
</code>```

Title: How to make switch tab content fixed?

Body:
I have switch tab but my problem is how can make a content fixed?
Example if I switch tabs my content is still fixed even short or long content

On this code when I have long content my layout will go long and my content is short my content also will be long.

How can set layout be fixed?

.tabs{
     margin-bottom:25px;
    }
    .nav-tabs{
    }
    .nav-tabs li{
     position:relative;
     display:block;
     float:left;
     margin-right:1px;
    }
    .nav-tabs li a{
     display:block;
     padding:10px 20px;
     background:#efefef;
     text-decoration:none;
    }
    .nav-tabs li > i{
     color:#efefef;
    }
    .nav-tabs li > i{
     position: absolute;
     bottom: -10px;
     font-size: 16px;
     width: 20px;
     left: 50%;
     margin-left: -10px;
    }
    .nav-tabs li a:hover{
     color:#fff;
     background:#666;
     text-decoration:none;
    }
    .nav-tabs li a:active, .nav-tabs li.active a{
     color:#fff;
     background:#666;
    }
    .tab-content{
     padding:20px 0;
     background:#ffffff;
    }
    .tab-content > .tab-pane{
     display:none;
    }
    .tab-content > .active{
     display:block;
    }

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

  Sample Tab #1

  Sample Tab #2

  Sample Tab #3

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce velit tortor, dictum in gravida nec, aliquet non lorem. Donec vestibulum justo a diam ultricies pellentesque. Quisque mattis diam vel lacus tincidunt elementum. Sed vitae adipiscing turpis. Aenean ligula nibh, molestie id viverra a, dapibus at dolor.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce velit tortor, dictum in gravida nec, aliquet non lorem. Donec vestibulum justo a diam ultricies pellentesque.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce velit tortor, dictum in gravida nec, aliquet non lorem. Donec vestibulum justo a diam ultricies pellentesque. Quisque mattis diam vel lacus tincidunt elementum. Sed vitae adipiscing turpis. Aenean ligula nibh, molestie id viverra a, dapibus at dolor. In iaculis viverra neque, ac eleifend ante lobortis id. In viverra ipsum ac eros tristique dignissim. Donec aliquam velit vitae mi dictum.

Thankyou

Body:
Add this css code to your .tab-content to make this fixed height with scroll

.tab-content{
height: 80px;//change this value
overflow-y: scroll;
}


问:
How to add extra fields to Firebase auth? Age & Gender
So far I'm really impressed with Firebase. But I would like to know how would I go about customizing my user email authentication. I would like to add the following fields: Age and Gender for users to fill out when registering.

here's my SignUpActivity.java.

```<code>public class SignUpActivity extends AppCompatActivity {
private EditText inputEmail, inputPassword, signupInputUsername, signupInputAge;
private Button btnLinkLogin, btnSignUp, btnResetPassword;
private ProgressBar progressBar;
private FirebaseAuth auth;
private Spinner sexSpinner;
String defaultTextForSpinner = "Sex";
String[] arrayForSpinner = {"Male", "Female"};

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

    //Get Firebase auth instance
    auth = FirebaseAuth.getInstance();

    inputEmail = (EditText) findViewById(R.id.signup_input_email);
    signupInputUsername = (EditText) findViewById(R.id.signup_input_username);
    inputPassword = (EditText) findViewById(R.id.signup_input_password);
    signupInputAge = (EditText) findViewById(R.id.signup_input_birthday);
    sexSpinner = (Spinner)findViewById(R.id.spinner);
    sexSpinner.setAdapter(new CustomSpinnerAdapter(this, R.layout.spinner_row, arrayForSpinner, defaultTextForSpinner));

    btnSignUp = (Button) findViewById(R.id.btnSignUp2);
    btnLinkLogin = (Button) findViewById(R.id.btnorlogin);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);
    EditText edittext = (EditText) findViewById(R.id.signup_input_birthday);

    edittext.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            //To show current date in the datepicker
            Calendar mcurrentDate = Calendar.getInstance();
            int mYear = mcurrentDate.get(Calendar.YEAR);
            int mMonth = mcurrentDate.get(Calendar.MONTH);
            int mDay = mcurrentDate.get(Calendar.DAY_OF_MONTH);

            DatePickerDialog mDatePicker=new DatePickerDialog(SignUpActivity.this, new DatePickerDialog.OnDateSetListener() {
                public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday) {
                    // TODO Auto-generated method stub
                /*      Your code   to get date and time    */
                }
            },mYear, mMonth, mDay);
            mDatePicker.setTitle("Select birthday");
            mDatePicker.show();  }
    });

    btnSignUp.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String email = inputEmail.getText().toString().trim();
            String password = inputPassword.getText().toString().trim();

            if (TextUtils.isEmpty(email)) {
                Toast.makeText(getApplicationContext(), "Enter email address.", Toast.LENGTH_SHORT).show();
                return;
            }

            if (TextUtils.isEmpty(password)) {
                Toast.makeText(getApplicationContext(), "Enter password.", Toast.LENGTH_SHORT).show();
                return;
            }

            if (password.length() < 6) {
                Toast.makeText(getApplicationContext(), "Password too short, enter minimum 6 characters.", Toast.LENGTH_SHORT).show();
                return;
            }

            progressBar.setVisibility(View.VISIBLE);
            //create user
            auth.createUserWithEmailAndPassword(email, password)
                    .addOnCompleteListener(SignUpActivity.this, new OnCompleteListener<AuthResult>() {
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {
                            Toast.makeText(SignUpActivity.this, "createUserWithEmail:onComplete:" + task.isSuccessful(), Toast.LENGTH_SHORT).show();
                            progressBar.setVisibility(View.GONE);
                            // If sign in fails, display a message to the user. If sign in succeeds
                            // the auth state listener will be notified and logic to handle the
                            // signed in user can be handled in the listener.
                            if (!task.isSuccessful()) {
                                Toast.makeText(SignUpActivity.this, "Authentication failed." + task.getException(),
                                        Toast.LENGTH_SHORT).show();
                            } else {
                                startActivity(new Intent(SignUpActivity.this, MainActivity.class));
                                finish();
                            }
                        }
                    });

        }
    });
}

@Override
protected void onResume() {
    super.onResume();
    progressBar.setVisibility(View.GONE);
}

public class CustomSpinnerAdapter extends ArrayAdapter<String> {

    Context context;
    String[] objects;
    String firstElement;
    boolean isFirstTime;

    public CustomSpinnerAdapter(Context context, int textViewResourceId, String[] objects, String defaultText) {
        super(context, textViewResourceId, objects);
        this.context = context;
        this.objects = objects;
        this.isFirstTime = true;
        setDefaultText(defaultText);
    }

    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {
        if(isFirstTime) {
            objects[0] = firstElement;
            isFirstTime = false;
        }
        return getCustomView(position, convertView, parent);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        notifyDataSetChanged();
        return getCustomView(position, convertView, parent);
    }

    public void setDefaultText(String defaultText) {
        this.firstElement = objects[0];
        objects[0] = defaultText;
    }

    public View getCustomView(int position, View convertView, ViewGroup parent) {

        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View row = inflater.inflate(R.layout.spinner_row, parent, false);
        TextView label = (TextView) row.findViewById(R.id.spinner_text);
        label.setText(objects[position]);

        return row;
    }

}
</code>```

答:
When you are using Firebase authentication with user and password, the only data that you can get after authentication  is that data that you get from FirebaseUser object. As you probably see, there also a couple of methods that can help you get the data easier, like: getEmail(), getDisplayName(), getPhotoUrl() and so on.

Unfortunately, you cannot add additional data like age and gender to the FirebaseUser object. If you want to add additional data, you need to create a model class for your user and then store it in your Firebase database.

You model class should look like this:

```<code>public class User {
    String name, gender, emailAddress;
    int age;

    public User(String name, String gender, String emailAddress, int age) {
        this.name = name;
        this.gender = gender;
        this.emailAddress = emailAddress;
        this.age = age;
    }

    public String getName() {return name;}
    public void setName(String name) {this.name = name;}

    public String getGender() {return gender;}
    public void setGender(String gender) {this.gender = gender;}

    public String getEmailAddress() {return emailAddress;}
    public void setEmailAddress(String emailAddress) {this.emailAddress = emailAddress;}

    public int getAge() {return age;}
    public void setAge(int age) {this.age = age;}
}
</code>```

Body:
So far I'm really impressed with Firebase. But I would like to know how would I go about customizing my user email authentication. I would like to add the following fields: Age and Gender for users to fill out when registering.

here's my SignUpActivity.java.

public class SignUpActivity extends AppCompatActivity {
private EditText inputEmail, inputPassword, signupInputUsername, signupInputAge;
private Button btnLinkLogin, btnSignUp, btnResetPassword;
private ProgressBar progressBar;
private FirebaseAuth auth;
private Spinner sexSpinner;
String defaultTextForSpinner = "Sex";
String[] arrayForSpinner = {"Male", "Female"};

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

    //Get Firebase auth instance
    auth = FirebaseAuth.getInstance();

    inputEmail = (EditText) findViewById(R.id.signup_input_email);
    signupInputUsername = (EditText) findViewById(R.id.signup_input_username);
    inputPassword = (EditText) findViewById(R.id.signup_input_password);
    signupInputAge = (EditText) findViewById(R.id.signup_input_birthday);
    sexSpinner = (Spinner)findViewById(R.id.spinner);
    sexSpinner.setAdapter(new CustomSpinnerAdapter(this, R.layout.spinner_row, arrayForSpinner, defaultTextForSpinner));

    btnSignUp = (Button) findViewById(R.id.btnSignUp2);
    btnLinkLogin = (Button) findViewById(R.id.btnorlogin);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);
    EditText edittext = (EditText) findViewById(R.id.signup_input_birthday);

    edittext.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            //To show current date in the datepicker
            Calendar mcurrentDate = Calendar.getInstance();
            int mYear = mcurrentDate.get(Calendar.YEAR);
            int mMonth = mcurrentDate.get(Calendar.MONTH);
            int mDay = mcurrentDate.get(Calendar.DAY_OF_MONTH);

            DatePickerDialog mDatePicker=new DatePickerDialog(SignUpActivity.this, new DatePickerDialog.OnDateSetListener() {
                public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday) {
                    // TODO Auto-generated method stub
                /*      Your code   to get date and time    */
                }
            },mYear, mMonth, mDay);
            mDatePicker.setTitle("Select birthday");
            mDatePicker.show();  }
    });

    btnSignUp.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String email = inputEmail.getText().toString().trim();
            String password = inputPassword.getText().toString().trim();

            if (TextUtils.isEmpty(email)) {
                Toast.makeText(getApplicationContext(), "Enter email address.", Toast.LENGTH_SHORT).show();
                return;
            }

            if (TextUtils.isEmpty(password)) {
                Toast.makeText(getApplicationContext(), "Enter password.", Toast.LENGTH_SHORT).show();
                return;
            }

            if (password.length() < 6) {
                Toast.makeText(getApplicationContext(), "Password too short, enter minimum 6 characters.", Toast.LENGTH_SHORT).show();
                return;
            }

            progressBar.setVisibility(View.VISIBLE);
            //create user
            auth.createUserWithEmailAndPassword(email, password)
                    .addOnCompleteListener(SignUpActivity.this, new OnCompleteListener<AuthResult>() {
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {
                            Toast.makeText(SignUpActivity.this, "createUserWithEmail:onComplete:" + task.isSuccessful(), Toast.LENGTH_SHORT).show();
                            progressBar.setVisibility(View.GONE);
                            // If sign in fails, display a message to the user. If sign in succeeds
                            // the auth state listener will be notified and logic to handle the
                            // signed in user can be handled in the listener.
                            if (!task.isSuccessful()) {
                                Toast.makeText(SignUpActivity.this, "Authentication failed." + task.getException(),
                                        Toast.LENGTH_SHORT).show();
                            } else {
                                startActivity(new Intent(SignUpActivity.this, MainActivity.class));
                                finish();
                            }
                        }
                    });

        }
    });
}

@Override
protected void onResume() {
    super.onResume();
    progressBar.setVisibility(View.GONE);
}

public class CustomSpinnerAdapter extends ArrayAdapter<String> {

    Context context;
    String[] objects;
    String firstElement;
    boolean isFirstTime;

    public CustomSpinnerAdapter(Context context, int textViewResourceId, String[] objects, String defaultText) {
        super(context, textViewResourceId, objects);
        this.context = context;
        this.objects = objects;
        this.isFirstTime = true;
        setDefaultText(defaultText);
    }

    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {
        if(isFirstTime) {
            objects[0] = firstElement;
            isFirstTime = false;
        }
        return getCustomView(position, convertView, parent);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        notifyDataSetChanged();
        return getCustomView(position, convertView, parent);
    }

    public void setDefaultText(String defaultText) {
        this.firstElement = objects[0];
        objects[0] = defaultText;
    }

    public View getCustomView(int position, View convertView, ViewGroup parent) {

        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View row = inflater.inflate(R.layout.spinner_row, parent, false);
        TextView label = (TextView) row.findViewById(R.id.spinner_text);
        label.setText(objects[position]);

        return row;
    }

}

Body:
When you are using Firebase authentication with user and password, the only data that you can get after authentication  is that data that you get from FirebaseUser object. As you probably see, there also a couple of methods that can help you get the data easier, like: getEmail(), getDisplayName(), getPhotoUrl() and so on.

Unfortunately, you cannot add additional data like age and gender to the FirebaseUser object. If you want to add additional data, you need to create a model class for your user and then store it in your Firebase database.

You model class should look like this:

public class User {
    String name, gender, emailAddress;
    int age;

    public User(String name, String gender, String emailAddress, int age) {
        this.name = name;
        this.gender = gender;
        this.emailAddress = emailAddress;
        this.age = age;
    }

    public String getName() {return name;}
    public void setName(String name) {this.name = name;}

    public String getGender() {return gender;}
    public void setGender(String gender) {this.gender = gender;}

    public String getEmailAddress() {return emailAddress;}
    public void setEmailAddress(String emailAddress) {this.emailAddress = emailAddress;}

    public int getAge() {return age;}
    public void setAge(int age) {this.age = age;}
}


问:
Java: How do I close a JFrame while opening another one?
My program starts with a picture with a textfield in a JFrame. I want when the user types start it closes the picture JFrame and opens another JFrame with the main program. I've tried

processEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));

on the Image frame but it closes all the windows.

答:
This post is a bit old but nevertheless.

If you initialize the form like that:

```<code>JFrame firstForm = new JFrame();

firstForm.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
firstForm.setSize(800, 600);
firstForm.setLocationRelativeTo(null);

firstForm.setVisible(true);
</code>```

And for instance create or open another form by a button:

```<code>JFrame secondForm = new JFrame();

secondForm.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
secondForm.setSize(800, 600);
secondForm.setLocationRelativeTo(null);

secondForm.setVisible(true);

this.dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
</code>```

This will dispose and destroy the first window without exiting the program.

The key is to set setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE).

It also raises the events (I've tested it with the WindowClosing event).

Body:
This post is a bit old but nevertheless.

If you initialize the form like that:

JFrame firstForm = new JFrame();

firstForm.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
firstForm.setSize(800, 600);
firstForm.setLocationRelativeTo(null);

firstForm.setVisible(true);

And for instance create or open another form by a button:

JFrame secondForm = new JFrame();

secondForm.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
secondForm.setSize(800, 600);
secondForm.setLocationRelativeTo(null);

secondForm.setVisible(true);

this.dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));

This will dispose and destroy the first window without exiting the program.

The key is to set setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE).

It also raises the events (I've tested it with the WindowClosing event).


问:
Sum and Average gives incorrect output
I have this code for calculating sum and average, but it gives me wrong calculations. Do you have any idea why?</p>

```<code>import java.util.Scanner;

public class SumAndAverage {
   public static void main(String args[]) {
       Scanner input = new Scanner(System.in);

       System.out.print("Enter a lower bound then an upper bound:");

       double sum = 0;
       double average;
       int lowerbound = input.nextInt();
       int upperbound = input.nextInt();

       System.out.println("The upper bound " + upperbound);

       for(int number = lowerbound; number <= upperbound; number++) {
           sum += number;
       }

       average = sum/upperbound;
       System.out.println("The sum is " +sum);
       System.out.println("The average is " + average);
   }
}
</code>```

答:
To get the correct average you must divide the total sum by the number of elements.

Therefore the average is not:

```<code>average = sum/upperbound;
</code>```

It's:

```<code>average = sum/(upperbound-lowerbound+1);
</code>```

Title: Sum and Average gives incorrect output

Body:
I have this code for calculating sum and average, but it gives me wrong calculations. Do you have any idea why?

import java.util.Scanner;

public class SumAndAverage {
   public static void main(String args[]) {
       Scanner input = new Scanner(System.in);

       System.out.print("Enter a lower bound then an upper bound:");

       double sum = 0;
       double average;
       int lowerbound = input.nextInt();
       int upperbound = input.nextInt();

       System.out.println("The upper bound " + upperbound);

       for(int number = lowerbound; number <= upperbound; number++) {
           sum += number;
       }

       average = sum/upperbound;
       System.out.println("The sum is " +sum);
       System.out.println("The average is " + average);
   }
}

Body:
To get the correct average you must divide the total sum by the number of elements.

Therefore the average is not:

average = sum/upperbound;

It's:

average = sum/(upperbound-lowerbound+1);


问:
Implications of using multiple interactive popup windows
I'm coming up with the idea of detaching elements onto popup windows. Make a popup with window.open(), set up some elements in that document and add event listeners to serve the original purpose, but as a popup window component. All of this works, and it seems that the created window is handled by the same thread.

Is this "technique" bug-prone by any chance? I.g: If I create a canvas in the popup window and get a WebGL context from it, will it work flawlessly? If I set a bunch of event listeners there, will I get callbacks from them without any delay?

I couldn't do my research on this one because almost no one does this. Through my life, I've seen many sites use popup windows for user inputs but not for interactive or real timey stuff. I'm building a web app that's complex that utilising multiple monitors would benefit in user experience. You know, at least I know how painful it is to have two monitors and be unable to use both of them because all the component of the app is cramped in a single window. Just imagine using an MDI version of Photoshop where all the toolbox is within the MDI area and you can't get them out of the app window. A web page is exactly that.

答:
Although this is non-conventional it definitely seems to suit the requirement you mentioned. I don't see any issues when it comes to the browser support for handling rendition or communication across the windows, it's just that you will need to be more careful with your code. Something like make frequent checks in case user has closed one of your pop-ups(or register a window close callback so that you can make necessary adjustments).

Eventing across the windows should also be fine. Refer http://help.dottoro.com/ljrwrqew.php which has exactly same example of attaching the event callback from one window to another.

Another good read is http://www.infimum.dk/HTML/JSwindows.html


问:
Centering the navbar links
I have tried most of the approach, but I'm unable to center align the links in my navbar.

.navbar-nav {
  margin: 30px 20px !important;
}

a {
  /* color: #fff !important;*/
  font-family: 'Caesar Dressing';
  font-size: 18px;
  padding: 10px 30px !important;
}

a:hover {
  border: 2px solid #fff !important;
  background-color: transparent !important;
}

.active {
  border: 2px solid #fff !important;
  background-color: transparent !important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<body>
  <div class="container-fluid bg">
    <nav class="navbar">
      <div class="container-fluid">
        <ul class="nav navbar-nav">
          <li class="active">Home</li>
          <li>About</li>
          <li>Education</li>
          <li>Contact</li>
        </ul>
      </div>
    </nav>
  </div>
</body></code>```

this is what I'm getting

But I want all the 4 links to be vertically centered on the screen

答:
Just add text-center class with the container-fluid</p>

```<code><body>
  <div class="container-fluid bg">
    <nav class="navbar">
      <div class="container-fluid text-center">
        <ul class="nav navbar-nav">
          <li class="active"><a href="#">Home</a></li>
          <li><a href="#">About</a></li>
          <li><a href="#">Education</a></li>
          <li><a href="#">Contact</a></li>
        </ul>
      </div>
    </nav>
  </div>
</body>
</code>```

Title: Centering the navbar links

Body:
I have tried most of the approach, but I'm unable to center align the links in my navbar.

.navbar-nav {
  margin: 30px 20px !important;
}

a {
  /* color: #fff !important;*/
  font-family: 'Caesar Dressing';
  font-size: 18px;
  padding: 10px 30px !important;
}

a:hover {
  border: 2px solid #fff !important;
  background-color: transparent !important;
}

.active {
  border: 2px solid #fff !important;
  background-color: transparent !important;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

Home

About

Education

Contact

this is what I'm getting

But I want all the 4 links to be vertically centered on the screen

Body:
Just add text-center class with the container-fluid

<body>
  <div class="container-fluid bg">
    <nav class="navbar">
      <div class="container-fluid text-center">
        <ul class="nav navbar-nav">
          <li class="active"><a href="#">Home</a></li>
          <li><a href="#">About</a></li>
          <li><a href="#">Education</a></li>
          <li><a href="#">Contact</a></li>
        </ul>
      </div>
    </nav>
  </div>
</body>


问:
Openshift online v3 - build Red Hat image (is Docker EE needed?)
I want to build a custom image to use on openshift online v3. Based on rhel 7. On the install page on docker.com it becomes clear that you will need Docker Enterprise Edition to install docker on rhel 7. Is it possible through a tool or workaround to build a docker image based on rhel7, without buying Docker Enterprise Edition?</p>

答:
No Docker EE required, just install the regular docker package from RHEL repos, and you're fine. See also access.redhat.com/solutions/3092401

I enabled the repos:

```<code>subscription-manager repos --enable=rhel-7-server-rpms
subscription-manager repos --enable=rhel-7-server-extras-rpms
subscription-manager repos --enable=rhel-7-server-optional-rpms
</code>```

Then I installed docker with yum install docker and i could use the red hat images. Thank you @GrahamDumpleton!

Body:
No Docker EE required, just install the regular docker package from RHEL repos, and you're fine. See also access.redhat.com/solutions/3092401

I enabled the repos:

subscription-manager repos --enable=rhel-7-server-rpms
subscription-manager repos --enable=rhel-7-server-extras-rpms
subscription-manager repos --enable=rhel-7-server-optional-rpms

Then I installed docker with yum install docker and i could use the red hat images. Thank you @GrahamDumpleton!


问:
What is the proper usage of Bundler groups in Rails 3 applications
I'm finding a disconnect between the description of how Bundler groups are used in Rails and what I see in examples of Bundler groups.

Supposedly, Rails normally loads gems from the default group as well as the group with the same name as the environment.  I commonly see examples, however, that seem to just put things in arbitrarily-named groups, and somehow, they just work.  So what's the real story, or what am I missing?

This example ( http://www.jonathanspies.com/posts/7-Rails-3-and-Shoulda ) for instance, says to list the 'shoulda' gem in a :shoulda group, and says that this works.  The environments that would need this, however, would be "test", and perhaps "development".  What causes gems in the "shoulda" group to be loaded?

In other examples such as http://comments.gmane.org/gmane.comp.programming.tools.cucumber/2691, I see cucumber-rails and related gems being placed into the :test group, but Cucumber tasks run with the "cucumber" environment, so again, how would the gems be loaded when they are needed?

答:
You will see at http://www.jonathanspies.com/posts/7-Rails-3-and-Shoulda they are also saying:

```<code>In test/test_helper.rb add:
Bundler.require(:shoulda)
</code>```

Which requires the shoulda group.

Body:
You will see at http://www.jonathanspies.com/posts/7-Rails-3-and-Shoulda they are also saying:

In test/test_helper.rb add:
Bundler.require(:shoulda)

Which requires the shoulda group.


问:
Highlighting HTML element on mouse hover canvas shape using canvas shape name
I'm having some problems with my javascript canvas application, where I try to change the background color of an html element outside the canvas area when mouse the mouse cursor is over a canvas shape. I'm using konva library.

What I'm trying to do in code is to target the html side text class and colorize its background when mouse cursor is over canvas element shape building. Moving to different buildings it highlights different text elements to show what areas are in that building. When cursors leaves the canvas building area and is not on any other building it highlights no text elements. Its like an interactive map.

So what I'm asking is, how can I highlight text element on html side when hovering over canvas shape then stop highlighting when leaving the canvas shape while using konva library?

    var stage = new Konva.Stage({
      container: 'container',
      width: 600,
      height: 800
    });

var layer = new Konva.Layer();

//just few buildings for example
var shapes = [];

shapes.push({
    points: [117,188,218,188,218,218,137,218,137,225,117,225],
    name: "Building-A",
    link: "a-building-link",
});

shapes.push({
    points: [230,185,255,185,255,310,250,310,250,318,237,318,237,310,230,310],
    name: "Building-B",
    link: "b-building-link",
});

shapes.push({
    points: [261,134,367,134,367,152,261,152],
    name: "Building-C",
    link: "c-building-link",
});

for (var i = 0; i < shapes.length; i++) {
    var s = shapes[i];
    //var links = document.getElementsByClassName(s.link);
   var poly = new Konva.Line({
  points: s.points,
      fill: 'rgba(255,0,0,0.2)',
       stroke: 'black',
       strokeWidth: 3,
       closed : true,
        name: s.link,
        opacity: 0
            });

            poly.on('mouseover', function () {
                this.opacity(1);
                layer.draw();
                //Some things I tried to get this working
                //for (var i = 0; i < links.length; i++) {
                //var item = links[i];
                    //item.style.backgroundColor = "#ffcc00";
               //}
                /////////////////
                //var item = this.name;
                //item.style.backgroundColor = "#ffcc00";
                ////////////////
                //document.getElementsByClassName(this.name).style.backgroundColor = "#ffcc00";
                ///////////////
                //highlight_target = this.name;
                ///////////////
                //document.getElementsByClassName(${this.name}).style.backgroundColor = "#ffcc00";
                ///////////////
                //document.getElementsByClassName(s.name).style.backgroundColor = "#ffcc00";
            });

            poly.on('mouseout', function () {
                this.opacity(0);
                layer.draw();
                //Some things I tried to get this working
               //for (var i = 0; i < links.length; i++) {
                    //var item = links[i];
                    //item.style.backgroundColor = "";
               //}
                /////////////
                //var item = this.name;
                //item.style.backgroundColor = "";
                /////////////
                //document.getElementsByClassName(this.name).style.backgroundColor = "";
                /////////////
                //highlight_target = "";
                /////////////
                //document.getElementsByClassName(${this.name }).style.backgroundColor = "";
                /////////////
                //document.getElementsByClassName(s.name).style.backgroundColor = "";
            });

    layer.add(poly);
}

stage.add(layer);```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
  <div id="container"></div>
  <div class="textlink a-building-link b-building-link">
                <span>Place 1</span>
                <span>A, B</span>
                <span>1</span>
            </div>
            <div class="textlink c-building-link">
                <span>Place 4 and 5</span>
                <span>C</span>
                <span>3</span>
            </div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="https://cdn.rawgit.com/konvajs/konva/1.7.6/konva.min.js"></script>
    <script type="text/javascript" src="test.js"></script>

</body>
</html></code>```

Thanks for any help.

答:
You were very close. To get the name of the shape you need to use .name(). After that it looks like some of your code would have worked.

I moved the building shapes layer up the page and put the text at the top in the snippet so that it is more clear what is going on for other future readers. Additionally, since Konvajs relies on jquery being present, you can use the handy jquery selector mechanism to access your test elements. This is not critical to the solution.

var stage = new Konva.Stage({
      container: 'container',
      width: 600,
      height: 400
    });

var layer = new Konva.Layer();

//just few buildings for example
var shapes = [];

shapes.push({
    points: [117,188,218,188,218,218,137,218,137,225,117,225],
    name: "Building-A",
    link: "a-building-link",
});

shapes.push({
    points: [230,185,255,185,255,310,250,310,250,318,237,318,237,310,230,310],
    name: "Building-B",
    link: "b-building-link",
});

shapes.push({
    points: [261,134,367,134,367,152,261,152],
    name: "Building-C",
    link: "c-building-link",
});

for (var i = 0; i < shapes.length; i++) {
    var s = shapes[i];
    //var links = document.getElementsByClassName(s.link);
   var poly = new Konva.Line({
  points: s.points,
      fill: 'rgba(255,0,0,0.2)',
       stroke: 'black',
       strokeWidth: 3,
       closed : true,
        name: s.link,
        opacity: 0.5
            });

            poly.on('mouseover', function () {
                this.opacity(1);
                layer.draw();

                // use name() to ge the name. I then use the name as a jquery selector.
                $('.' +this.name()).css({ backgroundColor: "#ffcc00"});
            });

            poly.on('mouseout', function () {
                this.opacity(0.5);
                layer.draw();
                $('.' +this.name()).css({ backgroundColor: "transparent"});
            });

    layer.add(poly);
    layer.move({x:0, y:-40}) // make layer nearer the top of page for SO.
    stage.draw();
}

stage.add(layer);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
  <div class="textlink a-building-link b-building-link">
                <span>Place 1</span>
                <span>A, B</span>
                <span>1</span>
            </div>
            <div class="textlink c-building-link">
                <span>Place 4 and 5</span>
                <span>C</span>
                <span>3</span>
            </div>
  <div id="container"></div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="https://cdn.rawgit.com/konvajs/konva/1.7.6/konva.min.js"></script>
    <script type="text/javascript" src="test.js"></script>

</body>
</html></code>```

Body:
I'm having some problems with my javascript canvas application, where I try to change the background color of an html element outside the canvas area when mouse the mouse cursor is over a canvas shape. I'm using konva library.

What I'm trying to do in code is to target the html side text class and colorize its background when mouse cursor is over canvas element shape building. Moving to different buildings it highlights different text elements to show what areas are in that building. When cursors leaves the canvas building area and is not on any other building it highlights no text elements. Its like an interactive map.

So what I'm asking is, how can I highlight text element on html side when hovering over canvas shape then stop highlighting when leaving the canvas shape while using konva library?

    var stage = new Konva.Stage({
      container: 'container',
      width: 600,
      height: 800
    });

var layer = new Konva.Layer();

//just few buildings for example
var shapes = [];

shapes.push({
    points: [117,188,218,188,218,218,137,218,137,225,117,225],
    name: "Building-A",
    link: "a-building-link",
});

shapes.push({
    points: [230,185,255,185,255,310,250,310,250,318,237,318,237,310,230,310],
    name: "Building-B",
    link: "b-building-link",
});

shapes.push({
    points: [261,134,367,134,367,152,261,152],
    name: "Building-C",
    link: "c-building-link",
});

for (var i = 0; i < shapes.length; i++) {
    var s = shapes[i];
    //var links = document.getElementsByClassName(s.link);
   var poly = new Konva.Line({
  points: s.points,
      fill: 'rgba(255,0,0,0.2)',
       stroke: 'black',
       strokeWidth: 3,
       closed : true,
        name: s.link,
        opacity: 0
            });

            poly.on('mouseover', function () {
                this.opacity(1);
                layer.draw();
                //Some things I tried to get this working
                //for (var i = 0; i < links.length; i++) {
                //var item = links[i];
                    //item.style.backgroundColor = "#ffcc00";
               //}
                /////////////////
                //var item = this.name;
                //item.style.backgroundColor = "#ffcc00";
                ////////////////
                //document.getElementsByClassName(this.name).style.backgroundColor = "#ffcc00";
                ///////////////
                //highlight_target = this.name;
                ///////////////
                //document.getElementsByClassName(${this.name}).style.backgroundColor = "#ffcc00";
                ///////////////
                //document.getElementsByClassName(s.name).style.backgroundColor = "#ffcc00";
            });

            poly.on('mouseout', function () {
                this.opacity(0);
                layer.draw();
                //Some things I tried to get this working
               //for (var i = 0; i < links.length; i++) {
                    //var item = links[i];
                    //item.style.backgroundColor = "";
               //}
                /////////////
                //var item = this.name;
                //item.style.backgroundColor = "";
                /////////////
                //document.getElementsByClassName(this.name).style.backgroundColor = "";
                /////////////
                //highlight_target = "";
                /////////////
                //document.getElementsByClassName(${this.name }).style.backgroundColor = "";
                /////////////
                //document.getElementsByClassName(s.name).style.backgroundColor = "";
            });

    layer.add(poly);
}

stage.add(layer);

  <!DOCTYPE html>

    <meta charset="utf-8" />
    <title></title>

                Place 1
                A, B
                1

                Place 4 and 5
                C
                3

Thanks for any help.

Body:
You were very close. To get the name of the shape you need to use .name(). After that it looks like some of your code would have worked.

I moved the building shapes layer up the page and put the text at the top in the snippet so that it is more clear what is going on for other future readers. Additionally, since Konvajs relies on jquery being present, you can use the handy jquery selector mechanism to access your test elements. This is not critical to the solution.

var stage = new Konva.Stage({
      container: 'container',
      width: 600,
      height: 400
    });

var layer = new Konva.Layer();

//just few buildings for example
var shapes = [];

shapes.push({
    points: [117,188,218,188,218,218,137,218,137,225,117,225],
    name: "Building-A",
    link: "a-building-link",
});

shapes.push({
    points: [230,185,255,185,255,310,250,310,250,318,237,318,237,310,230,310],
    name: "Building-B",
    link: "b-building-link",
});

shapes.push({
    points: [261,134,367,134,367,152,261,152],
    name: "Building-C",
    link: "c-building-link",
});

for (var i = 0; i < shapes.length; i++) {
    var s = shapes[i];
    //var links = document.getElementsByClassName(s.link);
   var poly = new Konva.Line({
  points: s.points,
      fill: 'rgba(255,0,0,0.2)',
       stroke: 'black',
       strokeWidth: 3,
       closed : true,
        name: s.link,
        opacity: 0.5
            });

            poly.on('mouseover', function () {
                this.opacity(1);
                layer.draw();

                // use name() to ge the name. I then use the name as a jquery selector.
                $('.' +this.name()).css({ backgroundColor: "#ffcc00"});
            });

            poly.on('mouseout', function () {
                this.opacity(0.5);
                layer.draw();
                $('.' +this.name()).css({ backgroundColor: "transparent"});
            });

    layer.add(poly);
    layer.move({x:0, y:-40}) // make layer nearer the top of page for SO.
    stage.draw();
}

stage.add(layer);

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
  <div class="textlink a-building-link b-building-link">
                <span>Place 1</span>
                <span>A, B</span>
                <span>1</span>
            </div>
            <div class="textlink c-building-link">
                <span>Place 4 and 5</span>
                <span>C</span>
                <span>3</span>
            </div>
  <div id="container"></div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="https://cdn.rawgit.com/konvajs/konva/1.7.6/konva.min.js"></script>
    <script type="text/javascript" src="test.js"></script>

</body>
</html>