问:
Performing Authentication on Routes with react-router-v4
I'm trying to write Authentication checking for my DashBoard. But the function itself is not getting called. Can anyone give me some solution for this? I'm developing in ReactJs.

This is the Route part :

```<code> <Router>
            <div>
              <Route exact path={"/"} component={Home} />
              <Route path={"/SignUp"} component={SignUp} />
              <Route path={"/SignIn"} component={SignIn} />
              <Route path={"/Dashboard"} component={Dashboard} onEnter={this.requireAuth} />
            </div>
          </Router>
</code>```

This is the function :

```<code>  requireAuth (nextState, replace) {
    console.log("?????????????",this.state.getToken);
    if(!this.state.getToken) {
      replace({pathname: '/'});
    }
  }
</code>```

答:
In react-router v4, you can make use of render prop to Route along with the lifecycle methods to replace the onEnter functionality existing in react-router v3.

See this answer for more details:

onEnter prop in react-router v4

However since all you want to do is authentication in the onEnter prop, you could easily create a HOC that does that

```<code>const RequireAuth = (Component) => {

    return class App extends Component {

        componentWillMount() {
            const getToken = localStorage.getItem('token');
            if(!getToken) {
               this.props.history.replace({pathname: '/'});
            }
        }
        render() {
           return <Component {...this.props} />
        }
    }

}

export { RequireAuth }
</code>```

and use it like

```<code><Route path={"/Dashboard"} component={RequireAuth(Dashboard)}/>
</code>```

Edit: In case you need to make a network call to find if the use if authenticated of not, you would write the HOC like

```<code> const RequireAuth = (Component) => {

    return class App extends Component {
        state = {
            isAuthenticated: false,
            isLoading: true
        }

        componentDidMount() {
            AuthCall().then(() => {
                this.setState({isAuthenticated: true, isLoading: false});
            }).catch(() => {
                this.setState({isLoading: false});
            })
        }
        render() {
           const { isAuthenticated, isLoading } = this.state;
           if(isLoading) {
               return <div>Loading...</div>
           }
           if(!isAuthenticated) {
               return <Redirect to="/login" />
           }
           return <Component {...this.props} />
        }
    }

}

export { RequireAuth }
</code>```

Update:

In addition to the HOC, you can also go for the PrivateRoute component like

```<code>const PrivateRoute = ({component: Component, isAuthenticated, isLoading, ...rest }) => {
           if(isLoading) {
               return <div>Loading...</div>
           }
           if(!isAuthenticated) {
               return <Redirect to="/login" />
           }
           return <Component {...this.props} />
        }
    }
}

 export { PrivateRoute };
</code>```

and you can use it like

```<code>  class App extends Component {
        state = {
            isAuthenticated: false,
            isLoading: true
        }

        componentDidMount() {
            AuthCall().then(() => {
                this.setState({isAuthenticated: true, isLoading: false});
            }).catch(() => {
                this.setState({isLoading: false});
            })
        }
        render() {
           <Router>
              <div>
                  <Route exact path={"/"} component={Home} />
                  <Route path={"/SignUp"} component={SignUp} />
                  <Route path={"/SignIn"} component={SignIn} />
                  <PrivateRoute path={"/Dashboard"} component={Dashboard} isAuthenticated={this.state.isAuthenticated} isLoading={this.isLoading}/>
               </div>
           </Router>
        }
    }

</code>```

Body:
I'm trying to write Authentication checking for my DashBoard. But the function itself is not getting called. Can anyone give me some solution for this? I'm developing in ReactJs.

This is the Route part :

 <Router>

              <Route exact path={"/"} component={Home} />
              <Route path={"/SignUp"} component={SignUp} />
              <Route path={"/SignIn"} component={SignIn} />
              <Route path={"/Dashboard"} component={Dashboard} onEnter={this.requireAuth} />

          </Router>

This is the function :

  requireAuth (nextState, replace) {
    console.log("?????????????",this.state.getToken);
    if(!this.state.getToken) {
      replace({pathname: '/'});
    }
  }

Body:
In react-router v4, you can make use of render prop to Route along with the lifecycle methods to replace the onEnter functionality existing in react-router v3.

See this answer for more details:

onEnter prop in react-router v4

However since all you want to do is authentication in the onEnter prop, you could easily create a HOC that does that

const RequireAuth = (Component) => {

    return class App extends Component {

        componentWillMount() {
            const getToken = localStorage.getItem('token');
            if(!getToken) {
               this.props.history.replace({pathname: '/'});
            }
        }
        render() {
           return <Component {...this.props} />
        }
    }

}

export { RequireAuth }

and use it like

<Route path={"/Dashboard"} component={RequireAuth(Dashboard)}/>

Edit: In case you need to make a network call to find if the use if authenticated of not, you would write the HOC like

 const RequireAuth = (Component) => {

    return class App extends Component {
        state = {
            isAuthenticated: false,
            isLoading: true
        }

        componentDidMount() {
            AuthCall().then(() => {
                this.setState({isAuthenticated: true, isLoading: false});
            }).catch(() => {
                this.setState({isLoading: false});
            })
        }
        render() {
           const { isAuthenticated, isLoading } = this.state;
           if(isLoading) {
               return <div>Loading...</div>
           }
           if(!isAuthenticated) {
               return <Redirect to="/login" />
           }
           return <Component {...this.props} />
        }
    }

}

export { RequireAuth }

Update:

In addition to the HOC, you can also go for the PrivateRoute component like

const PrivateRoute = ({component: Component, isAuthenticated, isLoading, ...rest }) => {
           if(isLoading) {
               return <div>Loading...</div>
           }
           if(!isAuthenticated) {
               return <Redirect to="/login" />
           }
           return <Component {...this.props} />
        }
    }
}

 export { PrivateRoute };

and you can use it like

  class App extends Component {
        state = {
            isAuthenticated: false,
            isLoading: true
        }

        componentDidMount() {
            AuthCall().then(() => {
                this.setState({isAuthenticated: true, isLoading: false});
            }).catch(() => {
                this.setState({isLoading: false});
            })
        }
        render() {
           <Router>
              <div>
                  <Route exact path={"/"} component={Home} />
                  <Route path={"/SignUp"} component={SignUp} />
                  <Route path={"/SignIn"} component={SignIn} />
                  <PrivateRoute path={"/Dashboard"} component={Dashboard} isAuthenticated={this.state.isAuthenticated} isLoading={this.isLoading}/>
               </div>
           </Router>
        }
    }


来源: stackexchange

问:
Allure Results Not Showing DisplayName
I'm using Allure2 in Java with Maven, Junit4, Appium, and Idea as my editor.

Here is my pom.xml:

```<code>    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    <dependency>
        <groupId>io.qameta.allure</groupId>
        <artifactId>allure-junit4</artifactId>
        <version>2.0-BETA19</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>io.appium</groupId>
        <artifactId>java-client</artifactId>
        <version>5.0.4</version>
        <exclusions>
            <exclusion>
                <groupId>com.google.guava</groupId>
                <artifactId>guava</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>21.0</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.5</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.5</version>
    </dependency>

<plugin>
            <groupId>io.qameta.allure</groupId>
            <artifactId>allure-maven</artifactId>
            <version>2.9</version>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>2.6</version>
            <executions>
                <execution>
                    <goals>
                        <goal>test-jar</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>2.10</version>
            <executions>
                <execution>
                    <id>copy-dependencies</id>
                    <phase>package</phase>
                    <goals>
                        <goal>copy-dependencies</goal>
                    </goals>
                    <configuration>
                        <outputDirectory>${project.build.directory}/dependency-jars/</outputDirectory>
                    </configuration>
                </execution>
            </executions>
        </plugin>
</code>```

Here is a test:

```<code>@DisplayName("It Should Choose An Assets Under 5k")
@Severity(SeverityLevel.NORMAL)
@Test(timeout = tenMinutes)
public void ItShouldChooseUnder5k(){
</code>```

I don't see the DisplayNames in the report in the Report I get:

ItShouldChooseUnder5k

I also get:

ALLURE REPORT UNKNOWN
unknown - unknown (Unknown)

Any ideas why my report is unknown or the DisplayNames aren't showing up?
It also ignores my Severity Flags.

Should the DisplayName be in the xml result?

答: Issue turned out to be I needed to call allure server on the allure-results dir and not the target/surefire-reports</p>

ContentLicense: CC BY-SA 3.0

Title: Allure Results Not Showing DisplayName

Body:
I'm using Allure2 in Java with Maven, Junit4, Appium, and Idea as my editor.

Here is my pom.xml:

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    <dependency>
        <groupId>io.qameta.allure</groupId>
        <artifactId>allure-junit4</artifactId>
        <version>2.0-BETA19</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>io.appium</groupId>
        <artifactId>java-client</artifactId>
        <version>5.0.4</version>
        <exclusions>
            <exclusion>
                <groupId>com.google.guava</groupId>
                <artifactId>guava</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>21.0</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.5</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.5</version>
    </dependency>

<plugin>
            <groupId>io.qameta.allure</groupId>
            <artifactId>allure-maven</artifactId>
            <version>2.9</version>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>2.6</version>
            <executions>
                <execution>
                    <goals>
                        <goal>test-jar</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>2.10</version>
            <executions>
                <execution>
                    <id>copy-dependencies</id>
                    <phase>package</phase>
                    <goals>
                        <goal>copy-dependencies</goal>
                    </goals>
                    <configuration>
                        <outputDirectory>${project.build.directory}/dependency-jars/</outputDirectory>
                    </configuration>
                </execution>
            </executions>
        </plugin>

Here is a test:

@DisplayName("It Should Choose An Assets Under 5k")
@Severity(SeverityLevel.NORMAL)
@Test(timeout = tenMinutes)
public void ItShouldChooseUnder5k(){

I don't see the DisplayNames in the report in the Report I get:

ItShouldChooseUnder5k

I also get:

ALLURE REPORT UNKNOWN
unknown - unknown (Unknown)

Any ideas why my report is unknown or the DisplayNames aren't showing up?
It also ignores my Severity Flags.

Should the DisplayName be in the xml result?


问:
Adding a comment in the middle of a call chain
How can I add a comment in the middle of a call chain?

I see that Ruby throws parse error when I try to add a comment in the middle of a call chain like:

```<code>Tag.joins(:taggings)
   # Wanted to add comment here cause it's long
   # and takes multiple lines
   .where(...)
   .where(...)
   .where(...)
   # And here
   .group(...)
   .order(...)
</code>```

答:
Change to this structure:

```<code>Tag.joins(:taggings).
   # Comment 1
   # Comment 2
   where(...).
   where(...).
   where(...).
   # And here
   group(...).
   order(...)
</code>```

Method . Dot at end will instruct the parser that expression hasn't ended and logical method chain will arrive.

Body:
How can I add a comment in the middle of a call chain?

I see that Ruby throws parse error when I try to add a comment in the middle of a call chain like:

Tag.joins(:taggings)
   # Wanted to add comment here cause it's long
   # and takes multiple lines
   .where(...)
   .where(...)
   .where(...)
   # And here
   .group(...)
   .order(...)

Body:
Change to this structure:

Tag.joins(:taggings).
   # Comment 1
   # Comment 2
   where(...).
   where(...).
   where(...).
   # And here
   group(...).
   order(...)

Method . Dot at end will instruct the parser that expression hasn't ended and logical method chain will arrive.


问:
How to get current user using devise in rails without using authenticate! on the controller
I'm using devise with rails 3 and i'm trying to create a page which can be viewed by everyone (even those not signed up) but has additional functionality for people who are registered.

The problem is that when I call current_user there is no user because I haven't used the authenticate! filter on my controller, because I want unregistered users to be able to view it.

How do I sign in a user if they are in the session otherwise leaving it without a user?

答:
Not to nitpick, but it seems like both work in the same places, it is just that current_user isn't initialized if no user is signed in.

Here's a scrap of a line from a related idea, it's from a before_filter which prohibits users from editing items which don't belong to them

```<code>user_signed_in? && (@subscription.user_id == current_user.id || current_user.admin)
</code>```

You have to wrap the whole bit with an && on user_signed_in? though, or it will crash when no user is signed in.

ContentLicense: CC BY-SA 2.5

Body:
Not to nitpick, but it seems like both work in the same places, it is just that current_user isn't initialized if no user is signed in.

Here's a scrap of a line from a related idea, it's from a before_filter which prohibits users from editing items which don't belong to them

user_signed_in? && (@subscription.user_id == current_user.id || current_user.admin)

You have to wrap the whole bit with an && on user_signed_in? though, or it will crash when no user is signed in.


问:
How to export SQL Server data to Excel using VBA?
Currently I'm testing how to export data from SQL Server Management Studio to Excel for an upcoming project.

I looked up online and came upon a code as follows:

```<code>Function ImportSQLtoRange(ByVal conString As String, ByVal query As String, ByVal target As Range) As Integer

On Error Resume Next

' Object type and CreateObject function are used instead of ADODB.Connection,
' ADODB.Command for late binding without reference to
' Microsoft ActiveX Data Objects 2.x Library

' ADO API Reference
' http://msdn.microsoft.com/en-us/library/ms678086(v=VS.85).aspx

' Dim con As ADODB.Connection
Dim con As Object
Set con = CreateObject("ADODB.Connection")

con.ConnectionString = conString

' Dim cmd As ADODB.Command
Dim cmd As Object
Set cmd = CreateObject("ADODB.Command")

cmd.CommandText = query
cmd.CommandType = 1         ' adCmdText

' The Open method doesn't actually establish a connection to the server
' until a Recordset is opened on the Connection object
con.Open
cmd.ActiveConnection = con

' Dim rst As ADODB.Recordset
Dim rst As Object
Set rst = cmd.Execute

If rst Is Nothing Then
    con.Close
    Set con = Nothing

    ImportSQLtoRange = 1
    Exit Function
End If

Dim ws As Worksheet
Dim col As Integer

Set ws = target.Worksheet

' Column Names
For col = 0 To rst.Fields.Count - 1
    ws.Cells(target.row, target.Column + col).Value = rst.Fields(col).Name
Next
ws.Range(ws.Cells(target.row, target.Column), ws.Cells(target.row, target.Column + rst.Fields.Count)).Font.Bold = True

' Data from Recordset
ws.Cells(target.row + 1, target.Column).CopyFromRecordset rst

rst.Close
con.Close

Set rst = Nothing
Set cmd = Nothing
Set con = Nothing

ImportSQLtoRange = 0

End Function

Sub TestImportUsingADO()

Dim conString As String
conString = "data source = server name; initial catalog = database; uid = name; password = password"

Dim query As String
query = "my query goes here"

Dim target As Range
Set target = ThisWorkbook.Sheets(2).Cells(3, 2)

target.CurrentRegion.Clear

Select Case ImportSQLtoRange(conString, query, target)
    Case 1
        MsgBox "Import database data error", vbCritical
    Case Else
End Select

End Sub
</code>```

When I try to use the macro, I receive a message box as set in Case 1 in ImportSQLtoRange. But I'm not sure if that means that the code works and can access the query or this is an error message. If this shows that it does work how do I modify it so that it gives me the table I want based on my query?

Edit: Upon following Kazimierz Jawor suggestion, I commented on

```<code>On Error Resume Next
</code>```

Now I get an error as follows:

Clicking Debug show the error coming from

```<code>con.open
</code>```

What does that mean?

答:
Please try to use the below code

```<code>Dim conn As New ADODB.Connection
Dim conn As ADODB.Connection
Set conn = New ADODB.Connection
</code>```

Below is the example:

```<code> Sub GetDataFromADO()
'Declare variables'
    Set objMyConn = New ADODB.Connection
    Set objMyRecordset = New ADODB.Recordset
    Dim strSQL As String

'Open Connection'
    objMyConn.ConnectionString = "Provider=SQLOLEDB;Data Source=localhost;Initial Catalog=MyDatabase;User ID=abc;Password=abc;"
    objMyConn.Open

'Set and Excecute SQL Command'
    strSQL = "select * from myTable"

'Open Recordset'
    Set objMyRecordset.ActiveConnection = objMyConn
    objMyRecordset.Open strSQL

'Copy Data to Excel'
    Do until objMyRecordset.EOF //Test whether the current record is after the last record
          'Your Code
    Loop

End Sub
</code>```

Body:
Currently I'm testing how to export data from SQL Server Management Studio to Excel for an upcoming project.

I looked up online and came upon a code as follows:

Function ImportSQLtoRange(ByVal conString As String, ByVal query As String, ByVal target As Range) As Integer

On Error Resume Next

' Object type and CreateObject function are used instead of ADODB.Connection,
' ADODB.Command for late binding without reference to
' Microsoft ActiveX Data Objects 2.x Library

' ADO API Reference
' http://msdn.microsoft.com/en-us/library/ms678086(v=VS.85).aspx

' Dim con As ADODB.Connection
Dim con As Object
Set con = CreateObject("ADODB.Connection")

con.ConnectionString = conString

' Dim cmd As ADODB.Command
Dim cmd As Object
Set cmd = CreateObject("ADODB.Command")

cmd.CommandText = query
cmd.CommandType = 1         ' adCmdText

' The Open method doesn't actually establish a connection to the server
' until a Recordset is opened on the Connection object
con.Open
cmd.ActiveConnection = con

' Dim rst As ADODB.Recordset
Dim rst As Object
Set rst = cmd.Execute

If rst Is Nothing Then
    con.Close
    Set con = Nothing

    ImportSQLtoRange = 1
    Exit Function
End If

Dim ws As Worksheet
Dim col As Integer

Set ws = target.Worksheet

' Column Names
For col = 0 To rst.Fields.Count - 1
    ws.Cells(target.row, target.Column + col).Value = rst.Fields(col).Name
Next
ws.Range(ws.Cells(target.row, target.Column), ws.Cells(target.row, target.Column + rst.Fields.Count)).Font.Bold = True

' Data from Recordset
ws.Cells(target.row + 1, target.Column).CopyFromRecordset rst

rst.Close
con.Close

Set rst = Nothing
Set cmd = Nothing
Set con = Nothing

ImportSQLtoRange = 0

End Function

Sub TestImportUsingADO()

Dim conString As String
conString = "data source = server name; initial catalog = database; uid = name; password = password"

Dim query As String
query = "my query goes here"

Dim target As Range
Set target = ThisWorkbook.Sheets(2).Cells(3, 2)

target.CurrentRegion.Clear

Select Case ImportSQLtoRange(conString, query, target)
    Case 1
        MsgBox "Import database data error", vbCritical
    Case Else
End Select

End Sub

When I try to use the macro, I receive a message box as set in Case 1 in ImportSQLtoRange. But I'm not sure if that means that the code works and can access the query or this is an error message. If this shows that it does work how do I modify it so that it gives me the table I want based on my query?

Edit: Upon following Kazimierz Jawor suggestion, I commented on

On Error Resume Next

Now I get an error as follows:

Clicking Debug show the error coming from

con.open

What does that mean?

Body:
Please try to use the below code

Dim conn As New ADODB.Connection
Dim conn As ADODB.Connection
Set conn = New ADODB.Connection

Below is the example:

 Sub GetDataFromADO()
'Declare variables'
    Set objMyConn = New ADODB.Connection
    Set objMyRecordset = New ADODB.Recordset
    Dim strSQL As String

'Open Connection'
    objMyConn.ConnectionString = "Provider=SQLOLEDB;Data Source=localhost;Initial Catalog=MyDatabase;User ID=abc;Password=abc;"
    objMyConn.Open

'Set and Excecute SQL Command'
    strSQL = "select * from myTable"

'Open Recordset'
    Set objMyRecordset.ActiveConnection = objMyConn
    objMyRecordset.Open strSQL

'Copy Data to Excel'
    Do until objMyRecordset.EOF //Test whether the current record is after the last record
          'Your Code
    Loop

End Sub


问:
Relative links in Jekyll on Github Pages and localhost are not working correctly
I use Gulp to run Jekyll. My setup works fine on localhost, but when I introduce Github Pages relative links stop working. I use gulp-gh-pages npm package to push _site contents to gh-pages branch.

Contents of gulpfile.js related to Jekyll and Github Pages:

```<code>var browserSync  = require('browser-sync').create();
var gulp         = require('gulp');
var runSequence  = require('run-sequence');
var ghPages      = require('gulp-gh-pages');
var gutil        = require('gulp-util');
var run          = require('gulp-run');
var del          = require('del');

gulp.task('build:jekyll', function(callback) {
    var shellCommand = 'jekyll build --incremental';

    return gulp.src('')
        .pipe(run(shellCommand))
        .on('error', gutil.log);

    callback();
});

gulp.task('clean', function() {
    return del(['_site', 'assets']);
});

// [`build:scripts`, `build:styles`, `build:images`] is removed from the runSequence example for MVP
gulp.task('build:prod', function(callback) {
    return runSequence('clean', 'build:jekyll', callback)
    browserSync.reload();
});

gulp.task('deploy',['build:prod'], function(){
    return gulp.src('./_site/**/*')
        .pipe(ghPages());
});
</code>```

Contents of config.yml:

```<code>baseurl: /

collections:
  pages:
    output: true
    permalink: /:title/

exclude: ["_assets", "gulpfile.js", "node_modules", "package.json", "package-lock.json", ".jekyll-metadata"]
</code>```

Reference to assets:

```<code><link rel="stylesheet" href="{{ site.baseurl }}assets/styles/main.min.css">
</code>```

Front matter on every page inside _pages directory:

```<code>---
layout: page
title: Title
description: Awesome description
image: https://source.unsplash.com/random/?water
---
</code>```

Here is the link to my Github repository with full source code: https://github.com/alljamin/portfolio

How can I configure Gulp and Jekyll so all the relative links work both locally and on Github Pages?

答:
Try : "baseurl: /portfolio"

Generate url with {{site.baseurl}}/path/to/res or {{ "/path/to/res" | prepend: site.baseurl }}.

Body:
I use Gulp to run Jekyll. My setup works fine on localhost, but when I introduce Github Pages relative links stop working. I use gulp-gh-pages npm package to push _site contents to gh-pages branch.

Contents of gulpfile.js related to Jekyll and Github Pages:

var browserSync  = require('browser-sync').create();
var gulp         = require('gulp');
var runSequence  = require('run-sequence');
var ghPages      = require('gulp-gh-pages');
var gutil        = require('gulp-util');
var run          = require('gulp-run');
var del          = require('del');

gulp.task('build:jekyll', function(callback) {
    var shellCommand = 'jekyll build --incremental';

    return gulp.src('')
        .pipe(run(shellCommand))
        .on('error', gutil.log);

    callback();
});

gulp.task('clean', function() {
    return del(['_site', 'assets']);
});

// [`build:scripts`, `build:styles`, `build:images`] is removed from the runSequence example for MVP
gulp.task('build:prod', function(callback) {
    return runSequence('clean', 'build:jekyll', callback)
    browserSync.reload();
});

gulp.task('deploy',['build:prod'], function(){
    return gulp.src('./_site/**/*')
        .pipe(ghPages());
});

Contents of config.yml:

baseurl: /

collections:
  pages:
    output: true
    permalink: /:title/

exclude: ["_assets", "gulpfile.js", "node_modules", "package.json", "package-lock.json", ".jekyll-metadata"]

Reference to assets:

<link rel="stylesheet" href="{{ site.baseurl }}assets/styles/main.min.css">

Front matter on every page inside _pages directory:

---
layout: page
title: Title
description: Awesome description
image: https://source.unsplash.com/random/?water
---

Here is the link to my Github repository with full source code: https://github.com/alljamin/portfolio

How can I configure Gulp and Jekyll so all the relative links work both locally and on Github Pages?


问:
bootstrap 4 navbar fade in\out when scrolling in a rails app
I'm trying to figure out how to have a top navbar in bootstrap 4 and then when the user scrolls down a little on the page have the navbar fade in I can currently get the navbar to show up using the below script, however, it doesn't fade in it just immediately shows up very fast and awkwardly.

```<code><script>
$(document).scroll(function(e){
    var scrollTop = $(document).scrollTop();
    if(scrollTop > 200){

        $('.navbar').removeClass('static-top').addClass('fixed-top');

    } else {
        $('.navbar').removeClass('fixed-top').addClass('static-top');
    }
});
</script>

<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <a class="navbar-brand" href="#">Navbar</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>

  <div class="collapse navbar-collapse" id="navbarSupportedContent">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item active">
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Link</a>
      </li>
      <li class="nav-item dropdown">
        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          Dropdown
        </a>
        <div class="dropdown-menu" aria-labelledby="navbarDropdown">
          <a class="dropdown-item" href="#">Action</a>
          <a class="dropdown-item" href="#">Another action</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="#">Something else here</a>
        </div>
      </li>
      <li class="nav-item">
        <a class="nav-link disabled" href="#">Disabled</a>
      </li>
    </ul>
    <form class="form-inline my-2 my-lg-0">
      <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
      <button class="btn btn-outline-primary my-2 my-sm-0" type="submit">Search</button>
    </form>
  </div>
</nav><!--./nav-->
</code>```

I'm looking for a navbar effect like this http://bootstraplovers.com/assan-v3.6/classic-template/html/index.html

答:
```<code>$('.navbar').removeClass('static-top').addClass('fixed-top');
</code>```

before calling .removeClass() you need to call .toggle() or other similar jquery effects. Refer to the documentation

.toggle() would hide the navbar, so maybe you want to post your question in the relevant stackoverflow section (jquery), think about how you want to build this animation and search the jquery documentation...

Body:
I'm trying to figure out how to have a top navbar in bootstrap 4 and then when the user scrolls down a little on the page have the navbar fade in I can currently get the navbar to show up using the below script, however, it doesn't fade in it just immediately shows up very fast and awkwardly.

  Navbar
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

  </button>

        Home (current)

        Link

          Dropdown

          Action
          Another action

          Something else here

        Disabled

    <form class="form-inline my-2 my-lg-0">
      <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
      <button class="btn btn-outline-primary my-2 my-sm-0" type="submit">Search</button>
    </form>

I'm looking for a navbar effect like this http://bootstraplovers.com/assan-v3.6/classic-template/html/index.html

Body:
$('.navbar').removeClass('static-top').addClass('fixed-top');

before calling .removeClass() you need to call .toggle() or other similar jquery effects. Refer to the documentation

.toggle() would hide the navbar, so maybe you want to post your question in the relevant stackoverflow section (jquery), think about how you want to build this animation and search the jquery documentation...


问:
Issue with linking directly to my URL (https://)
I've just gotten an SSL cerificate and have redirected my site to display https:// rather than http:// using HTaccess:

```<code>RewriteEngine On

RewriteCond %{HTTPS} off
RewriteRule (.*) https://www.example.co.uk/%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</code>```

Before I used to link to my index like this:

```<code><a href="http://www.example.co.uk/">Home</a>
</code>```

And you would be taken to http://www.example.co.uk.

Now with the SSL I've changed it to this:

```<code><a href="https://www.example.co.uk/">Home</a>
</code>```

And it is taking me to https://www.example.co.uk/www.example.co.uk/.

Any idea why this is?

答:
This is what you need</p>

```<code><IfModule mod_rewrite.c>

    RewriteEngine On

    # Redirect HTTP to HTTPS automatically (only if not in localhost)
    RewriteCond %{HTTP_HOST} !=localhost
    RewriteCond %{HTTPS} off
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

</IfModule>
</code>```

Body:
I've just gotten an SSL cerificate and have redirected my site to display https:// rather than http:// using HTaccess:

RewriteEngine On

RewriteCond %{HTTPS} off
RewriteRule (.*) https://www.example.co.uk/%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Before I used to link to my index like this:

Home

And you would be taken to http://www.example.co.uk.

Now with the SSL I've changed it to this:

Home

And it is taking me to https://www.example.co.uk/www.example.co.uk/.

Any idea why this is?

Body:
This is what you need

<IfModule mod_rewrite.c>

    RewriteEngine On

    # Redirect HTTP to HTTPS automatically (only if not in localhost)
    RewriteCond %{HTTP_HOST} !=localhost
    RewriteCond %{HTTPS} off
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

</IfModule>


问:
PHP: Constants & Bitwise separator as default argument to a method
Im creating a class method and want to have a default argument value that contains constants:

```<code><?php
class mq_series_client{
    function get($message_options = array('Options' => MQSERIES_MQGMO_FAIL_IF_QUIESCING | MQSERIES_MQGMO_WAIT, 'WaitInterval' => 500)){

    }
}
</code>```

However I'm getting a Parse error:  syntax error, unexpected '|'

I could do this:

```<code><?php
class mq_series_client{
    function get(Array $message_options = null){
        if(!isset($message_options)){
           $message_options = array('Options' => MQSERIES_MQGMO_FAIL_IF_QUIESCING | MQSERIES_MQGMO_WAIT, 'WaitInterval' => 500);
        }
    }
}
</code>```

But it doesn't seem very clean. I wish the first way would work!

Is there a better "correct" way to do this?

答:
It looks like the first option is not valid, as according to this page:

The default value must be a constant
  expression, not (for example) a
  variable, a class member or a function
  call.

Experimenting a bit, it looks like expressions are not accepted, like:

```<code><?php
    function get($options = array('test' => 1+1)) {

    }
}
?>
</code>```

which chokes on the + -- presumably because it is not a “constant expression.“

Body:
Im creating a class method and want to have a default argument value that contains constants:

<?php
class mq_series_client{
    function get($message_options = array('Options' => MQSERIES_MQGMO_FAIL_IF_QUIESCING | MQSERIES_MQGMO_WAIT, 'WaitInterval' => 500)){

    }
}

However I'm getting a Parse error:  syntax error, unexpected '|'

I could do this:

<?php
class mq_series_client{
    function get(Array $message_options = null){
        if(!isset($message_options)){
           $message_options = array('Options' => MQSERIES_MQGMO_FAIL_IF_QUIESCING | MQSERIES_MQGMO_WAIT, 'WaitInterval' => 500);
        }
    }
}

But it doesn't seem very clean. I wish the first way would work!

Is there a better "correct" way to do this?

Body:
It looks like the first option is not valid, as according to this page:

The default value must be a constant
  expression, not (for example) a
  variable, a class member or a function
  call.

Experimenting a bit, it looks like expressions are not accepted, like:

<?php
    function get($options = array('test' => 1+1)) {

    }
}
?>

which chokes on the + -- presumably because it is not a “constant expression.“


问:
401 invalid_client when processing paypal payment using node SDK on production system
I have a weird situation going on, I always get a 401 invalid_client error when trying to make a payment on my production system using the node SDK.
The credentials are a 100% correct, mode property is set to live and this config works on localhost - I can process the payment with no issues. So sandbox works on production and localhost, live works only on localhost. ENV variables are exactly the same when I simulate live mode on localhost. The debug id I get from PayPal is bc930e48644c9. Does anyone have a clue what is going on here?</p>

答:
Issue already set:

https://github.com/paypal/PayPal-node-SDK/issues/320

Seems to occur after the v1.8.0 update of the node sdk. According to the description a rollback of the npm package to v1.7.1 seems to work.

EDIT: Just confirmed that by my self. Works.


问:
Allowing docker-in-docker on dc/os?
I am trying to schedule 'docker run' jobs using Airflow, on DC/OS. This requires the ability to start docker containers from within the docker container which contains Airflow. I am able to do this on OSX but just running:

```<code>docker run \
  -p 8080:8080 \
  -v /var/run/docker.sock:/var/run/docker.sock {image name}
</code>```

Is there an equivalent way for me to do this using DC/OS?

答:
The DC/OS way would be scheduling jobs via Mesos Master. That means writing a framework that would negotiate resource allocation (= "starting a Docker job") with the Master. Thus starting the job on any node in the cluster with available resources for the task. Such framework is yet another service that is responsible for resource negotiation with the Mesos Master. There are many examples of such frameworks:

kafka

elastic

cassandra

Most of the are build on top of dcos-commons service-framework.

A workaround would be starting the job via another existing framework, e.g. Marathon. Marathon offers a REST API.

Title: Allowing docker-in-docker on dc/os?

Body:
I am trying to schedule 'docker run' jobs using Airflow, on DC/OS. This requires the ability to start docker containers from within the docker container which contains Airflow. I am able to do this on OSX but just running:

docker run \
  -p 8080:8080 \
  -v /var/run/docker.sock:/var/run/docker.sock {image name}

Is there an equivalent way for me to do this using DC/OS?


答:
Um, don't do that? Instead, use methods to break things up into smaller pieces of logic that have descriptive names:

```<code>def add_that_long_thing_to(query)
  # Wanted to add comment here cause it's long
  # and takes multiple lines
  query.where(...)
       .where(...)
       .where(...)
end

def add_grouping_and_ordering_to_query)
  # And here
  query.group(...)
       .order(...)
end

query = Tag.joins(:taggings)
query = add_that_long_thing_to(query)
query = add_grouping_and_ordering_to(query)
</code>```

Of course, those names would be more sensible in real life but we don't know what any of the code is actually doing so I had to make something up.

Title: Adding a comment in the middle of a call chain

Body:
Um, don't do that? Instead, use methods to break things up into smaller pieces of logic that have descriptive names:

def add_that_long_thing_to(query)
  # Wanted to add comment here cause it's long
  # and takes multiple lines
  query.where(...)
       .where(...)
       .where(...)
end

def add_grouping_and_ordering_to_query)
  # And here
  query.group(...)
       .order(...)
end

query = Tag.joins(:taggings)
query = add_that_long_thing_to(query)
query = add_grouping_and_ordering_to(query)

Of course, those names would be more sensible in real life but we don't know what any of the code is actually doing so I had to make something up.


问:
Why are two dialog boxes popping up when I used angularjs-popup.js plugin?
As the following code , The web shows two dialog,why?</p>

```<code>Popup.alert('hello world', function () {
    console.log('ok');
});
</code>```

答: change the version of angularjs to 1.1.5 and work done.</p>

Body:
As the following code , The web shows two dialog,why?

Popup.alert('hello world', function () {
    console.log('ok');
});


问:
Turn off error for console.log on my eslint
I'm trying to turn off lint warning for my eslint at VS code.

My code is contains.

```<code>console.log('blabla..');
</code>```

eslint said as below.

```<code> error  Unexpected console statement                      no-console
</code>```

Even though already add no-restricted-syntax at my .eslintrc.json, no fixed.

Here is my .eslintrc.json

```<code>{
    "env": {
        "es6": true,
        "node": true,
        "amd": true,
        "mocha": true
    },
    "extends": "eslint:recommended",
    "parserOptions": {
        "ecmaVersion": 2017,
        "sourceType": "module"
    },
    "rules": {
        "linebreak-style": [
            "error",
            "windows"
        ],
        "no-restricted-syntax": [
            "error",
            {
                "selector": "CallExpression[callee.object.name='console'][callee.property.name=/^(log|warn|error|info|trace)$/]",
                "message": "Unexpected property on console object was called"
            }
        ]
    }
}
</code>```

What did I mistake?

答:
Allowing the console.log to stay in code is requiring a separate rule.
You need to add 'no-console' statement to your eslint config rules.

Like so:

```<code>rules: {
  "no-console": 0
}
</code>```

A better practice is to warn you about all the console.log in your code, like so:

```<code>rules: {
  "no-console": 1
}
</code>```

Body:
I'm trying to turn off lint warning for my eslint at VS code.

My code is contains.

console.log('blabla..');

eslint said as below.

 error  Unexpected console statement                      no-console

Even though already add no-restricted-syntax at my .eslintrc.json, no fixed.

Here is my .eslintrc.json

{
    "env": {
        "es6": true,
        "node": true,
        "amd": true,
        "mocha": true
    },
    "extends": "eslint:recommended",
    "parserOptions": {
        "ecmaVersion": 2017,
        "sourceType": "module"
    },
    "rules": {
        "linebreak-style": [
            "error",
            "windows"
        ],
        "no-restricted-syntax": [
            "error",
            {
                "selector": "CallExpression[callee.object.name='console'][callee.property.name=/^(log|warn|error|info|trace)$/]",
                "message": "Unexpected property on console object was called"
            }
        ]
    }
}

What did I mistake?

Body:
Allowing the console.log to stay in code is requiring a separate rule.
You need to add 'no-console' statement to your eslint config rules.

Like so:

rules: {
  "no-console": 0
}

A better practice is to warn you about all the console.log in your code, like so:

rules: {
  "no-console": 1
}

ContentLicense: CC BY-SA 4.0


问:
What is the difference between Reader and InputStream?
What is the difference between Reader and InputStream?
And when to use what?
If I can use Reader for reading characters why I will use inputstream, I guess to read objects?</p>

答:
I guess the source of confusion is that InputStream.read() returns an int and Reader.read() also returns an int.

The difference is that InputStream.read() return byte values between 0 and 255 corresponding to the raw contents of the byte stream and Reader.read() return the character value which is between 0 and 65357 (because there are 65358 different unicode codepoints)

An InputStream lets you read the contents byte by byte, for example the contents "a‡a" has 3 characters but it's encoded at 5 bytes in UTF-8. So with Inputstream you can read it as a stream of 5 bytes (each one represented as an int between 0 and 255) resulting in 97, 226, 128, 161 and 97 where

```<code>a -> U+0061 -> 0x61 (hex) -> 97 (dec)
‡ -> U+2021 -> 0xE280A1 (utf-8 encoding of 0x2021) -> 226 128 161 (1 int per byte)
a -> U+0061 -> 0x61 (hex) -> 97 (dec)
</code>```

A Reader lets you read the contents character by character so the contents "a‡a" are read as 3 characters 97, 8225 and 97 where

```<code>a -> U+0061 -> 0x61 -> 97
‡ -> U+2021 -> 0x2021 -> 8225 (single int, not 3)
a -> U+0061 -> 0x61 -> 97
</code>```

The character ‡ is referred as U+2021 in Unicode

Body:
I guess the source of confusion is that InputStream.read() returns an int and Reader.read() also returns an int.

The difference is that InputStream.read() return byte values between 0 and 255 corresponding to the raw contents of the byte stream and Reader.read() return the character value which is between 0 and 65357 (because there are 65358 different unicode codepoints)

An InputStream lets you read the contents byte by byte, for example the contents "a‡a" has 3 characters but it's encoded at 5 bytes in UTF-8. So with Inputstream you can read it as a stream of 5 bytes (each one represented as an int between 0 and 255) resulting in 97, 226, 128, 161 and 97 where

a -> U+0061 -> 0x61 (hex) -> 97 (dec)
‡ -> U+2021 -> 0xE280A1 (utf-8 encoding of 0x2021) -> 226 128 161 (1 int per byte)
a -> U+0061 -> 0x61 (hex) -> 97 (dec)

A Reader lets you read the contents character by character so the contents "a‡a" are read as 3 characters 97, 8225 and 97 where

a -> U+0061 -> 0x61 -> 97
‡ -> U+2021 -> 0x2021 -> 8225 (single int, not 3)
a -> U+0061 -> 0x61 -> 97

The character ‡ is referred as U+2021 in Unicode


问:
Referencing outer query's tables in a subquery
Is it possible to reference an outer query in a subquery with MySQL? I know there are some cases where this is possible:

```<code>SELECT *
FROM table t1
WHERE t1.date = (
    SELECT MAX(date)
    FROM table t2
    WHERE t2.id = t1.id
);
</code>```

But I'm wondering if something like this could work:

```<code>SELECT u.username, c._postCount
FROM User u
INNER JOIN (
    SELECT p.user, COUNT(*) AS _postCount
    FROM Posting p
    --# This is the reference I would need:
    WHERE p.user = u.id
    GROUP BY p.user
) c ON c.user = u.id
WHERE u.joinDate < '2009-10-10';
</code>```

I know I could achieve the same using a GROUP BY or by pulling the outer WHERE clause into the sub-query, but I need this for automatic SQL generation and cannot use either alternative for various other reasons.

UPDATE: Sorry, the question led to some confusion: The first query is just a working example, to demonstrate what I don't need.

UPDATE 2: I need both u.id = p.user comparisons: The first counts users that joined before '2009-10-10', while the other one is a join condition that associates table rows correctly.

答:
This solution is for postgresql.
You could use LATERAL JOIN which is available in postgresql. Here is how you could use it in your query.

```<code>SELECT u.username, c._postCount
FROM User u
INNER JOIN LATERAL (
    SELECT p.user, COUNT(*) AS _postCount
    FROM Posting p
    WHERE p.user = u.id
    GROUP BY p.user
) c ON c.user = u.id
WHERE u.joinDate < '2009-10-10';
</code>```

Here is a reference you could use. https://medium.com/kkempin/postgresqls-lateral-join-bfd6bd0199df

Body:
Is it possible to reference an outer query in a subquery with MySQL? I know there are some cases where this is possible:

SELECT *
FROM table t1
WHERE t1.date = (
    SELECT MAX(date)
    FROM table t2
    WHERE t2.id = t1.id
);

But I'm wondering if something like this could work:

SELECT u.username, c._postCount
FROM User u
INNER JOIN (
    SELECT p.user, COUNT(*) AS _postCount
    FROM Posting p
    --# This is the reference I would need:
    WHERE p.user = u.id
    GROUP BY p.user
) c ON c.user = u.id
WHERE u.joinDate < '2009-10-10';

I know I could achieve the same using a GROUP BY or by pulling the outer WHERE clause into the sub-query, but I need this for automatic SQL generation and cannot use either alternative for various other reasons.

UPDATE: Sorry, the question led to some confusion: The first query is just a working example, to demonstrate what I don't need.

UPDATE 2: I need both u.id = p.user comparisons: The first counts users that joined before '2009-10-10', while the other one is a join condition that associates table rows correctly.

Body:
This solution is for postgresql.
You could use LATERAL JOIN which is available in postgresql. Here is how you could use it in your query.

SELECT u.username, c._postCount
FROM User u
INNER JOIN LATERAL (
    SELECT p.user, COUNT(*) AS _postCount
    FROM Posting p
    WHERE p.user = u.id
    GROUP BY p.user
) c ON c.user = u.id
WHERE u.joinDate < '2009-10-10';

Here is a reference you could use. https://medium.com/kkempin/postgresqls-lateral-join-bfd6bd0199df


问:
Can we overload the main method in Java?
Can we overload a main() method in Java?

答:
Yes a main method can be overloaded as other functions can be overloaded.One thing needs to be taken care is that there should be atleast one main function with "String args[] " as arguments .And there can be any number of main functions in your program with different arguments and functionality.Lets understand through a simple example:

```<code>Class A{

public static void main(String[] args)
{
System.out.println("This is the main function ");
A object= new A();
object.main("Hi this is overloaded function");//Calling the main function
}

public static void main(String argu)     //duplicate main function
{
System.out.println("main(String argu)");
}
}
</code>```

Output:
This is the main function

Hi this is overloaded function

Body:
Yes a main method can be overloaded as other functions can be overloaded.One thing needs to be taken care is that there should be atleast one main function with "String args[] " as arguments .And there can be any number of main functions in your program with different arguments and functionality.Lets understand through a simple example:

Class A{

public static void main(String[] args)
{
System.out.println("This is the main function ");
A object= new A();
object.main("Hi this is overloaded function");//Calling the main function
}

public static void main(String argu)     //duplicate main function
{
System.out.println("main(String argu)");
}
}

Output:
This is the main function

Hi this is overloaded function


问:
How do I check the Database type in a Rails Migration?
I have the following migration and I want to be able to check if the current database related to the environment is a mysql database.  If it's mysql then I want to execute the SQL that is specific to the database.

How do I go about this?

```
class AddUsersFb < ActiveRecord::Migration

  def self.up
    add_column :users, :fb_user_id, :integer
    add_column :users, :email_hash, :string
    #if mysql
    #execute("alter table users modify fb_user_id bigint")
  end

  def self.down
    remove_column :users, :fb_user_id
    remove_column :users, :email_hash
  end

end
```

答:
In Rails 3, (maybe earlier, but I'm using Rails 3 currently) using ActiveRecord::ConnectionAdapters::MysqlAdapter is a poor way to go about it, as it's only initialized if the database adapter in use is MySQL.  Even if you have the MySQL gem installed, if it's not your connection type, that call wil fail:

```<code>Loading development environment (Rails 3.0.3)
>> ActiveRecord::Base.connection.instance_of? ActiveRecord::ConnectionAdapters::MysqlAdapter
NameError: uninitialized constant ActiveRecord::ConnectionAdapters::MysqlAdapter
from (irb):1
</code>```

So, I'd recommend stasl's answer and use the adapter_name property of the connection.

Body:
I have the following migration and I want to be able to check if the current database related to the environment is a mysql database.  If it's mysql then I want to execute the SQL that is specific to the database.

How do I go about this?

class AddUsersFb < ActiveRecord::Migration

  def self.up
    add_column :users, :fb_user_id, :integer
    add_column :users, :email_hash, :string
    #if mysql
    #execute("alter table users modify fb_user_id bigint")
  end

  def self.down
    remove_column :users, :fb_user_id
    remove_column :users, :email_hash
  end

end

Body:
In Rails 3, (maybe earlier, but I'm using Rails 3 currently) using ActiveRecord::ConnectionAdapters::MysqlAdapter is a poor way to go about it, as it's only initialized if the database adapter in use is MySQL.  Even if you have the MySQL gem installed, if it's not your connection type, that call wil fail:

Loading development environment (Rails 3.0.3)
>> ActiveRecord::Base.connection.instance_of? ActiveRecord::ConnectionAdapters::MysqlAdapter
NameError: uninitialized constant ActiveRecord::ConnectionAdapters::MysqlAdapter
from (irb):1

So, I'd recommend stasl's answer and use the adapter_name property of the connection.


问:
Couldn't display buttons on hovering
I want to display a set of buttons when user hover over a particular button (Settings), I was able to do it when user hover over the current div element hide the particular button(Settings) and show the other buttons,

```<code><div class="md-card container">
    <p matLine><b>{{message.artifactId}}</b></p>
    <p matLine>
        {{message.groupId}}    {{message.version}}
        <button type="submit" class="btn btn-danger pull-right settingsbtn">
            <i class="material-icons">settings</i>
        </button>
        <a routerLink="/baseline-errors/{{message.id}}">
            <button type="submit" class="btn btn-danger pull-right listbtn">
                <i class="material-icons">content_paste</i>
            </button>
        </a>
        <button *ngIf="isScanning" type="submit" class="btn btn-danger pull-right spaceTest listbtn"
                (click)="rescanBaseline(message)">
            <i class="material-icons">refresh</i>
        </button>
        <button type="submit" class="btn btn-danger pull-right listbtn"
                (click)="deleteBaseline(message)">
            <i class="material-icons">delete</i>
        </button>
        <button type="submit" class="btn btn-danger pull-right listbtn"
                (click)="editBaseline(message)"><i
                class="material-icons">mode_edit</i>
        </button>
    </p>
    <mat-divider></mat-divider>
</div>
</code>```

CSS

```<code>.listbtn {
    opacity: 0;
    transition: opacity .35s ease;
}

.container:hover .listbtn {
    opacity: 1;
}

.settingsbtn {
    opacity: 1;
    transition: opacity .35s ease;
}

.container:hover .settingsbtn {
    opacity: 0;
}
</code>```

This code works for div element but I want to change it to when user hover over the settings button rest will be shown, So I changed the code as this.

```<code><div class="md-card container">
    <p matLine><b>{{message.artifactId}}</b></p>
    <p matLine>
        {{message.groupId}}    {{message.version}}
        <span class="sd">
        <button type="submit" class="btn btn-danger pull-right settingsbtn">
        <i class="material-icons">settings</i>
        </button>
        <a routerLink="/baseline-errors/{{message.id}}">
            <button type="submit" class="btn btn-danger pull-right listbtn">
                <i class="material-icons">content_paste</i>
            </button>
        </a>
        <button *ngIf="isScanning" type="submit" class="btn btn-danger pull-right spaceTest listbtn"
                (click)="rescanBaseline(message)">
            <i class="material-icons">refresh</i>
        </button>
        <button type="submit" class="btn btn-danger pull-right listbtn"
                (click)="deleteBaseline(message)">
            <i class="material-icons">delete</i>
        </button>
        <button type="submit" class="btn btn-danger pull-right listbtn"
                (click)="editBaseline(message)"><i
                class="material-icons">mode_edit</i>
        </button>
        </span>
    </p>
    <mat-divider></mat-divider>
</div>
</code>```

CSS

```<code>.listbtn {
    opacity: 0;
    transition: opacity .35s ease;
}

.sd:hover .listbtn {
    opacity: 1;
}

.settingsbtn {
    opacity: 1;
    transition: opacity .35s ease;
}

.sd:hover .settingsbtn {
    opacity: 0;
}
</code>```

But it didn't work, what is the mistake I am making here?

EDIT

I want to display the settings button initially and when user hovers over settings button it should be hidden and other buttons should be visible but when user hovers over other buttons initially it shouldn't show those buttons. My current code snippet will work as when user hovers over any button either settings or hidden it will show the  buttons.

答:
Use this css it will works

```<code>.listbtn {
    opacity: 0;
    transition: opacity .35s ease;
}

.settingsbtn:hover ~ .listbtn,.settingsbtn:hover + a .listbtn {
    opacity: 1;
}

.settingsbtn {
    opacity: 1;
    transition: opacity .35s ease;
}

.settingsbtn:hover {
    opacity: 0;
}
</code>```

.listbtn {
    opacity: 0;
    transition: opacity .35s ease;
}

.settingsbtn:hover ~ .listbtn,.settingsbtn:hover + a .listbtn {
    opacity: 1;
}

.settingsbtn {
    opacity: 1;
    transition: opacity .35s ease;
}

.settingsbtn:hover {
    opacity: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="md-card container">
    <p matLine><b>{{message.artifactId}}</b></p>
    <p matLine>
        {{message.groupId}}    {{message.version}}
        <button type="submit" class="btn btn-danger pull-right settingsbtn">
        <i class="material-icons">settings</i>
        </button>

            <button type="submit" class="btn btn-danger pull-right listbtn">
                <i class="material-icons">content_paste</i>
            </button>

        <button *ngIf="isScanning" type="submit" class="btn btn-danger pull-right spaceTest listbtn"
                (click)="rescanBaseline(message)">
            <i class="material-icons">refresh</i>
        </button>
        <button type="submit" class="btn btn-danger pull-right listbtn"
                (click)="deleteBaseline(message)">
            <i class="material-icons">delete</i>
        </button>
        <button type="submit" class="btn btn-danger pull-right listbtn"
                (click)="editBaseline(message)"><i
                class="material-icons">mode_edit</i>
        </button>
    </p>
    <mat-divider></mat-divider>
</div></code>```

Title: Couldn't display buttons on hovering

Body:
I want to display a set of buttons when user hover over a particular button (Settings), I was able to do it when user hover over the current div element hide the particular button(Settings) and show the other buttons,

{{message.artifactId}}

        {{message.groupId}}    {{message.version}}
        <button type="submit" class="btn btn-danger pull-right settingsbtn">
            settings
        </button>

            <button type="submit" class="btn btn-danger pull-right listbtn">
                content_paste
            </button>

        <button *ngIf="isScanning" type="submit" class="btn btn-danger pull-right spaceTest listbtn"
                (click)="rescanBaseline(message)">
            refresh
        </button>
        <button type="submit" class="btn btn-danger pull-right listbtn"
                (click)="deleteBaseline(message)">
            delete
        </button>
        <button type="submit" class="btn btn-danger pull-right listbtn"
                (click)="editBaseline(message)">mode_edit
        </button>

    <mat-divider></mat-divider>

CSS

.listbtn {
    opacity: 0;
    transition: opacity .35s ease;
}

.container:hover .listbtn {
    opacity: 1;
}

.settingsbtn {
    opacity: 1;
    transition: opacity .35s ease;
}

.container:hover .settingsbtn {
    opacity: 0;
}

This code works for div element but I want to change it to when user hover over the settings button rest will be shown, So I changed the code as this.

{{message.artifactId}}

        {{message.groupId}}    {{message.version}}

        <button type="submit" class="btn btn-danger pull-right settingsbtn">
        settings
        </button>

            <button type="submit" class="btn btn-danger pull-right listbtn">
                content_paste
            </button>

        <button *ngIf="isScanning" type="submit" class="btn btn-danger pull-right spaceTest listbtn"
                (click)="rescanBaseline(message)">
            refresh
        </button>
        <button type="submit" class="btn btn-danger pull-right listbtn"
                (click)="deleteBaseline(message)">
            delete
        </button>
        <button type="submit" class="btn btn-danger pull-right listbtn"
                (click)="editBaseline(message)">mode_edit
        </button>

    <mat-divider></mat-divider>

CSS

.listbtn {
    opacity: 0;
    transition: opacity .35s ease;
}

.sd:hover .listbtn {
    opacity: 1;
}

.settingsbtn {
    opacity: 1;
    transition: opacity .35s ease;
}

.sd:hover .settingsbtn {
    opacity: 0;
}

But it didn't work, what is the mistake I am making here?

EDIT

I want to display the settings button initially and when user hovers over settings button it should be hidden and other buttons should be visible but when user hovers over other buttons initially it shouldn't show those buttons. My current code snippet will work as when user hovers over any button either settings or hidden it will show the  buttons.

Body:
Use this css it will works

.listbtn {
    opacity: 0;
    transition: opacity .35s ease;
}

.settingsbtn:hover ~ .listbtn,.settingsbtn:hover + a .listbtn {
    opacity: 1;
}

.settingsbtn {
    opacity: 1;
    transition: opacity .35s ease;
}

.settingsbtn:hover {
    opacity: 0;
}

.listbtn {
    opacity: 0;
    transition: opacity .35s ease;
}

.settingsbtn:hover ~ .listbtn,.settingsbtn:hover + a .listbtn {
    opacity: 1;
}

.settingsbtn {
    opacity: 1;
    transition: opacity .35s ease;
}

.settingsbtn:hover {
    opacity: 0;
}

<div class="md-card container">
    <p matLine><b>{{message.artifactId}}</b></p>
    <p matLine>
        {{message.groupId}} &nbsp;&nbsp; {{message.version}}
        <button type="submit" class="btn btn-danger pull-right settingsbtn">
        <i class="material-icons">settings</i>
        </button>
        <a routerLink="/baseline-errors/{{message.id}}">
            <button type="submit" class="btn btn-danger pull-right listbtn">
                <i class="material-icons">content_paste</i>
            </button>
        </a>
        <button *ngIf="isScanning" type="submit" class="btn btn-danger pull-right spaceTest listbtn"
                (click)="rescanBaseline(message)">
            <i class="material-icons">refresh</i>
        </button>
        <button type="submit" class="btn btn-danger pull-right listbtn"
                (click)="deleteBaseline(message)">
            <i class="material-icons">delete</i>
        </button>
        <button type="submit" class="btn btn-danger pull-right listbtn"
                (click)="editBaseline(message)"><i
                class="material-icons">mode_edit</i>
        </button>
    </p>
    <mat-divider></mat-divider>
</div>


问:
Error when logging in Ionic 3 + Angular 4 + Firebase mobile application - Error: username is not defined
I'm trying to create a simple chat application with  Ionic 3 and Firebase. Registering and logging in users works.

Users give their username in login.html and I'd like to use this username later on the chat.html page. This is the next page coming up after logging in. I'm using ionic storage to get and set the username (email address). I can't see the username from the chat page.

When trying ionic serve, I get this log on console:
ionViewDidLoad ChatPage

There is a space after ChatPage, that's the initial value of username. I'd like it to change to the current logged in user's username. I'm trying to get this value in ionViewDidLoad() in chat.ts:

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { AngularFireDatabase } from 'angularfire2/database';
import { Storage } from '@ionic/storage';

@IonicPage()
@Component({
  selector: 'page-chat',
  templateUrl: 'chat.html',
})
export class ChatPage {

  username: string= '';
  message: string= '';

  constructor(public db: AngularFireDatabase, public navCtrl: NavController, public navParams: NavParams, private storage: Storage) {
    this.storage.get('username').then((val) => {
      if (val != null) {
        this.username= val;
      }
    });
  }

  sendMessage() {
    this.db.list('/chat').push({
      username: this.username,
      message: this.message
    })
  }

  ionViewDidLoad() {
    let username= '';

    this.storage.get('username').then((val) => {
      if (val != null) {
        username= val;
      }
    });
    console.log('ionViewDidLoad ChatPage', username);
  }
}```
</div>
</div>
</p>

<p>login.html:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><ion-header>
  <ion-navbar>
    <ion-title>
      Login
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <ion-list>

  <ion-item>
    <ion-label floating>Username</ion-label>
    <ion-input type="text" [(ngModel)]= "username"></ion-input>
  </ion-item>

  <ion-item>
    <ion-label floating>Password</ion-label>
    <ion-input type="text" [(ngModel)]= "password"></ion-input>
  </ion-item>

  </ion-list>

  <div padding>
    <button ion-button (click)="signInUser()">Sign in</button>
  </div>
</ion-content></code>```

login.ts:

import { Component} from '@angular/core';
import { IonicPage, NavController, AlertController, NavParams } from 'ionic-angular';
import { AngularFireAuth } from 'angularfire2/auth';
import { ChatPage } from '../chat/chat';
import { Storage } from '@ionic/storage';

@IonicPage()
@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
})

export class LoginPage {
  username: string= '';
  password: string= '';

  constructor(private fire: AngularFireAuth, public navCtrl: NavController, private alertCtrl: AlertController, public navParams: NavParams, private storage: Storage)
  {
    this.storage.get('username').then((val) => {
      if (val != null) {
        this.username= val;
      }
    });
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad LoginPage');
  }

  alert(message: string) {
    this.alertCtrl.create({
      title: 'Info!',
      subTitle: message,
      buttons: ['OK']
    }).present();
  }

  signInUser() {
    this.storage.set('username', this.username);
    this.fire.auth.signInWithEmailAndPassword(this.username, this.password).then(data=> {
    console.log('got data', this.fire.auth.currentUser);
    this.alert('Success! You\'re logged in');
    this.navCtrl.push(ChatPage);

    }).catch(error => {
      console.log('got an error', error);
      this.alert(error.message);
    })
    console.log('Would sign in with ', this.username, this.password)
  }
}```

答:
Remove the first two lines in signInUser function.

```<code>signInUser() {

    this.fire.auth.signInWithEmailAndPassword(this.username, this.password).then(data=> {
    console.log('got data', this.fire.auth.currentUser);
    this.alert('Success! You\'re logged in');
    this.navCtrl.push(ChatPage);

    }).catch(error => {
      console.log('got an error', error);
      this.alert(error.message);
    })
    console.log('Would sign in with ', this.username, this.password)
}
</code>```

To use the username in other pages store it in the localstorage using ionic storage

Body:
I'm trying to create a simple chat application with  Ionic 3 and Firebase. Registering and logging in users works.

Users give their username in login.html and I'd like to use this username later on the chat.html page. This is the next page coming up after logging in. I'm using ionic storage to get and set the username (email address). I can't see the username from the chat page.

When trying ionic serve, I get this log on console:
ionViewDidLoad ChatPage

There is a space after ChatPage, that's the initial value of username. I'd like it to change to the current logged in user's username. I'm trying to get this value in ionViewDidLoad() in chat.ts:

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { AngularFireDatabase } from 'angularfire2/database';
import { Storage } from '@ionic/storage';

@IonicPage()
@Component({
  selector: 'page-chat',
  templateUrl: 'chat.html',
})
export class ChatPage {

  username: string= '';
  message: string= '';

  constructor(public db: AngularFireDatabase, public navCtrl: NavController, public navParams: NavParams, private storage: Storage) {
    this.storage.get('username').then((val) => {
      if (val != null) {
        this.username= val;
      }
    });
  }

  sendMessage() {
    this.db.list('/chat').push({
      username: this.username,
      message: this.message
    })
  }

  ionViewDidLoad() {
    let username= '';

    this.storage.get('username').then((val) => {
      if (val != null) {
        username= val;
      }
    });
    console.log('ionViewDidLoad ChatPage', username);
  }
}

login.html:

<ion-header>
  <ion-navbar>
    <ion-title>
      Login
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <ion-list>

  <ion-item>
    <ion-label floating>Username</ion-label>
    <ion-input type="text" [(ngModel)]= "username"></ion-input>
  </ion-item>

  <ion-item>
    <ion-label floating>Password</ion-label>
    <ion-input type="text" [(ngModel)]= "password"></ion-input>
  </ion-item>

  </ion-list>

    <button ion-button (click)="signInUser()">Sign in</button>

</ion-content>

login.ts:

import { Component} from '@angular/core';
import { IonicPage, NavController, AlertController, NavParams } from 'ionic-angular';
import { AngularFireAuth } from 'angularfire2/auth';
import { ChatPage } from '../chat/chat';
import { Storage } from '@ionic/storage';

@IonicPage()
@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
})

export class LoginPage {
  username: string= '';
  password: string= '';

  constructor(private fire: AngularFireAuth, public navCtrl: NavController, private alertCtrl: AlertController, public navParams: NavParams, private storage: Storage)
  {
    this.storage.get('username').then((val) => {
      if (val != null) {
        this.username= val;
      }
    });
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad LoginPage');
  }

  alert(message: string) {
    this.alertCtrl.create({
      title: 'Info!',
      subTitle: message,
      buttons: ['OK']
    }).present();
  }

  signInUser() {
    this.storage.set('username', this.username);
    this.fire.auth.signInWithEmailAndPassword(this.username, this.password).then(data=> {
    console.log('got data', this.fire.auth.currentUser);
    this.alert('Success! You\'re logged in');
    this.navCtrl.push(ChatPage);

    }).catch(error => {
      console.log('got an error', error);
      this.alert(error.message);
    })
    console.log('Would sign in with ', this.username, this.password)
  }
}

Body:
Remove the first two lines in signInUser function.

signInUser() {

    this.fire.auth.signInWithEmailAndPassword(this.username, this.password).then(data=> {
    console.log('got data', this.fire.auth.currentUser);
    this.alert('Success! You\'re logged in');
    this.navCtrl.push(ChatPage);

    }).catch(error => {
      console.log('got an error', error);
      this.alert(error.message);
    })
    console.log('Would sign in with ', this.username, this.password)
}

To use the username in other pages store it in the localstorage using ionic storage


问:
Python hyper parameter for rounding float numbers
This question must be an easy one but I couldn't find anything about it here.

Is there a way in python to define or use 1 command line so that every float number across the script will be rounded by X digists.

For example if I define:

```<code>max_float_digits = 4
</code>```

and the program wants to outputs or print the following number 5.1355895682, all I will see is 5.1356

This necessity rises when some module return this value to my script:

```<code>[('user_ctr', 2253.459088429824), ('user_clicks', 2042.3175666666664), ('t_avg_sim', 176.83513843049306), ('item_ctr', 137.6051319164618), ('item_age', 128.52122456437388), ('t_max_sim', 126.23752629310347), ('item_read_time', 46.94452635514022), ('clicks', 26.368489035532996), ('likes', 15.43922933884298), ('c_max_sim', 14.761540559999993), ('no_clicks', 13.020515220883516), ('c_avg_sim', 10.969965476190472), ('user_read_time', 10.21293115646259), ('user_age', 9.776781678832117)]
</code>```

Instead of trying to access each value and round them I'd like a 1 command line that will round them all for me.

答:
Sorry, Python doesn't provide global settings to control formatting. If you don't want to display floats at their full precision then you need to format them explicitly. I suppose that's not so convenient when you print a collection containing floats. However, the __repr__ of Python's collection objects (tuple, list, dict, set) is primarily intended for displaying these objects to programmers, not to users. It is expected that you will format such objects if you intend to display them to users, not just dump them to the terminal.

If you want to use the same formatting in multiple places it may be worthwhile to define a function. Eg,

```<code>max_float_digits = 4
def rounded(val):
    return '{:.{}f}'.format(val, max_float_digits)

data = [
    ('user_ctr', 2253.459088429824), ('user_clicks', 2042.3175666666664),
    ('t_avg_sim', 176.83513843049306), ('item_ctr', 137.6051319164618),
    ('item_age', 128.52122456437388), ('t_max_sim', 126.23752629310347),
    ('item_read_time', 46.94452635514022), ('clicks', 26.368489035532996),
    ('likes', 15.43922933884298), ('c_max_sim', 14.761540559999993),
    ('no_clicks', 13.020515220883516), ('c_avg_sim', 10.969965476190472),
    ('user_read_time', 10.21293115646259), ('user_age', 9.776781678832117),
]

out_data = [(key, rounded(val)) for key, val in data]
for row in out_data:
    print(row)
</code>```

output

```<code>('user_ctr', '2253.4591')
('user_clicks', '2042.3176')
('t_avg_sim', '176.8351')
('item_ctr', '137.6051')
('item_age', '128.5212')
('t_max_sim', '126.2375')
('item_read_time', '46.9445')
('clicks', '26.3685')
('likes', '15.4392')
('c_max_sim', '14.7615')
('no_clicks', '13.0205')
('c_avg_sim', '10.9700')
('user_read_time', '10.2129')
('user_age', '9.7768')
</code>```

If you actually want the string representation of the list, and you want it to look as shown in the question, you can use the built-in round function.

```<code>output = [(key, round(val, max_float_digits)) for key, val in data]
print(output)
</code>```

output

```<code>[('user_ctr', 2253.4591), ('user_clicks', 2042.3176), ('t_avg_sim', 176.8351), ('item_ctr', 137.6051), ('item_age', 128.5212), ('t_max_sim', 126.2375), ('item_read_time', 46.9445), ('clicks', 26.3685), ('likes', 15.4392), ('c_max_sim', 14.7615), ('no_clicks', 13.0205), ('c_avg_sim', 10.97), ('user_read_time', 10.2129), ('user_age', 9.7768)]
</code>```

To turn any object into its string representation, pass it to repr or str, eg

```<code>s = repr(output)
</code>```

Body:
This question must be an easy one but I couldn't find anything about it here.

Is there a way in python to define or use 1 command line so that every float number across the script will be rounded by X digists.

For example if I define:

max_float_digits = 4

and the program wants to outputs or print the following number 5.1355895682, all I will see is 5.1356

This necessity rises when some module return this value to my script:

[('user_ctr', 2253.459088429824), ('user_clicks', 2042.3175666666664), ('t_avg_sim', 176.83513843049306), ('item_ctr', 137.6051319164618), ('item_age', 128.52122456437388), ('t_max_sim', 126.23752629310347), ('item_read_time', 46.94452635514022), ('clicks', 26.368489035532996), ('likes', 15.43922933884298), ('c_max_sim', 14.761540559999993), ('no_clicks', 13.020515220883516), ('c_avg_sim', 10.969965476190472), ('user_read_time', 10.21293115646259), ('user_age', 9.776781678832117)]

Instead of trying to access each value and round them I'd like a 1 command line that will round them all for me.

Body:
Sorry, Python doesn't provide global settings to control formatting. If you don't want to display floats at their full precision then you need to format them explicitly. I suppose that's not so convenient when you print a collection containing floats. However, the __repr__ of Python's collection objects (tuple, list, dict, set) is primarily intended for displaying these objects to programmers, not to users. It is expected that you will format such objects if you intend to display them to users, not just dump them to the terminal.

If you want to use the same formatting in multiple places it may be worthwhile to define a function. Eg,

max_float_digits = 4
def rounded(val):
    return '{:.{}f}'.format(val, max_float_digits)

data = [
    ('user_ctr', 2253.459088429824), ('user_clicks', 2042.3175666666664),
    ('t_avg_sim', 176.83513843049306), ('item_ctr', 137.6051319164618),
    ('item_age', 128.52122456437388), ('t_max_sim', 126.23752629310347),
    ('item_read_time', 46.94452635514022), ('clicks', 26.368489035532996),
    ('likes', 15.43922933884298), ('c_max_sim', 14.761540559999993),
    ('no_clicks', 13.020515220883516), ('c_avg_sim', 10.969965476190472),
    ('user_read_time', 10.21293115646259), ('user_age', 9.776781678832117),
]

out_data = [(key, rounded(val)) for key, val in data]
for row in out_data:
    print(row)

output

('user_ctr', '2253.4591')
('user_clicks', '2042.3176')
('t_avg_sim', '176.8351')
('item_ctr', '137.6051')
('item_age', '128.5212')
('t_max_sim', '126.2375')
('item_read_time', '46.9445')
('clicks', '26.3685')
('likes', '15.4392')
('c_max_sim', '14.7615')
('no_clicks', '13.0205')
('c_avg_sim', '10.9700')
('user_read_time', '10.2129')
('user_age', '9.7768')

If you actually want the string representation of the list, and you want it to look as shown in the question, you can use the built-in round function.

output = [(key, round(val, max_float_digits)) for key, val in data]
print(output)

output

[('user_ctr', 2253.4591), ('user_clicks', 2042.3176), ('t_avg_sim', 176.8351), ('item_ctr', 137.6051), ('item_age', 128.5212), ('t_max_sim', 126.2375), ('item_read_time', 46.9445), ('clicks', 26.3685), ('likes', 15.4392), ('c_max_sim', 14.7615), ('no_clicks', 13.0205), ('c_avg_sim', 10.97), ('user_read_time', 10.2129), ('user_age', 9.7768)]

To turn any object into its string representation, pass it to repr or str, eg

s = repr(output)


答: You can add // eslint-disable-line if you need to ignore a specific (or multiple) line

Title: Turn off error for console.log on my eslint


问:
Writing over previously output lines in the command prompt with ruby
I've run command line programs that output a line, and then update that line a moment later.  But with ruby I can only seem to output a line and then another line.

What I have being output now:

```<code>Downloading file:
11MB 294K/s
12MB 307K/s
14MB 294K/s
15MB 301K/s
16MB 300K/s
Done!
</code>```

And instead, I want to see this:

```<code>Downloading file:
11MB 294K/s
</code>```

Followed a moment later by this:

```<code>Downloading file:
16MB 300K/s
Done!
</code>```

The line my ruby script outputs that shows the downloaded filesize and transfer speed would be overwritten each time instead of listing the updated values as a whole new line.

I'm currently using puts to generate output, which clearly isn't designed for this case.  Is there a different output method that can achieve this result?

答:
Use \r to move the cursor to the beginning of the line.  And you should not be using puts as it adds \n, use print instead.  Like this:

```<code>print "11MB 294K/s"
print "\r"
print "12MB 307K/s"
</code>```

One thing to keep in mind though: \r doesn't delete anything, it just moves the cursor back, so you would need to pad the output with spaces to overwrite the previous output (in case it was longer).

By default when \n is printed to the standard output the buffer is flushed.  Now you might need to use STDOUT.flush after print to make sure the text get printed right away.

Body:
I've run command line programs that output a line, and then update that line a moment later.  But with ruby I can only seem to output a line and then another line.

What I have being output now:

Downloading file:
11MB 294K/s
12MB 307K/s
14MB 294K/s
15MB 301K/s
16MB 300K/s
Done!

And instead, I want to see this:

Downloading file:
11MB 294K/s

Followed a moment later by this:

Downloading file:
16MB 300K/s
Done!

The line my ruby script outputs that shows the downloaded filesize and transfer speed would be overwritten each time instead of listing the updated values as a whole new line.

I'm currently using puts to generate output, which clearly isn't designed for this case.  Is there a different output method that can achieve this result?

Body:
Use \r to move the cursor to the beginning of the line.  And you should not be using puts as it adds \n, use print instead.  Like this:

print "11MB 294K/s"
print "\r"
print "12MB 307K/s"

One thing to keep in mind though: \r doesn't delete anything, it just moves the cursor back, so you would need to pad the output with spaces to overwrite the previous output (in case it was longer).

By default when \n is printed to the standard output the buffer is flushed.  Now you might need to use STDOUT.flush after print to make sure the text get printed right away.


问:
How to check SQL Server is availability using C# and ASP.NET 4.0
I have client server architecture. I have server and 4 client machines, each client has SQL Server connected with LAN.

I need to check the 4 client database was connected or not.

In my web.config

```<code><connectionStrings>
    <add name="DBConnection"
         connectionString="Data Source=192.168.1.90,1433;Initial Catalog=POS;Integrated Security=False;User Id=sa;Password=sql2008;"
         providerName="System.Data.SqlClient" />
    <add name="DBConnection1"
         connectionString="Data Source=192.168.1.91,1433;Initial Catalog=POS;Integrated Security=False;User Id=sa;Password=sql2008;Connection Timeout=5"
         providerName="System.Data.SqlClient" />
    <add name="DBConnection2"
         connectionString="Data Source=192.168.1.92,1433;Initial Catalog=POS;Integrated Security=False;User Id=sa;Password=sql2008;Connection Timeout=5"
         providerName="System.Data.SqlClient" />
    <add name="DBConnection3"
         connectionString="Data Source=192.168.1.93,1433;Initial Catalog=POS;Integrated Security=False;User Id=sa;Password=sql2008;Connection Timeout=5"
         providerName="System.Data.SqlClient" />
    <add name="DBConnection4"
         connectionString="Data Source=192.168.1.94,1433;Initial Catalog=POS;Integrated Security=False;User Id=sa;Password=sql2008;Connection Timeout=5"
         providerName="System.Data.SqlClient" />
</connectionStrings>
</code>```

In my ASP.NET code, I am using an ajax method inside the for loop

```<code>   <script type="text/javascript">
     function CheckDB() {

         for (var i = 1; i <= 4); i++) {
             var DBConnection = "DBConnection" + i;
             $.ajax({
                 type: 'POST',
                 url: 'StockIntegration.aspx/CheckDB',
                 data: "{DBConnection:" + JSON.stringify(DBConnection) + "}",
                 contentType: 'application/json; charset=utf-8',
                 dataType: 'json',
                 success: function (data) {

                     if (data.d == null || data.d == undefined) {

                     } else {

                         if (data.d == "1") {
                             $('[id$=Label1]').append("CONNECTED SYSTEM: " + DBConnection + "<br/>");
                         } else {
                             $('[id$=Label2]').append("DISCONNECTED SYSTEM: " + DBConnection + "<br/>");
                         }
                     }
                 },
                 error: function ()
                 { alert('there is some error'); }
             });
         }
     }
 </script>
</code>```

In my web service

```<code>[System.Web.Services.WebMethod]
public static String CheckDB(String DBConnection)
{
        try
        {
            SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[DBConnection].ConnectionString);
            SqlCommand cmd = new SqlCommand("select 1", con);
            con.Open();
            var rowCount = cmd.ExecuteScalar();
            con.Close();
            return rowCount.ToString();
        }
        catch
        {
            return "Fasle";
        }
}
</code>```

The loop will close if any of SQL Server instances is disconnected. How to achieve this? I need to show the list of connected and disconnected SQL Server instances.

答:
Here is your frontend client javascript code. But only success part of it:

```<code>success: function (data) {
                 if (data == null || !data) {
                      $('[id$=Label2]').append("DISCONNECTED SYSTEM: " + DBConnection + "<br/>");
                 } else {
                      $('[id$=Label1]').append("CONNECTED SYSTEM: " + DBConnection + "<br/>");
                 }
             },
</code>```

this is your c# backend code.

```<code>[System.Web.Services.WebMethod]
public static bool CheckDB(String DBConnection)
{
    try
    {
        using(var con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[DBConnection].ConnectionString);
        {
            con.Open();
            return true;
        }
    }
    catch
    {
        return false;
    }
 }
</code>```

Body:
I have client server architecture. I have server and 4 client machines, each client has SQL Server connected with LAN.

I need to check the 4 client database was connected or not.

In my web.config

<connectionStrings>
    <add name="DBConnection"
         connectionString="Data Source=192.168.1.90,1433;Initial Catalog=POS;Integrated Security=False;User Id=sa;Password=sql2008;"
         providerName="System.Data.SqlClient" />
    <add name="DBConnection1"
         connectionString="Data Source=192.168.1.91,1433;Initial Catalog=POS;Integrated Security=False;User Id=sa;Password=sql2008;Connection Timeout=5"
         providerName="System.Data.SqlClient" />
    <add name="DBConnection2"
         connectionString="Data Source=192.168.1.92,1433;Initial Catalog=POS;Integrated Security=False;User Id=sa;Password=sql2008;Connection Timeout=5"
         providerName="System.Data.SqlClient" />
    <add name="DBConnection3"
         connectionString="Data Source=192.168.1.93,1433;Initial Catalog=POS;Integrated Security=False;User Id=sa;Password=sql2008;Connection Timeout=5"
         providerName="System.Data.SqlClient" />
    <add name="DBConnection4"
         connectionString="Data Source=192.168.1.94,1433;Initial Catalog=POS;Integrated Security=False;User Id=sa;Password=sql2008;Connection Timeout=5"
         providerName="System.Data.SqlClient" />
</connectionStrings>

In my ASP.NET code, I am using an ajax method inside the for loop

In my web service

[System.Web.Services.WebMethod]
public static String CheckDB(String DBConnection)
{
        try
        {
            SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[DBConnection].ConnectionString);
            SqlCommand cmd = new SqlCommand("select 1", con);
            con.Open();
            var rowCount = cmd.ExecuteScalar();
            con.Close();
            return rowCount.ToString();
        }
        catch
        {
            return "Fasle";
        }
}

The loop will close if any of SQL Server instances is disconnected. How to achieve this? I need to show the list of connected and disconnected SQL Server instances.

Body:
Here is your frontend client javascript code. But only success part of it:

success: function (data) {
                 if (data == null || !data) {
                      $('[id$=Label2]').append("DISCONNECTED SYSTEM: " + DBConnection + "<br/>");
                 } else {
                      $('[id$=Label1]').append("CONNECTED SYSTEM: " + DBConnection + "<br/>");
                 }
             },

this is your c# backend code.

[System.Web.Services.WebMethod]
public static bool CheckDB(String DBConnection)
{
    try
    {
        using(var con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[DBConnection].ConnectionString);
        {
            con.Open();
            return true;
        }
    }
    catch
    {
        return false;
    }
 }


问:
How to set c++ compiler on OS X with bazel?
How can you tell bazel to use a different C++ compiler on OS X?

```<code>bazel build --action_env CC=/path/to/compiler //:target
</code>```

works on linux.

But -s shows that bazel always runs with external/local_config_cc/wrapped_clang (clang) on OSX regardless of what CC is.

答:
Use --crosstool_top.

See also --host_crosstool_top and --apple_crosstool_top.

Body:
How can you tell bazel to use a different C++ compiler on OS X?

bazel build --action_env CC=/path/to/compiler //:target

works on linux.

But -s shows that bazel always runs with external/local_config_cc/wrapped_clang (clang) on OSX regardless of what CC is.


问:
How to fetch questions ony by one on save and next buttons
I have a quiz management system and need to fetch the data from the database and displaying the data one by one on clicking next button.

I want to use ajax to insert data into database after clicking next button by using file read and write function.

```<code>$sql=mysqli_query($con,"SELECT * FROM tbl_question WHERE setid='$set' AND status=1 ORDER BY RAND()");

while($sha=mysqli_fetch_array($sql)) {
    <h4><? echo $sha['id'];?></h4>
</code>```

答:
here's simple way to do it
first get question from database then put a button to the next id </p>

```<code><?php
$rows = 0;
$id = isset($_GET['id'] ? (int) $_GET['id'] : 0;
$query = 'SELECT * FROM `tbl_question` WHERE `tbl_question`.`status` = 1 AND  `tbl_question`.`id` = ? LIMIT 1';
$mysqli = new mysqli('localhost','user','password','database');
$stmt = $mysqli->prepare($query);
$stmt->bind_param('i',$id);
$stmt->execute();
$stmt->bind_result($id,$something,$something_else,$status);
while($stmt->fetch())
     $rows++;
$stmt->close();
$mysqli->close();

if($rows === 0) {
 echo 'qustion not found';
} else {

   // output qustion

   // button

   echo '<a type="buttton" href="?id=' . $id + 1 . '">next</a>';
}
</code>```

Body:
I have a quiz management system and need to fetch the data from the database and displaying the data one by one on clicking next button.

I want to use ajax to insert data into database after clicking next button by using file read and write function.

$sql=mysqli_query($con,"SELECT * FROM tbl_question WHERE setid='$set' AND status=1 ORDER BY RAND()");

while($sha=mysqli_fetch_array($sql)) {

<? echo $sha['id'];?>

Body:
here's simple way to do it
first get question from database then put a button to the next id

<?php
$rows = 0;
$id = isset($_GET['id'] ? (int) $_GET['id'] : 0;
$query = 'SELECT * FROM `tbl_question` WHERE `tbl_question`.`status` = 1 AND  `tbl_question`.`id` = ? LIMIT 1';
$mysqli = new mysqli('localhost','user','password','database');
$stmt = $mysqli->prepare($query);
$stmt->bind_param('i',$id);
$stmt->execute();
$stmt->bind_result($id,$something,$something_else,$status);
while($stmt->fetch())
     $rows++;
$stmt->close();
$mysqli->close();

if($rows === 0) {
 echo 'qustion not found';
} else {

   // output qustion

   // button

   echo '<a type="buttton" href="?id=' . $id + 1 . '">next</a>';
}


问:
How to continue code on next line (code too long)
How do I continue code (record insertion) on the next line?  In the example below I tried using underscore to end a line, then & to begin the next due to suggestions online, but it still doesn't compile.  Any thoughts?

Code Line:

```<code>CurrentDb.Execute "INSERT INTO AIP&BOP (PlanTitle, FileLocation, YearsofData, AnnualImprovedCML, AIP1, AIP1BOP1, AIP2, AIP1BOP2, AIP3, AIP1BOP3, AIP4, AIP1BOP4, AIP5, AIP1BOP5, AIP6, AIP1BOP6, AIP7, AIP1BOP7, AIP8, AIP1BOP8, AIP9, AIP1BOP9, AIP10, AIP1BOP10, AIP11, AIP1BOP11, AIP12, AIP1BOP12, AIP13, AIP1BOP13, AIP14, AIP1BOP14, AIP15, AIP1BOP15, AIP16, AIP1BOP16, AIP17, AIP1BOP17, AIP18, AIP1BOP18, AIP19, AIP1BOP19, AIP20, AIP1BOP20, AIP21, AIP1BOP21, AIP22, AIP1BOP22, AIP23, AIP1BOP23, AIP24, AIP1BOP24) Values ('" & RWPSheetvalues(71) & "', '" & RWPSheetvalues(72) & "', '" & RWPSheetvalues(73) & "', '" & RWPSheetvalues(74) & "','" & RWPSheetvalues(1) & "','" & RWPSheetvalues(2) & "', '" & RWPSheetvalues(3) & "', '" & RWPSheetvalues(4) & "','" & RWPSheetvalues(5) & "','" & RWPSheetvalues(6) & "', '" & RWPSheetvalues(7) & "', '" & RWPSheetvalues(8) & "','" & RWPSheetvalues(9) & "', _
& '" & RWPSheetvalues(10) & "', '" & RWPSheetvalues(11) & "', '" & RWPSheetvalues(12) & "','" & RWPSheetvalues(13) & "','" & RWPSheetvalues(14) & "', '" & RWPSheetvalues(15) & "', '" & RWPSheetvalues(16) & "','" & RWPSheetvalues(17) & "','" & RWPSheetvalues(18) & "', '" & RWPSheetvalues(19) & "', '" & RWPSheetvalues(20) & "','" & RWPSheetvalues(21) & "','" & RWPSheetvalues(22) & "', '" & RWPSheetvalues(23) & "', '" & RWPSheetvalues(24) & "','" & RWPSheetvalues(25) & "','" & RWPSheetvalues(26) & "', '" & RWPSheetvalues(27) & "', '" & RWPSheetvalues(28) & "','" & RWPSheetvalues(29) & "','" & RWPSheetvalues(30) & "', '" & RWPSheetvalues(31) & "', '" & RWPSheetvalues(32) & "','" & RWPSheetvalues(33) & "','" & RWPSheetvalues(34) & "', '" & RWPSheetvalues(35) & "', '" & RWPSheetvalues(36) & "','" & RWPSheetvalues(37) & "','" & RWPSheetvalues(38) & "', '" & RWPSheetvalues(39) & "', '" & RWPSheetvalues(40) & "','" & RWPSheetvalues(41) & "', _
& '" & RWPSheetvalues(42) & "', '" & RWPSheetvalues(43) & "', '" & RWPSheetvalues(44) & "','" & RWPSheetvalues(45) & "','" & RWPSheetvalues(46) & "', '" & RWPSheetvalues(47) & "', '" & RWPSheetvalues(48) & "','" & RWPSheetvalues(49) & "','" & RWPSheetvalues(50) & "', '" & RWPSheetvalues(51) & "', '" & RWPSheetvalues(52) & "','" & RWPSheetvalues(53) & "','" & RWPSheetvalues(54) & "', '" & RWPSheetvalues(55) & "', '" & RWPSheetvalues(56) & "','" & RWPSheetvalues(57) & "','" & RWPSheetvalues(58) & "', '" & RWPSheetvalues(59) & "', '" & RWPSheetvalues(60) & "','" & RWPSheetvalues(61) & "','" & RWPSheetvalues(62) & "', '" & RWPSheetvalues(63) & "', '" & RWPSheetvalues(64) & "','" & RWPSheetvalues(65) & "','" & RWPSheetvalues(66) & "', '" & RWPSheetvalues(67) & "', '" & RWPSheetvalues(68) & "','" & RWPSheetvalues(69) & "','" & RWPSheetvalues(70) & "')"
</code>```

答:
This code is a nightmare to maintain. To set so many columns, using a recordset is better readable.

It also prevents SQL injection and problems with data formatting (e.g. date fields).

Dim RS As DAO.Recordset

Set RS = CurrentDb.OpenRecordset("AIP&BOP")
With RS
    .AddNew
    !PlanTitle = RWPSheetvalues(71)
    !FileLocation = RWPSheetvalues(72)
    !YearsofData = RWPSheetvalues(73)
    ' etc. ........
    .Update
End With
```

Body:
How do I continue code (record insertion) on the next line?  In the example below I tried using underscore to end a line, then & to begin the next due to suggestions online, but it still doesn't compile.  Any thoughts?

Code Line:

CurrentDb.Execute "INSERT INTO AIP&BOP (PlanTitle, FileLocation, YearsofData, AnnualImprovedCML, AIP1, AIP1BOP1, AIP2, AIP1BOP2, AIP3, AIP1BOP3, AIP4, AIP1BOP4, AIP5, AIP1BOP5, AIP6, AIP1BOP6, AIP7, AIP1BOP7, AIP8, AIP1BOP8, AIP9, AIP1BOP9, AIP10, AIP1BOP10, AIP11, AIP1BOP11, AIP12, AIP1BOP12, AIP13, AIP1BOP13, AIP14, AIP1BOP14, AIP15, AIP1BOP15, AIP16, AIP1BOP16, AIP17, AIP1BOP17, AIP18, AIP1BOP18, AIP19, AIP1BOP19, AIP20, AIP1BOP20, AIP21, AIP1BOP21, AIP22, AIP1BOP22, AIP23, AIP1BOP23, AIP24, AIP1BOP24) Values ('" & RWPSheetvalues(71) & "', '" & RWPSheetvalues(72) & "', '" & RWPSheetvalues(73) & "', '" & RWPSheetvalues(74) & "','" & RWPSheetvalues(1) & "','" & RWPSheetvalues(2) & "', '" & RWPSheetvalues(3) & "', '" & RWPSheetvalues(4) & "','" & RWPSheetvalues(5) & "','" & RWPSheetvalues(6) & "', '" & RWPSheetvalues(7) & "', '" & RWPSheetvalues(8) & "','" & RWPSheetvalues(9) & "', _
& '" & RWPSheetvalues(10) & "', '" & RWPSheetvalues(11) & "', '" & RWPSheetvalues(12) & "','" & RWPSheetvalues(13) & "','" & RWPSheetvalues(14) & "', '" & RWPSheetvalues(15) & "', '" & RWPSheetvalues(16) & "','" & RWPSheetvalues(17) & "','" & RWPSheetvalues(18) & "', '" & RWPSheetvalues(19) & "', '" & RWPSheetvalues(20) & "','" & RWPSheetvalues(21) & "','" & RWPSheetvalues(22) & "', '" & RWPSheetvalues(23) & "', '" & RWPSheetvalues(24) & "','" & RWPSheetvalues(25) & "','" & RWPSheetvalues(26) & "', '" & RWPSheetvalues(27) & "', '" & RWPSheetvalues(28) & "','" & RWPSheetvalues(29) & "','" & RWPSheetvalues(30) & "', '" & RWPSheetvalues(31) & "', '" & RWPSheetvalues(32) & "','" & RWPSheetvalues(33) & "','" & RWPSheetvalues(34) & "', '" & RWPSheetvalues(35) & "', '" & RWPSheetvalues(36) & "','" & RWPSheetvalues(37) & "','" & RWPSheetvalues(38) & "', '" & RWPSheetvalues(39) & "', '" & RWPSheetvalues(40) & "','" & RWPSheetvalues(41) & "', _
& '" & RWPSheetvalues(42) & "', '" & RWPSheetvalues(43) & "', '" & RWPSheetvalues(44) & "','" & RWPSheetvalues(45) & "','" & RWPSheetvalues(46) & "', '" & RWPSheetvalues(47) & "', '" & RWPSheetvalues(48) & "','" & RWPSheetvalues(49) & "','" & RWPSheetvalues(50) & "', '" & RWPSheetvalues(51) & "', '" & RWPSheetvalues(52) & "','" & RWPSheetvalues(53) & "','" & RWPSheetvalues(54) & "', '" & RWPSheetvalues(55) & "', '" & RWPSheetvalues(56) & "','" & RWPSheetvalues(57) & "','" & RWPSheetvalues(58) & "', '" & RWPSheetvalues(59) & "', '" & RWPSheetvalues(60) & "','" & RWPSheetvalues(61) & "','" & RWPSheetvalues(62) & "', '" & RWPSheetvalues(63) & "', '" & RWPSheetvalues(64) & "','" & RWPSheetvalues(65) & "','" & RWPSheetvalues(66) & "', '" & RWPSheetvalues(67) & "', '" & RWPSheetvalues(68) & "','" & RWPSheetvalues(69) & "','" & RWPSheetvalues(70) & "')"