问:
Cannot read property 'replaceChild' of null URL: webpack:///./~react-dom/lib/DOMLazyTree.js
I am using phonegap to create an app using react v15 and "webpack": "^2.2.1" to bundle up everything. I then run my webpack.prod.json to generate a stand alone .js file which is included in the app.

When I install the app locally, I have no problems and can run the application, however when I build through phonegap.com/build is when the issue occurs.

Even weirder still is that the initial state loads fine. Its when I navigate to #/home that this error occurs:

```<code>Uncaught SyntaxError: Unexpected token u in JSON at position 0
    at JSON.parse (<anonymous>)
    at RequireLogin.render (RequireLogin.js:32)
    at ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext (ReactCompositeComponent.js:799)
    at ReactCompositeComponentWrapper._renderValidatedComponent (ReactCompositeComponent.js:822)
    at ReactCompositeComponentWrapper.performInitialMount (ReactCompositeComponent.js:362)
    at ReactCompositeComponentWrapper.mountComponent (ReactCompositeComponent.js:258)
    at Object.mountComponent (ReactReconciler.js:46)
    at ReactCompositeComponentWrapper.performInitialMount (ReactCompositeComponent.js:371)
    at ReactCompositeComponentWrapper.mountComponent (ReactCompositeComponent.js:258)
    at Object.mountComponent (ReactReconciler.js:46)
</code>```

RequireLogin.js

```<code>import React from 'react';
import {connect} from 'react-redux';
import {Redirect} from 'react-router'

class BlockForLoggedInUsers extends React.Component {
  constructor(props){
    super(props);
  }
  render(){
    const loggedIn = this.props.user.loggedIn || JSON.parse(localStorage.LOGGED_IN);
    if (loggedIn) {
      return (
        <Redirect push to="/home"/>
      )
    }else{
      return (
        <div></div>
      );
    }
  }
}

function mapStateToProps(state){
  return {
    user: state.user
  };
}

export default connect(mapStateToProps)(BlockForLoggedInUsers);
</code>```

Then, when I hit the back key I get a different error:

```<code>DOMLazyTree.js:69 Uncaught TypeError: Cannot read property 'replaceChild' of null
    at Function.replaceChildWithTree (DOMLazyTree.js:69)
    at Object.dangerouslyReplaceNodeWithMarkup [as replaceNodeWithMarkup] (Danger.js:41)
    at ReactCompositeComponentWrapper._replaceNodeWithMarkup (ReactCompositeComponent.js:784)
    at ReactCompositeComponentWrapper._updateRenderedComponent (ReactCompositeComponent.js:774)
    at ReactCompositeComponentWrapper._performComponentUpdate (ReactCompositeComponent.js:724)
    at ReactCompositeComponentWrapper.updateComponent (ReactCompositeComponent.js:645)
    at ReactCompositeComponentWrapper.receiveComponent (ReactCompositeComponent.js:547)
    at Object.receiveComponent (ReactReconciler.js:125)
    at Object.updateChildren (ReactChildReconciler.js:109)
    at ReactDOMComponent._reconcilerUpdateChildren (ReactMultiChild.js:213)
</code>```

The problem I have with this is it means that the app is loading well, but I assume something in my #/home component is broken, but I have stripped this back to be nothing but a div.

All packages noteworthy:

```<code>"history": "^4.5.1",
"react": "^15.5.0",
"react-css-modules": "^4.1.0",
"react-dom": "^15.5.0",
"react-redux": "^5.0.3",
"react-router": "^4.1.1",
"react-router-dom": "^4.0.0",
"react-router-redux": "^5.0.0-alpha.6",
"react-tap-event-plugin": "^2.0.1",
"redux": "^3.6.0",
"webpack": "^2.2.1"
</code>```

Router.js

```<code>export default class Routes extends Component {
  render() {
    return (
      <div>
        <Route exact path="/" component={Splash}/>

        <Route path="/signin" component={SignIn} />
        <Route path="/logout" component={Logout} />

        <Route path="/home" component={Home}  />
        <Route path="/settings" component={Settings} />

        <Route path="/sextypeselection" component={SexTypeSelection} />
        <Route path="/desire" component={Desire} />
      </div>
    )
  }
};
</code>```

home/index.js

```<code>import React from 'react';
import { bindActionCreators } from 'redux'
import { RequireLogin } from '../shared/auth/userRedirects'
import mobiscroll from '../shared/mobiscroll/mobiscroll.custom';
import * as currentSexInfo from '../../actions/currentSexInfo'
import {connect} from 'react-redux';

//Header
import Header from '../shared/header/Header';
import RightPlus from '../shared/header/RightPlus';
import Menu from '../shared/menu';

//Styles
import HomeStyle from './home.css';

class Home extends React.Component {
  constructor (props){
    super(props);
    console.info(props);
    const now = new Date();
    this.state = {
      settings : {
        display: 'inline',
        yearChange: false,
        marked: [
          new Date(2017, 5, 4)
        ]
        , max: new Date()
        // , showOuterDays: false
      }
    };
    this.selectData = this.selectData.bind(this);
  }

  selectData = (event, inst) => {
    if(event.control) {
      this.props.DispatchChangeCurrentSexInfo(event.date);
      window.location.hash = 'sextypeselection';
    }
  };

  onPosition = (ev) => {
    let $ = mobiscroll.$,
      monthCont = $('.mbsc-cal-anim-c', ev.target),
      calHeight = document.body.offsetHeight - 375;
    monthCont.height('');
    monthCont.height(calHeight);
  };

  render(){
    return (
      <div>
        <RequireLogin />
        <Header right={<RightPlus link="sextypeselection" />} />
        <div className={HomeStyle.home}>
          <div className="pageInfo">
            <h1>My calender</h1>
            <p>Select a date to view <br/> input your information</p>
          </div>
          <div className={"cal " + HomeStyle.calenderContainer}>
            <mobiscroll.Calendar onPosition={this.onPosition} onSetDate={this.selectData} options={this.state.settings} {...this.props} />
          </div>
        </div>
        <Menu />
      </div>
    );
  }
}

function matchDispatchToProps(dispatch){
  return {DispatchChangeCurrentSexInfo : bindActionCreators(currentSexInfo.changeCurrentSexInfo, dispatch)}
}

export default connect(null,matchDispatchToProps)(Home);
</code>```

答:
Sadly it was simple in the end, I doubt anybody will have this same problem but in the end it was JSON.parse trying to work on an undefined item.

The fix:

```<code>const storage = localStorage.LOGGED_IN || {};
const loggedIn = this.props.user.loggedIn || JSON.parse(JSON.stringify(storage));
</code>```

Body:
I am using phonegap to create an app using react v15 and "webpack": "^2.2.1" to bundle up everything. I then run my webpack.prod.json to generate a stand alone .js file which is included in the app.

When I install the app locally, I have no problems and can run the application, however when I build through phonegap.com/build is when the issue occurs.

Even weirder still is that the initial state loads fine. Its when I navigate to #/home that this error occurs:

Uncaught SyntaxError: Unexpected token u in JSON at position 0
    at JSON.parse (<anonymous>)
    at RequireLogin.render (RequireLogin.js:32)
    at ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext (ReactCompositeComponent.js:799)
    at ReactCompositeComponentWrapper._renderValidatedComponent (ReactCompositeComponent.js:822)
    at ReactCompositeComponentWrapper.performInitialMount (ReactCompositeComponent.js:362)
    at ReactCompositeComponentWrapper.mountComponent (ReactCompositeComponent.js:258)
    at Object.mountComponent (ReactReconciler.js:46)
    at ReactCompositeComponentWrapper.performInitialMount (ReactCompositeComponent.js:371)
    at ReactCompositeComponentWrapper.mountComponent (ReactCompositeComponent.js:258)
    at Object.mountComponent (ReactReconciler.js:46)

RequireLogin.js

import React from 'react';
import {connect} from 'react-redux';
import {Redirect} from 'react-router'

class BlockForLoggedInUsers extends React.Component {
  constructor(props){
    super(props);
  }
  render(){
    const loggedIn = this.props.user.loggedIn || JSON.parse(localStorage.LOGGED_IN);
    if (loggedIn) {
      return (
        <Redirect push to="/home"/>
      )
    }else{
      return (

      );
    }
  }
}

function mapStateToProps(state){
  return {
    user: state.user
  };
}

export default connect(mapStateToProps)(BlockForLoggedInUsers);

Then, when I hit the back key I get a different error:

DOMLazyTree.js:69 Uncaught TypeError: Cannot read property 'replaceChild' of null
    at Function.replaceChildWithTree (DOMLazyTree.js:69)
    at Object.dangerouslyReplaceNodeWithMarkup [as replaceNodeWithMarkup] (Danger.js:41)
    at ReactCompositeComponentWrapper._replaceNodeWithMarkup (ReactCompositeComponent.js:784)
    at ReactCompositeComponentWrapper._updateRenderedComponent (ReactCompositeComponent.js:774)
    at ReactCompositeComponentWrapper._performComponentUpdate (ReactCompositeComponent.js:724)
    at ReactCompositeComponentWrapper.updateComponent (ReactCompositeComponent.js:645)
    at ReactCompositeComponentWrapper.receiveComponent (ReactCompositeComponent.js:547)
    at Object.receiveComponent (ReactReconciler.js:125)
    at Object.updateChildren (ReactChildReconciler.js:109)
    at ReactDOMComponent._reconcilerUpdateChildren (ReactMultiChild.js:213)

The problem I have with this is it means that the app is loading well, but I assume something in my #/home component is broken, but I have stripped this back to be nothing but a div.

All packages noteworthy:

"history": "^4.5.1",
"react": "^15.5.0",
"react-css-modules": "^4.1.0",
"react-dom": "^15.5.0",
"react-redux": "^5.0.3",
"react-router": "^4.1.1",
"react-router-dom": "^4.0.0",
"react-router-redux": "^5.0.0-alpha.6",
"react-tap-event-plugin": "^2.0.1",
"redux": "^3.6.0",
"webpack": "^2.2.1"

Router.js

export default class Routes extends Component {
  render() {
    return (

        <Route exact path="/" component={Splash}/>

        <Route path="/signin" component={SignIn} />
        <Route path="/logout" component={Logout} />

        <Route path="/home" component={Home}  />
        <Route path="/settings" component={Settings} />

        <Route path="/sextypeselection" component={SexTypeSelection} />
        <Route path="/desire" component={Desire} />

    )
  }
};

home/index.js

import React from 'react';
import { bindActionCreators } from 'redux'
import { RequireLogin } from '../shared/auth/userRedirects'
import mobiscroll from '../shared/mobiscroll/mobiscroll.custom';
import * as currentSexInfo from '../../actions/currentSexInfo'
import {connect} from 'react-redux';

//Header
import Header from '../shared/header/Header';
import RightPlus from '../shared/header/RightPlus';
import Menu from '../shared/menu';

//Styles
import HomeStyle from './home.css';

class Home extends React.Component {
  constructor (props){
    super(props);
    console.info(props);
    const now = new Date();
    this.state = {
      settings : {
        display: 'inline',
        yearChange: false,
        marked: [
          new Date(2017, 5, 4)
        ]
        , max: new Date()
        // , showOuterDays: false
      }
    };
    this.selectData = this.selectData.bind(this);
  }

  selectData = (event, inst) => {
    if(event.control) {
      this.props.DispatchChangeCurrentSexInfo(event.date);
      window.location.hash = 'sextypeselection';
    }
  };

  onPosition = (ev) => {
    let $ = mobiscroll.$,
      monthCont = $('.mbsc-cal-anim-c', ev.target),
      calHeight = document.body.offsetHeight - 375;
    monthCont.height('');
    monthCont.height(calHeight);
  };

  render(){
    return (

        <RequireLogin />
        <Header right={<RightPlus link="sextypeselection" />} />

My calender

Select a date to view
 input your information

            <mobiscroll.Calendar onPosition={this.onPosition} onSetDate={this.selectData} options={this.state.settings} {...this.props} />

        <Menu />

    );
  }
}

function matchDispatchToProps(dispatch){
  return {DispatchChangeCurrentSexInfo : bindActionCreators(currentSexInfo.changeCurrentSexInfo, dispatch)}
}

export default connect(null,matchDispatchToProps)(Home);

Body:
Sadly it was simple in the end, I doubt anybody will have this same problem but in the end it was JSON.parse trying to work on an undefined item.

The fix:

const storage = localStorage.LOGGED_IN || {};
const loggedIn = this.props.user.loggedIn || JSON.parse(JSON.stringify(storage));


来源: stackexchange

问:
Infopath 2013 Buttons
We have developed a form that is being used via SharePoint 2013.  We would like the audience to be able to click on a list item to open up the InfoPath form and then when in the InfoPath form, press on the created buttons to load different views of the form and hide/show certain sections....without it being in Edit mode.

The premise being that the end user has an interactive form that is quick and easy to use upon loading.

Is there any way that a user can activate the rules applied to the buttons in Read mode or does Edit mode always have to be activated first?

Many thanks in advance for any hints or tips!

答:
Well technically you can create a Read-Only form by making all the Pages Read-Only in their settings and use data connections to pull the data into the form fields you want. </p>

<p>So I would make a landing page with buttons that would change the view, run a query and set fields values that you want to display for each Read-Only page/view. </p>

ContentLicense: CC BY-SA 3.0

Title: Infopath 2013 Buttons

Body:
Well technically you can create a Read-Only form by making all the Pages Read-Only in their settings and use data connections to pull the data into the form fields you want.

So I would make a landing page with buttons that would change the view, run a query and set fields values that you want to display for each Read-Only page/view.


问:
SqlConnection.Open() hangs in .NET Core Consol project, but connects fine in a regular C# console project
My program connects to the server fine in a C# console project using the following code:

```<code>public static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            System.Data.SqlClient.SqlConnection conn =
                new System.Data.SqlClient.SqlConnection();

            string connectionString = "Data Source=IPOfServer;" +
                "Initial Catalog=nameOfDatabase;"+
                "User ID=USERNAME;" +
                "Password=PASSWORD";

            conn.ConnectionString = connectionString;

            try
            {
                Console.WriteLine("Before Connection");
                conn.Open();
                Console.WriteLine("Connection Open");
                conn.Close();
                Console.WriteLine("Connection Closed");
            }
            catch (Exception ex)
            {
                Console.WriteLine(String.Format("Can't Connect; Error:{0}", ex.Message));
            }
        }
</code>```

And outputs:

```<code>Hello World!
Before Connection
Connection Open
Connection Closed
</code>```

When I try the exact same code in a .NET Core Console project, my output is:

```<code>Hello World!
Before Connection
</code>```

But the program does not ever error or end. It just hangs forever.

I am using the packages System.Data.Common and System.Data.SqlClient

It is a MSSQL 2005 Server that I am attempting to connect to.

What am I doing wrong/how do I connect to my server using a .NET Core Console project? I looked into using the EntityFramework, but would prefer to not use it unless that is my only option.

答:
Try the following:

Open existing Solution in Visual Studio 2015. Now, add new Client
  Library .NET Core project in Solution.

Open Add New Project Screen through Solution Context Menu >> Add >>
  New Project Or File >> New >> Project. Select Class Library (.NET
  Core) Template through Installed >> Templates >> Visual C# >> .NET
  Core. Name project as “WebApplicationCore.NetCore.DataAccess”. Set
  suitable location as “C:\ASP.NET Core\Welcome To .NET Core 1.0\
  ASP.NET Core” (selected by default to solution root). Click OK button.

It will create a new class library project.

Add Reference to Microsoft.EntityFrameworkCore.SqlServer, using one of
  following methods.

Open Package Manger Console through Tools >> NuGet Packet Manger >>
  Package Manger Console and run install command "Install-Package
  Microsoft.EntityFrameworkCore.SqlServer" for
  WebApplicationCore.NetCore.DataAccess project.

Open NuGet Manager through WebApplicationCore.NetCore.DataAccess
  Reference context menu >> References >> Manage NuGet Packages. in
  Browse tab search for "Microsoft.EntityFrameworkCore.SqlServer" and
  install.

Rename Class1 as BaseDataAccess and add the required implementation to
  connect to SQL Server Database.

- Source (csharpcorner)

Similar question on StackOverflow

Body:
My program connects to the server fine in a C# console project using the following code:

public static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            System.Data.SqlClient.SqlConnection conn =
                new System.Data.SqlClient.SqlConnection();

            string connectionString = "Data Source=IPOfServer;" +
                "Initial Catalog=nameOfDatabase;"+
                "User ID=USERNAME;" +
                "Password=PASSWORD";

            conn.ConnectionString = connectionString;

            try
            {
                Console.WriteLine("Before Connection");
                conn.Open();
                Console.WriteLine("Connection Open");
                conn.Close();
                Console.WriteLine("Connection Closed");
            }
            catch (Exception ex)
            {
                Console.WriteLine(String.Format("Can't Connect; Error:{0}", ex.Message));
            }
        }

And outputs:

Hello World!
Before Connection
Connection Open
Connection Closed

When I try the exact same code in a .NET Core Console project, my output is:

Hello World!
Before Connection

But the program does not ever error or end. It just hangs forever.

I am using the packages System.Data.Common and System.Data.SqlClient

It is a MSSQL 2005 Server that I am attempting to connect to.

What am I doing wrong/how do I connect to my server using a .NET Core Console project? I looked into using the EntityFramework, but would prefer to not use it unless that is my only option.


问:
php mailer in function generates error
I created a function to handle email sending using PHPMailer

this is the function:

```<code>function sendEmail($from, $replyTo, $to, $subject, $message) {
$mail = new PHPMailer;

//$mail->SMTPDebug = 3;                               // Enable verbose debug output

$mail->isSMTP();                                      // Set mailer to use SMTP
$mail->Host = 'mail.pickbyclick.ro';  // Specify main and backup SMTP servers
$mail->SMTPAuth = false;
$mail->Username = 'admin@pickbyclick.ro';
$mail->Port = 25;

$mail->setFrom($from, 'Pick by Click Team');
$mail->addReplyTo($replyTo);
$mail->addAdress($to);
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = emailShowNice($message);
$mail->AltBody = $message;
if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}
</code>```

}

And after this call

```<code>sendEmail($from, "no-reply@pickbyclick.ro", $to, $subject, $message);
</code>```

It shows 500 error server. Can anyone please help me?

Edit: this is the emailShowNice function

```<code>function emailShowNice($message) {

$order   = array('\r', '\n', '\r\n', "\r", "\n", "\r\n");
$replace = ' <br /> ';

$mes = str_replace($order, $replace, $message);

return $mes;
}
</code>```

答:
Replace the line a mistake here

```<code>$mail->addAdress($to);
</code>```

with

```<code>$mail->addAddress($to);
</code>```

Title: php mailer in function generates error

Body:
I created a function to handle email sending using PHPMailer

this is the function:

function sendEmail($from, $replyTo, $to, $subject, $message) {
$mail = new PHPMailer;

//$mail->SMTPDebug = 3;                               // Enable verbose debug output

$mail->isSMTP();                                      // Set mailer to use SMTP
$mail->Host = 'mail.pickbyclick.ro';  // Specify main and backup SMTP servers
$mail->SMTPAuth = false;
$mail->Username = 'admin@pickbyclick.ro';
$mail->Port = 25;

$mail->setFrom($from, 'Pick by Click Team');
$mail->addReplyTo($replyTo);
$mail->addAdress($to);
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = emailShowNice($message);
$mail->AltBody = $message;
if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}

}

And after this call

sendEmail($from, "no-reply@pickbyclick.ro", $to, $subject, $message);

It shows 500 error server. Can anyone please help me?

Edit: this is the emailShowNice function

function emailShowNice($message) {

$order   = array('\r', '\n', '\r\n', "\r", "\n", "\r\n");
$replace = '
 ';

$mes = str_replace($order, $replace, $message);

return $mes;
}

Body:
Replace the line a mistake here

$mail->addAdress($to);

with

$mail->addAddress($to);


问:
Windows Command Line - Select Server Based upon Ping Latency
Ok basic premise here is that there are two servers with the same files.

I'm using Windows command line scripts and opening a network share to either of those hosts. I'd like to make the script "smart" so it works out the latency between the two servers and picks the lowest latency host to connect to.

I want to do something like (i know this code doesn't work, it's an example of my concept):

```<code>PING 192.168.0.1
SET HOST1=%ERRORLEVEL%
PING 192.168.0.2
SET HOST2=%ERRORLEVEL%
IF HOST1 GTR HOST2 GOTO HOST2CONNECT
:HOST1CONNECT
NET USE X: \\HOST1 (etc)
:HOST2CONNECT
NET USE X: \\HOST2 (etc)
</code>```

Does that make any sense? I just can't seem to visualise a way of comparing the data from the two PING tests and i know that ERRORLEVEL in this situation is just a 1 or 0 based upon whether the ping is successful or not, so it's garbage as they'll both succeed. But i'm hoping you get the concept and can see what i'm missing.

Thanks in advance.

答:
MC ND posted his answer before I did so he should deserve the credits. Please do not mark this as the answer, that is not the intention of my post.

Because I had already made the effort of posting an answer as well and for sake of completeness, I feel that it doesn't hurt to post another approach to deal with the problem. The main difference is that I've chosen to use the average round-trip times of the ping command and provide a way to store the latency times and target host names in a group of variables that could be considered an array of structures.

Keep in mind that measuring round-trip latency with the ping command is not very accurate and the results can fluctuate tremendously. Referring to the following quote from Wikipedia:

Many software platforms provide a service called ping that can be used
  to measure round-trip latency. Ping performs no packet processing; it
  merely sends a response back when it receives a packet (i.e. performs
  a no-op), thus it is a first rough way of measuring latency. Ping
  cannot perform accurate measurements, principally because it uses the
  ICMP protocol that is used only for diagnostic or control purposes,
  and differs from real communication protocols such as TCP.
  Furthermore, routers and ISP's might apply different traffic shaping
  policies to different protocols.

```<code>@echo off

setlocal enabledelayedexpansion
set targets="192.168.0.1" "192.168.0.2"

for %%e in (%targets%) do (
  call :GetAverageLatency %%e latency

  if errorlevel 1 (
    echo Unable to obtain latency from host: %%~e
    exit /b
  )

  set /a count+=1
  set "host[!count!].name=%%~e"
  set "host[!count!].latency=!latency!"

  if -!latency! gtr -!lowest! (
    set lowest=!latency!
    set index=!count!
  )
)

echo;Mapping network drive to host: !host[%index%].name!
echo;

net use * "\\!host[%index%].name!"
set host

exit /b

:GetAverageLatency (__in hostName, __out *latency) {
  for /f "skip=10 tokens=13 delims=m " %%e in ('ping "%~1"') do (
    set "%2=%%e"
    exit /b 0
  )
  exit /b 1
}
</code>```

The set host command is obviously not necessary but it used to show the values stored in the host* variables.

Body:
Ok basic premise here is that there are two servers with the same files.

I'm using Windows command line scripts and opening a network share to either of those hosts. I'd like to make the script "smart" so it works out the latency between the two servers and picks the lowest latency host to connect to.

I want to do something like (i know this code doesn't work, it's an example of my concept):

PING 192.168.0.1
SET HOST1=%ERRORLEVEL%
PING 192.168.0.2
SET HOST2=%ERRORLEVEL%
IF HOST1 GTR HOST2 GOTO HOST2CONNECT
:HOST1CONNECT
NET USE X: \\HOST1 (etc)
:HOST2CONNECT
NET USE X: \\HOST2 (etc)

Does that make any sense? I just can't seem to visualise a way of comparing the data from the two PING tests and i know that ERRORLEVEL in this situation is just a 1 or 0 based upon whether the ping is successful or not, so it's garbage as they'll both succeed. But i'm hoping you get the concept and can see what i'm missing.

Thanks in advance.

Body:
MC ND posted his answer before I did so he should deserve the credits. Please do not mark this as the answer, that is not the intention of my post.

Because I had already made the effort of posting an answer as well and for sake of completeness, I feel that it doesn't hurt to post another approach to deal with the problem. The main difference is that I've chosen to use the average round-trip times of the ping command and provide a way to store the latency times and target host names in a group of variables that could be considered an array of structures.

Keep in mind that measuring round-trip latency with the ping command is not very accurate and the results can fluctuate tremendously. Referring to the following quote from Wikipedia:

Many software platforms provide a service called ping that can be used
  to measure round-trip latency. Ping performs no packet processing; it
  merely sends a response back when it receives a packet (i.e. performs
  a no-op), thus it is a first rough way of measuring latency. Ping
  cannot perform accurate measurements, principally because it uses the
  ICMP protocol that is used only for diagnostic or control purposes,
  and differs from real communication protocols such as TCP.
  Furthermore, routers and ISP's might apply different traffic shaping
  policies to different protocols.

@echo off

setlocal enabledelayedexpansion
set targets="192.168.0.1" "192.168.0.2"

for %%e in (%targets%) do (
  call :GetAverageLatency %%e latency

  if errorlevel 1 (
    echo Unable to obtain latency from host: %%~e
    exit /b
  )

  set /a count+=1
  set "host[!count!].name=%%~e"
  set "host[!count!].latency=!latency!"

  if -!latency! gtr -!lowest! (
    set lowest=!latency!
    set index=!count!
  )
)

echo;Mapping network drive to host: !host[%index%].name!
echo;

net use * "\\!host[%index%].name!"
set host

exit /b

:GetAverageLatency (__in hostName, __out *latency) {
  for /f "skip=10 tokens=13 delims=m " %%e in ('ping "%~1"') do (
    set "%2=%%e"
    exit /b 0
  )
  exit /b 1
}

The set host command is obviously not necessary but it used to show the values stored in the host* variables.


问:
Restrict date in jquery datepicker based on another datepicker or textbox
I have two text boxes with a datepicker hooked up to them. The text boxes are for start date and end date. The first datepicker is setup so that the user cannot choose a date before today, but can choose any date in the future.

How can I setup the second datepicker so that it cannot choose a date before the date chosen in the first date picker? For example: If today is 12/11/10 and I choose 12/15/10 in the first datepicker, then the second date picker shouldn't be able to choose anything before 12/15/10.

Heres what I have so far:

```<code>$("#txtStartDate").datepicker({ minDate: 0 });
$("#txtEndDate").datepicker({});
</code>```

答:
Use the "getDate" method of the first datepicker UI and pass it into minDate option of the second datepicker:

```<code>$("#txtEndDate").datepicker({
    showOn: "both",
    minDate: $("#txtStartDate").datepicker("getDate")
});
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have two text boxes with a datepicker hooked up to them. The text boxes are for start date and end date. The first datepicker is setup so that the user cannot choose a date before today, but can choose any date in the future.

How can I setup the second datepicker so that it cannot choose a date before the date chosen in the first date picker? For example: If today is 12/11/10 and I choose 12/15/10 in the first datepicker, then the second date picker shouldn't be able to choose anything before 12/15/10.

Heres what I have so far:

$("#txtStartDate").datepicker({ minDate: 0 });
$("#txtEndDate").datepicker({});

Body:
Use the "getDate" method of the first datepicker UI and pass it into minDate option of the second datepicker:

$("#txtEndDate").datepicker({
    showOn: "both",
    minDate: $("#txtStartDate").datepicker("getDate")
});


问:
Send email async: An asynchronous module or handler completed while an asynchronous operation was still pending
I'm trying to send email from a Controller asynchronous and getting the following error:

I don't want to wait email be sent to complete the action.

An asynchronous module or handler completed while an asynchronous
  operation was still pending.

This is my implementation: I also tried using void instead async Task

```<code>public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    var user = await _userManager.FindByNameAsync(model.Email);
    if (user != null)
    {
        if (!await _userManager.IsEmailConfirmedAsync(user.Id))
        {

            //dont want to await result
            //just send email
            _mailService.SendAccountConfirmationEmailAsync(user);
            ...
        }
        ...
    }
    return View();
}
</code>```

.

```<code>public async Task SendAccountConfirmationEmailAsync(ApplicationUser user)
{
    dynamic email = GetAccountConfirmationEmailTemplate();

    email.Username = user.Email;
    email.Name = user.UserName;
    email.To = user.Email;
    email.AccountConfirmationUrl = await GetAccountConfirmationUrl(user);

    await _mailService.SendAsync(email);
}
</code>```

What am I missing?

答:
You need to await your async call in order to avoid the error message, but then you'll need to wait for the email to finish sending before your action method returns (and a failure sending the email will cause your action method to error out).

```<code>await _mailService.SendAccountConfirmationEmailAsync(user);
</code>```

If you ever see a method name that ends in -Async, check if that method returns a Task or Task. If it does, you need to await it.

If you have an async call that you don't want to wait for it to complete in this context, you'll get that error. If you want to continue processing, you'll need some method of sending this email in a background task. That might be that you have a separate application that handles emails, and you communicate with it via a messaging system like RabbitMQ. Or there are ways to run code in the background directly in a website such as Hangfire.

Body:
I'm trying to send email from a Controller asynchronous and getting the following error:

I don't want to wait email be sent to complete the action.

An asynchronous module or handler completed while an asynchronous
  operation was still pending.

This is my implementation: I also tried using void instead async Task

public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    var user = await _userManager.FindByNameAsync(model.Email);
    if (user != null)
    {
        if (!await _userManager.IsEmailConfirmedAsync(user.Id))
        {

            //dont want to await result
            //just send email
            _mailService.SendAccountConfirmationEmailAsync(user);
            ...
        }
        ...
    }
    return View();
}

.

public async Task SendAccountConfirmationEmailAsync(ApplicationUser user)
{
    dynamic email = GetAccountConfirmationEmailTemplate();

    email.Username = user.Email;
    email.Name = user.UserName;
    email.To = user.Email;
    email.AccountConfirmationUrl = await GetAccountConfirmationUrl(user);

    await _mailService.SendAsync(email);
}

What am I missing?

Body:
You need to await your async call in order to avoid the error message, but then you'll need to wait for the email to finish sending before your action method returns (and a failure sending the email will cause your action method to error out).

await _mailService.SendAccountConfirmationEmailAsync(user);

If you ever see a method name that ends in -Async, check if that method returns a Task or Task. If it does, you need to await it.

If you have an async call that you don't want to wait for it to complete in this context, you'll get that error. If you want to continue processing, you'll need some method of sending this email in a background task. That might be that you have a separate application that handles emails, and you communicate with it via a messaging system like RabbitMQ. Or there are ways to run code in the background directly in a website such as Hangfire.


问:
Pass data to pug using pug-html-loader (cannot read property of undefined)
According to the readme of pug-html-loader, the loader accepts a data object which is being passed as part of the options to the template. While not available on the options within the pug API reference, a grunt plugin I've found (grunt-contrib-pug) uses the API the same way.

I've specified the following options for the loader:

```<code>  loader: 'pug-html-loader',
  options: {
    pretty: true,
    exports: false,
    debug: !env.production,
    compileDebug: !env.production,
    cache: config.build.useCaching,
    doctype: 'html',
    data: {
      title:    config.metadata.title,
      baseUrl:  config.build.baseUrl,
      server:   env.server,
      metadata: config.metadata
    }
  }
</code>```

Which I'd like to access the following way, according to this question:

```<code>title= data.title
</code>```

However, I always run into the following error when compiling:

```<code>ERROR in   Error: Child compilation failed:
  Module build failed: TypeError: Cannot read property 'title' of undefined
</code>```

For debugging purposes, I've included the following line in the template:

```<code>-
  console.log(' DATA! ' + data);
</code>```

Which results in:

```<code>DATA! undefined
</code>```

I've also ensured that the data is correctly being passed to pug by declaring some gibberish instead of an object (e.g. a string, plain json, a number..), then the pug compiler complains that the data is not in valid format etc.

Anyone facing the same issue?

答:
You should reference data directy (i.e. without prefixing the fields with data)

So you should change your code like so:

```<code>{
  loader: 'pug-html-loader',
  options: {
    data: {
      title: 'Hello World'
    }
  }
}
</code>```

And then reference it from your PUG template Updated

```<code>doctype html
html
  head
    title= title
</code>```

Body:
According to the readme of pug-html-loader, the loader accepts a data object which is being passed as part of the options to the template. While not available on the options within the pug API reference, a grunt plugin I've found (grunt-contrib-pug) uses the API the same way.

I've specified the following options for the loader:

  loader: 'pug-html-loader',
  options: {
    pretty: true,
    exports: false,
    debug: !env.production,
    compileDebug: !env.production,
    cache: config.build.useCaching,
    doctype: 'html',
    data: {
      title:    config.metadata.title,
      baseUrl:  config.build.baseUrl,
      server:   env.server,
      metadata: config.metadata
    }
  }

Which I'd like to access the following way, according to this question:

title= data.title

However, I always run into the following error when compiling:

ERROR in   Error: Child compilation failed:
  Module build failed: TypeError: Cannot read property 'title' of undefined

For debugging purposes, I've included the following line in the template:

-
  console.log(' DATA! ' + data);

Which results in:

DATA! undefined

I've also ensured that the data is correctly being passed to pug by declaring some gibberish instead of an object (e.g. a string, plain json, a number..), then the pug compiler complains that the data is not in valid format etc.

Anyone facing the same issue?

Body:
You should reference data directy (i.e. without prefixing the fields with data)

So you should change your code like so:

{
  loader: 'pug-html-loader',
  options: {
    data: {
      title: 'Hello World'
    }
  }
}

And then reference it from your PUG template Updated

doctype html
html
  head
    title= title

ContentLicense: CC BY-SA 4.0


问:
Java: Printing ALL Args as single string
Ok, I want a line of code That will allow me to print all args as one string.

Example of what i need: lets say arg[0] = "Hi"; and lets say arg[1] =
"there";

i want it to print "Hi there", not something like [Hi, there] when you use
Array.toString()

Thanks - Jay (0-0)/

答:
In java 8 you can use this</p>

```<code>Arrays.asList(args).forEach(x -> System.out.print(x + " "));
</code>```

Body:
In java 8 you can use this

Arrays.asList(args).forEach(x -> System.out.print(x + " "));


问:
How to search multiple keywords in file using nodejs?
Lets say i have multiple search keywords from client side searchStr that should match with the line in file , how i will match both text with each line in file and push that line to results. With below code i am getting empty response of results, Any idea what is implemented wrong ?

search.js

```<code>  function asyncFiles(filesData) {
     async.eachSeries(filesData.logFiles, function(logfile, done) {
         // read file
         readStream = fs.createReadStream('./logs/' + filesData.searchEnv + '/' + logfile.filename, 'utf8')
         readStream.pipe(split())
             .on('data', function(line) {
               var searchStr = [{"text":"4588769"},{"text":"request"}]
                 searchStr.forEach(function(text) {
                     if (line.toLowerCase().indexOf(text.toLowerCase()) != -1)
                         var messageDateInfo = line.split('|')[0].replace(/[\[\]']+/g, '');
                     messageDateInfo = new Date(messageDateInfo).getTime();
                     searchStartDate = new Date(searchStartDate).getTime();
                     searchEndDate = new Date(searchEndDate).getTime();
                     if (messageDateInfo - searchStartDate > 0 && searchEndDate - messageDateInfo > 0) {
                         results.push({
                             filename: logfile.filename,
                             value: line
                         });
                     }
                 });
             });
         done();
     }, function(err) {
         if (err) {
             console.log('error', err);
         }
         readStream.on('end', function() {
             callback(results);
         });
         results = [];
     });
 }
</code>```

答:
your question does not clearly show what happend with results but this code should return certain value of results without any dependence:

function asyncFiles(filesData) {
     async.eachSeries(filesData.logFiles, function(logfile, done) {
         // read file
         readStream = fs.createReadStream('./logs/' + filesData.searchEnv + '/' + logfile.filename, 'utf8')
         readStream.pipe(split())
             .on('data', function(line) {
               var searchStr = [{"text":"4588769"},{"text":"request"}]
                 searchStr.forEach(function(text) {
                     if (line.toLowerCase().indexOf(text.toLowerCase()) != -1)
                         var messageDateInfo = line.split('|')[0].replace(/[\[\]']+/g, '');
                     messageDateInfo = new Date(messageDateInfo).getTime();
                     searchStartDate = new Date(searchStartDate).getTime();
                     searchEndDate = new Date(searchEndDate).getTime();
                     if (messageDateInfo - searchStartDate > 0 && searchEndDate - messageDateInfo > 0) {
                         results.push({
                             filename: logfile.filename,
                             value: line
                         });
                     }
                 });
             });
         done();
     }, function(err) {
         if (err) {
             console.log('error', err);
         }
         readStream.on('end', function() {
             setTimeout(function(){callback(results);},2000)
           });
           //results = [];
        });
    }

Body:
Lets say i have multiple search keywords from client side searchStr that should match with the line in file , how i will match both text with each line in file and push that line to results. With below code i am getting empty response of results, Any idea what is implemented wrong ?

search.js

  function asyncFiles(filesData) {
     async.eachSeries(filesData.logFiles, function(logfile, done) {
         // read file
         readStream = fs.createReadStream('./logs/' + filesData.searchEnv + '/' + logfile.filename, 'utf8')
         readStream.pipe(split())
             .on('data', function(line) {
               var searchStr = [{"text":"4588769"},{"text":"request"}]
                 searchStr.forEach(function(text) {
                     if (line.toLowerCase().indexOf(text.toLowerCase()) != -1)
                         var messageDateInfo = line.split('|')[0].replace(/[\[\]']+/g, '');
                     messageDateInfo = new Date(messageDateInfo).getTime();
                     searchStartDate = new Date(searchStartDate).getTime();
                     searchEndDate = new Date(searchEndDate).getTime();
                     if (messageDateInfo - searchStartDate > 0 && searchEndDate - messageDateInfo > 0) {
                         results.push({
                             filename: logfile.filename,
                             value: line
                         });
                     }
                 });
             });
         done();
     }, function(err) {
         if (err) {
             console.log('error', err);
         }
         readStream.on('end', function() {
             callback(results);
         });
         results = [];
     });
 }


问:
Is it bad to create a big array just to be sure?
I'm working on a project for school. I implemented some arrays in my application to store some codes, so they are int arrays. The user of the program will import an excel sheet, and depending on the number of rows from the excel sheet, the program will generate codes. If the excel sheet as 5 rows, it will generate 5 codes, but if it has 5000 codes, it will generate 5000 codes.

I created an array of 99999 big with: int[] name = new int[999999] just to be sure, because I'm sure they will never go over 99999. Is that a bad way of coding? The program has to be efficient and stuff.

Edit: Thank you all very much. I already got a method which counts the number of rows in the Excel sheet but I didn't think of using int[] name = new int[rows]. Thanks a lot! And I will remember to use ArrayLists in the future! Thanks!

答:
This will impact performance, so create the array as the user imports the data so you can create just the right size. For example if I want to store numbers in an array yet I do not know the input I can simply.

```<code>public class Arrays {

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    System.out.println("enter number of elements");

    int n = input.nextInt();

    int arr[] = new int[n];

    System.out.println("enter elements");

    for(int i = 0;i<n;i++){//for reading array
        arr[i]=input.nextInt();

    }

    for(int i: arr){ //for printing array

        System.out.println(i);

    }

}
</code>```

This ensures that you never create more than you need and never have to little. So find a way to read the amount of excel tables when they are imported and create and array with that as it's size!

Body:
This will impact performance, so create the array as the user imports the data so you can create just the right size. For example if I want to store numbers in an array yet I do not know the input I can simply.

public class Arrays {

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    System.out.println("enter number of elements");

    int n = input.nextInt();

    int arr[] = new int[n];

    System.out.println("enter elements");

    for(int i = 0;i<n;i++){//for reading array
        arr[i]=input.nextInt();

    }

    for(int i: arr){ //for printing array

        System.out.println(i);

    }

}

This ensures that you never create more than you need and never have to little. So find a way to read the amount of excel tables when they are imported and create and array with that as it's size!


问:
Crystal Reports Error in formula
I have a global variable which was declared in a formula in the Report Header section of my document.  I then try to reference that variable to use it in a for loop, and I get the error:

A number, currency amount, boolean,
  data, time, date-time, or string is
  expected here.

What is wrong here and how can I correct?  Code follows:

Header Formula:

```<code>Global StringVar Array items;
redim items [1];

Global StringVar Array jobs;
redim jobs [1];

Global StringVar Array POs;
redim POs [1];

Global StringVar Array Qty;
redim Qty [1];

Global NumberVar numRecordsPrinted;
numRecordsPrinted := 0;

""
</code>```

Detail Formula:

```<code>    Local NumberVar occurances;
    Local StringVar poTOuse;
    Local NumberVar i;

    if {%Line_PO_Test} <> ''
    and {PackingSlipHeader.CompanyCode} <> '10063'
    and {PackingSlipHeader.CompanyCode} <> '10017'
    then
        //Count the number of occurances
        For i := 0 To numRecordsPrinted Do       //Error on numRecordsPrinted
        (
            if items[i] = {PS_DETAIL_FOR_PRINT.DTSItemNumber}
                AND jobs[i] = {PS_DETAIL_FOR_PRINT.JobNumber}
                And Qty[i] = {PS_DETAIL_FOR_PRINT.Quantity_Shipped}
                THEN
                    occurances := occurances + 1
        )

        //Use the # of occurances to get the right PO number
Select occurances
        case 0: poTOuse := {@LinePOnum}
        case 1: poTOuse := {@Line_PO_3}
        case 2: poTOuse := {@Line_PO_2}

        default: poTOuse := "";

        //Save data into the array and increment for next time
        numRecordsPrinted := numRecordsPrinted + 1
        items[numRecordsPrinted] := {PS_DETAIL_FOR_PRINT.DTSItemNumber}
        jobs[numRecordsPrinted] := {PS_DETAIL_FOR_PRINT.JobNumber}
        Qty[numRecordsPrinted] :=   {PS_DETAIL_FOR_PRINT.Quantity_Shipped}

    //Print to the report
    'PO#: ' + poTOuse;
</code>```

答:
Surely this bit :

```<code>    Select occurances
        case 0: poTOuse = LinePOnum
        case 1: poTOuse = Line_PO_3
        case 2: poTOuse = Line_PO_2

        default: poTOuse = "";
</code>```

should be

```<code>    Select occurances
        case 0: poTOuse := LinePOnum
        case 1: poTOuse := Line_PO_3
        case 2: poTOuse := Line_PO_2

        default: poTOuse := "";
</code>```

Although it's not clear what LinePOnum, Line_PO_3 and Line_PO_2 are.

Title: Crystal Reports Error in formula

Body:
I have a global variable which was declared in a formula in the Report Header section of my document.  I then try to reference that variable to use it in a for loop, and I get the error:

A number, currency amount, boolean,
  data, time, date-time, or string is
  expected here.

What is wrong here and how can I correct?  Code follows:

Header Formula:

Global StringVar Array items;
redim items [1];

Global StringVar Array jobs;
redim jobs [1];

Global StringVar Array POs;
redim POs [1];

Global StringVar Array Qty;
redim Qty [1];

Global NumberVar numRecordsPrinted;
numRecordsPrinted := 0;

""

Detail Formula:

    Local NumberVar occurances;
    Local StringVar poTOuse;
    Local NumberVar i;

    if {%Line_PO_Test} <> ''
    and {PackingSlipHeader.CompanyCode} <> '10063'
    and {PackingSlipHeader.CompanyCode} <> '10017'
    then
        //Count the number of occurances
        For i := 0 To numRecordsPrinted Do       //Error on numRecordsPrinted
        (
            if items[i] = {PS_DETAIL_FOR_PRINT.DTSItemNumber}
                AND jobs[i] = {PS_DETAIL_FOR_PRINT.JobNumber}
                And Qty[i] = {PS_DETAIL_FOR_PRINT.Quantity_Shipped}
                THEN
                    occurances := occurances + 1
        )

        //Use the # of occurances to get the right PO number
Select occurances
        case 0: poTOuse := {@LinePOnum}
        case 1: poTOuse := {@Line_PO_3}
        case 2: poTOuse := {@Line_PO_2}

        default: poTOuse := "";

        //Save data into the array and increment for next time
        numRecordsPrinted := numRecordsPrinted + 1
        items[numRecordsPrinted] := {PS_DETAIL_FOR_PRINT.DTSItemNumber}
        jobs[numRecordsPrinted] := {PS_DETAIL_FOR_PRINT.JobNumber}
        Qty[numRecordsPrinted] :=   {PS_DETAIL_FOR_PRINT.Quantity_Shipped}

    //Print to the report
    'PO#: ' + poTOuse;

Body:
Surely this bit :

    Select occurances
        case 0: poTOuse = LinePOnum
        case 1: poTOuse = Line_PO_3
        case 2: poTOuse = Line_PO_2

        default: poTOuse = "";

should be

    Select occurances
        case 0: poTOuse := LinePOnum
        case 1: poTOuse := Line_PO_3
        case 2: poTOuse := Line_PO_2

        default: poTOuse := "";

Although it's not clear what LinePOnum, Line_PO_3 and Line_PO_2 are.


答:
If you know that you will be adding 99999 elements to the array every time, then this it would be fine. However, since it can happen that you only end up needing to store 500 elements in the array, then you have allocated a huge amount of space that will not be used.

In the case of the excel sheet, it is best to first check how many rows the excel sheet given has (from your post, it seems that the number of columns is irrelevant). That way, you can assign exactly the amount of space you need everytime, like this:

```<code>int[] name = new int[rows]
</code>```

Title: Is it bad to create a big array just to be sure?

Body:
I'm working on a project for school. I implemented some arrays in my application to store some codes, so they are int arrays. The user of the program will import an excel sheet, and depending on the number of rows from the excel sheet, the program will generate codes. If the excel sheet as 5 rows, it will generate 5 codes, but if it has 5000 codes, it will generate 5000 codes.

I created an array of 99999 big with: int[] name = new int[999999] just to be sure, because I'm sure they will never go over 99999. Is that a bad way of coding? The program has to be efficient and stuff.

Edit: Thank you all very much. I already got a method which counts the number of rows in the Excel sheet but I didn't think of using int[] name = new int[rows]. Thanks a lot! And I will remember to use ArrayLists in the future! Thanks!

Body:
If you know that you will be adding 99999 elements to the array every time, then this it would be fine. However, since it can happen that you only end up needing to store 500 elements in the array, then you have allocated a huge amount of space that will not be used.

In the case of the excel sheet, it is best to first check how many rows the excel sheet given has (from your post, it seems that the number of columns is irrelevant). That way, you can assign exactly the amount of space you need everytime, like this:

int[] name = new int[rows]


问:
Why TO_UTC_TIMESTAMP in hive returns wrong year?
Trying to run a simple query in hive CLI -

```<code>select to_utc_timestamp(unix_timestamp("04/24/2017 01:59:01","MM/dd/YYYY HH:mm:ss"),'EST');
</code>```

result:

```<code>OK
1970-01-18 09:00:35.941
Time taken: 0.448 seconds, Fetched: 1 row(s)
</code>```

Shouldn't the output be just date plus 4 hours?

答:
Here we go.  You need to wrap your unix_timestamp in a from_unixtime.

```<code>select to_utc_timestamp(from_unixtime(unix_timestamp('04/24/2017 01:59:01','MM/dd/yyyy hh:mm:ss'),'yyyy-MM-dd hh:mm:ss'),"EST");
</code>```

Body:
Trying to run a simple query in hive CLI -

select to_utc_timestamp(unix_timestamp("04/24/2017 01:59:01","MM/dd/YYYY HH:mm:ss"),'EST');

result:

OK
1970-01-18 09:00:35.941
Time taken: 0.448 seconds, Fetched: 1 row(s)

Shouldn't the output be just date plus 4 hours?

Body:
Here we go.  You need to wrap your unix_timestamp in a from_unixtime.

select to_utc_timestamp(from_unixtime(unix_timestamp('04/24/2017 01:59:01','MM/dd/yyyy hh:mm:ss'),'yyyy-MM-dd hh:mm:ss'),"EST");


问:
How do I pull the clientID of an asp:button inside an asp:listview for use with jQuery?
I'm attempting to do something which should be relatively simple.  I'm using a ListView to show a number of items, using the ItemTemplate.  Inside the ItemTemplate I have a div surrounding the full item, so that I can highlight on a hover event, (being handled already by jQuery).

What I would like to do is have the click event on the div fire a button to open a details view for that specific item.  The problem I'm having is pulling back the ClientID for that button while using jQuery.  I've tried the:

```<code>$('#<%= Button1.ClientID %>')
</code>```

route, but that doesn't work, as the Button doesn't exist when the page loads.

The basic code is as follows:

```<code><asp:listview>
 <itemtemplate>
  <td runat="server">
   <div class="container">
    <asp:linkbutton id="Button1" runat="server" text="View Details" />
     fun and exciting stuff here...
   </div>
  </td>
 </itemtemplate>
</asp:listview>
</code>```

Any suggestions or help are much appreciated!

答:
Wire up a method to the ItemDataBound event of your ListView.  In there, you can use FindControl method on the Item property of the ListViewItemEventArgs parameter to get a reference to that LinkButton for each item in your list.  From that reference, you can get the ClientID, and do with it whatever you need to do.

UPDATE

In terms of what you can do with the reference to the button, the easiest is probably to just assign your click event in the ItemDataBound event, maybe something like this

```<code>var button = (Button)e.Item.FindControl("Button1");
button.OnClientClick = "ShowEditDialog(" + Eval("ItemId") + ")";
</code>```

If you need to wire it up on the client side, maybe you could maintain a dictionary mapping ClientIDs to Item IDs, and send that dictionary down to the client, where you could iterate over it and wire the events up.

OwnerDisplayName: riceboyler

Body:
I'm attempting to do something which should be relatively simple.  I'm using a ListView to show a number of items, using the ItemTemplate.  Inside the ItemTemplate I have a div surrounding the full item, so that I can highlight on a hover event, (being handled already by jQuery).

What I would like to do is have the click event on the div fire a button to open a details view for that specific item.  The problem I'm having is pulling back the ClientID for that button while using jQuery.  I've tried the:

$('#<%= Button1.ClientID %>')

route, but that doesn't work, as the Button doesn't exist when the page loads.

The basic code is as follows:

<asp:listview>
 <itemtemplate>

    <asp:linkbutton id="Button1" runat="server" text="View Details" />
     fun and exciting stuff here...

 </itemtemplate>
</asp:listview>

Any suggestions or help are much appreciated!

Body:
Wire up a method to the ItemDataBound event of your ListView.  In there, you can use FindControl method on the Item property of the ListViewItemEventArgs parameter to get a reference to that LinkButton for each item in your list.  From that reference, you can get the ClientID, and do with it whatever you need to do.

UPDATE

In terms of what you can do with the reference to the button, the easiest is probably to just assign your click event in the ItemDataBound event, maybe something like this

var button = (Button)e.Item.FindControl("Button1");
button.OnClientClick = "ShowEditDialog(" + Eval("ItemId") + ")";

If you need to wire it up on the client side, maybe you could maintain a dictionary mapping ClientIDs to Item IDs, and send that dictionary down to the client, where you could iterate over it and wire the events up.

OwnerDisplayName: bdukes

LastEditorDisplayName: bdukes


问:
CSS - Make a div "clickable"
I'd like to know how i can render a div clickable (like a link, with the small hand when i go over with the mouse).

I have some elements like this:

```<code><div class="teamSelector">Some</div>
</code>```

With this jQuery:

```<code>$('.teamSelector').click(function() {
    // some functions
});
</code>```

Cheers

答:
The css for it is:

```<code>.teamSelector
{
  cursor: pointer
}
</code>```

You can also add hover effects, but I'm not sure if :active will work cross-browser.

If you need something to be clickable, you're better off using a button or a element and styling that. You can always prevent the default action with javascript. The reason it's better is for accessibility so that users with screen readers know that there's something to interact with.

Edit to add:
When you tab through a page, you can hit the space bar to click an element. This will not work the same on non-interactive elements, so anyone using that functionality will not be able to use whatever it is you're making.

Title: CSS - Make a div "clickable"

Body:
I'd like to know how i can render a div clickable (like a link, with the small hand when i go over with the mouse).

I have some elements like this:

Some

With this jQuery:

$('.teamSelector').click(function() {
    // some functions
});

Cheers

Body:
The css for it is:

.teamSelector
{
  cursor: pointer
}

You can also add hover effects, but I'm not sure if :active will work cross-browser.

If you need something to be clickable, you're better off using a button or a element and styling that. You can always prevent the default action with javascript. The reason it's better is for accessibility so that users with screen readers know that there's something to interact with.

Edit to add:
When you tab through a page, you can hit the space bar to click an element. This will not work the same on non-interactive elements, so anyone using that functionality will not be able to use whatever it is you're making.


问:
Bootstrap onClick change tab and target a new windows at the same time
So I have a button in one of my bootstrap tab-content and I have about 5 nav-tabs.  What I want to do is when you click on the button to go to the final tab and launch a new window at the same time.

Here is what I've tried.

```<code> <a href="#done"
 onClick="window.open('https://amazon.com', '_blank')"
 class="btn btn-success"> Marketplace</a>
</code>```

It launches the new window but the tab doesn't move to the final tab.  Any thoughts?

答:
Use a click handler that handles the bootstrap tab change and opens a window. You can put the URL you want for each tab in a data attribute of the element and read that in dynamically.

Since the SO sandbox won't allow a popup, here's a codepen https://codepen.io/anon/pen/dRYOmE

$('#myTabs a').on('click', function (e) {
  e.preventDefault()
  $(this).tab('show');
  window.open($(this).attr('data-url'), '_blank');
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div>

  <!-- Nav tabs -->
  <ul class="nav nav-tabs" role="tablist" id="myTabs">
    <li role="presentation" class="active">Home</li>
    <li role="presentation">Profile</li>
    <li role="presentation">Messages</li>
  </ul>

  <!-- Tab panes -->
  <div class="tab-content">
    <div role="tabpanel" class="tab-pane active" id="home">home</div>
    <div role="tabpanel" class="tab-pane" id="profile">profile</div>
    <div role="tabpanel" class="tab-pane" id="messages">messages</div>
  </div>

</div></code>```

Body:
So I have a button in one of my bootstrap tab-content and I have about 5 nav-tabs.  What I want to do is when you click on the button to go to the final tab and launch a new window at the same time.

Here is what I've tried.

  Marketplace

It launches the new window but the tab doesn't move to the final tab.  Any thoughts?

Body:
Use a click handler that handles the bootstrap tab change and opens a window. You can put the URL you want for each tab in a data attribute of the element and read that in dynamically.

Since the SO sandbox won't allow a popup, here's a codepen https://codepen.io/anon/pen/dRYOmE

$('#myTabs a').on('click', function (e) {
  e.preventDefault()
  $(this).tab('show');
  window.open($(this).attr('data-url'), '_blank');
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div>

  <!-- Nav tabs -->
  <ul class="nav nav-tabs" role="tablist" id="myTabs">
    <li role="presentation" class="active"><a href="#home" data-url="http://www.amazon.com" aria-controls="home" role="tab" data-toggle="tab">Home</a></li>
    <li role="presentation"><a href="#profile" data-url="http://www.stackoverflow.com" aria-controls="profile" role="tab" data-toggle="tab">Profile</a></li>
    <li role="presentation"><a href="#messages" data-url="http://www.google.com" aria-controls="messages" role="tab" data-toggle="tab">Messages</a></li>
  </ul>

  <!-- Tab panes -->
  <div class="tab-content">
    <div role="tabpanel" class="tab-pane active" id="home">home</div>
    <div role="tabpanel" class="tab-pane" id="profile">profile</div>
    <div role="tabpanel" class="tab-pane" id="messages">messages</div>
  </div>

</div>


问:
Android application: calc function does not work after changing to DrawerLayout
I changed the layout in my app from RelativLayout to RelativLayout as a child of DrawerLayout. Everything works fine, except the everything inside onClick() in MainActivity.java. After pressing the button button1 the result of the calculation is NaN which was working before. It has to do something with the change of the layout. I don't have a clue what causes this issue.
Maybe someone can help me out?
GitHub: https://github.com/ephlox/GradesCalculator2

MainActivity.java

```<code>package com.lob.gradescalculator;

import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import android.view.MenuInflater;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity {

    Toolbar toolbar;
    DrawerLayout drawerLayoutgesamt;
    ActionBarDrawerToggle drawerToggle;

    int sum = 0;
    int ects = 0;
    float mark = 0;
    NumberFormat numberFormat = new DecimalFormat("0.00");
    Button button1;
    TextView textView1;
    EditText editText1;
    EditText editText2;
    EditText editText3;

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

        toolbar = (Toolbar) findViewById(R.id.toolbar1);
        setSupportActionBar(toolbar);

        drawerLayoutgesamt = (DrawerLayout) findViewById(R.id.drawerlayoutgesamt);
        drawerToggle = new ActionBarDrawerToggle(MainActivity.this, drawerLayoutgesamt, R.string.auf, R.string.zu);
        drawerLayoutgesamt.setDrawerListener(drawerToggle);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        drawerToggle.syncState();

        button1 = (Button)findViewById(R.id.button1);
        textView1 = (TextView)findViewById(R.id.textView1);
        editText1 = (EditText)findViewById(R.id.editTextGDI);
        editText2 = (EditText)findViewById(R.id.editTextGDW);
        editText3 = (EditText)findViewById(R.id.editTextProgrammieren1);
        loadSavedPreferences();

        button1.setOnClickListener(
                new Button.OnClickListener() {
                    public void onClick(View v){

                        ViewGroup group = (ViewGroup)findViewById(R.id.activity_main);
                        for (int i = 0, count = group.getChildCount(); i < count; ++i) {
                            View view = group.getChildAt(i);
                            if (view instanceof EditText) {
                                if(view.equals(editText1) && !(editText1.getText().toString().matches(""))){ //GDI
                                    System.out.println("edittext1");
                                    ects += 5;
                                    try{ sum += Integer.parseInt(editText1.getText().toString()) *5; } catch(NumberFormatException n){}
                                }
                                else if(view.equals(editText2)&& !(editText2.getText().toString().matches(""))){ //GDW
                                    System.out.println("edittext2");
                                    ects += 5;
                                    try{ sum += Integer.parseInt(editText2.getText().toString()) *5; } catch(NumberFormatException n){}
                                }
                                else if(view.equals(editText3)&& !(editText3.getText().toString().matches(""))){
                                    System.out.println("edittext3");
                                    ects += 7;
                                    try{ sum += Integer.parseInt(editText3.getText().toString()) *7; } catch(NumberFormatException n){}
                                }
                            }
                        }

                        mark = (float)sum / (float)ects;
                        textView1.setText(String.valueOf(numberFormat.format(mark)));
                        savePreferences("editText1", editText1.getText().toString());
                        savePreferences("editText2", editText2.getText().toString());
                        savePreferences("editText3", editText3.getText().toString());

                        sum = 0;
                        ects = 0;
                        mark = 0;
                    }
                }
        );
    }

    private void loadSavedPreferences() {
        SharedPreferences sharedPreferences = PreferenceManager
                .getDefaultSharedPreferences(this);
        editText1.setText(sharedPreferences.getString("editText1", ""));
        editText2.setText(sharedPreferences.getString("editText2", ""));
        editText3.setText(sharedPreferences.getString("editText3", ""));
    }

    private void savePreferences(String key, String value) {
        SharedPreferences sharedPreferences = PreferenceManager
                .getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(key, value);
        editor.commit();
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        int id = item.getItemId();

        if(id == R.id.action_settings){
           return true;
        }
        if(drawerToggle.onOptionsItemSelected(item)){
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onPostCreate(@Nullable Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        drawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        drawerToggle.onConfigurationChanged(new Configuration());
    }
}
</code>```

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.lob.gradescalculator.MainActivity">

    <android.support.v4.widget.DrawerLayout
        android:layout_height="fill_parent"
        android:layout_width="fill_parent"
        android:id="@+id/drawerlayoutgesamt"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true">

        <!--  Activity Layout für Hauptbereich -->
        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:id="@+id/activitylayout"
            >

            <android.support.v7.widget.Toolbar
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:id="@+id/toolbar1"
                android:background="#c6d9ff"
                android:fitsSystemWindows="true"
                >
            </android.support.v7.widget.Toolbar>

            <!-- TextViews -->
            <TextView
                android:id="@+id/WIF_Title"
                android:text="Wirtschaftsinformatik B.Sc."
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="25dp"
                android:layout_x="23dp"
                android:layout_y="200dp"
                android:layout_below="@+id/toolbar1"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="10dp"/>

            <TextView
                android:id="@+id/textViewGDW"
                android:text="Grundlagen der Wirtschaftsinformatik"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="@style/TextAppearance.AppCompat.Body1"
                android:textStyle="normal|bold"
                android:textAlignment="textStart"
                android:layout_below="@+id/textViewGDI"
                android:layout_marginTop="30dp"
                android:layout_x="45dp"
                android:layout_y="344dp"
                android:layout_alignStart="@+id/textViewGDI" />
            <TextView
                android:id="@+id/TextViewProgrammieren1"
                android:text="Programmieren 1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="@style/TextAppearance.AppCompat.Body1"
                android:textStyle="normal|bold"
                android:textAlignment="textStart"
                android:layout_below="@+id/textViewGDW"
                android:layout_marginTop="32dp"
                android:layout_x="113dp"
                android:layout_y="238dp"
                android:layout_alignStart="@+id/textViewGDW" />

            <!-- EditTexts -->

            <!-- Buttons -->

            <EditText
                android:id="@+id/editTextGDI"
                android:layout_width="50dp"
                android:layout_height="wrap_content"
                android:layout_below="@+id/WIF_Title"
                android:layout_alignParentEnd="true"
                android:layout_marginTop="10dp"
                android:layout_marginEnd="10dp"
                android:inputType="number"
                android:textColorHint="@drawable/selector"
                android:background="@drawable/roundedborders"
                android:digits="12345"
                android:maxLength="1"

                />

            <TextView
                android:id="@+id/textViewGDI"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"

                android:text="Grundlagen der Informatik"
                android:textAppearance="@style/TextAppearance.AppCompat.Body1"
                android:textStyle="normal|bold"
                android:textAlignment="center"
                android:layout_x="125dp"
                android:layout_y="184dp"
                android:layout_below="@+id/WIF_Title"
                android:layout_alignParentStart="true"
                android:layout_marginStart="3dp"
                android:layout_marginTop="15dp"/>

            <EditText
                android:id="@+id/editTextGDW"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:inputType="number"
                android:textColorHint="@drawable/selector"
                android:background="@drawable/roundedborders"
                android:ems="10"
                android:layout_x="69dp"
                android:layout_y="91dp"
                android:layout_alignBaseline="@+id/textViewGDW"
                android:layout_alignBottom="@+id/textViewGDW"
                android:layout_alignStart="@+id/editTextGDI"
                android:layout_alignEnd="@+id/editTextGDI" />

            <EditText
                android:id="@+id/editTextProgrammieren1"
                android:layout_height="wrap_content"
                android:inputType="number"
                android:textColorHint="@drawable/selector"
                android:background="@drawable/roundedborders"
                android:ems="10"
                android:layout_x="78dp"
                android:layout_y="264dp"
                android:layout_width="50dp"
                android:layout_alignBaseline="@+id/TextViewProgrammieren1"
                android:layout_alignBottom="@+id/TextViewProgrammieren1"
                android:layout_alignStart="@+id/editTextGDW"
                android:layout_alignEnd="@+id/editTextGDW" />

            <TextView
                android:id="@+id/textView1"
                android:text="..."
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="71dp"
                android:layout_x="23dp"
                android:layout_y="200dp"
                android:layout_above="@+id/button1"
                android:layout_centerHorizontal="true" />

            <Button
                android:id="@+id/button1"
                android:text="Berechne"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="75dp"
                android:layout_x="128dp"
                android:layout_y="442dp"
                android:layout_alignParentBottom="true"
                android:layout_alignEnd="@+id/textViewGDW" />

        </RelativeLayout>

        <!-- Drawerlayout für links -->
        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:id="@+id/drayerlayoutsingle"
            android:layout_gravity="start"
            android:background="#fff">

        </RelativeLayout>

    </android.support.v4.widget.DrawerLayout>

</RelativeLayout>
</code>```

答: Solved it. I had to change ViewGroup group = (ViewGroup)findViewById(R.id.activity_main); to ViewGroup group = (ViewGroup)findViewById(R.id.activitylayout);.

Body:
I changed the layout in my app from RelativLayout to RelativLayout as a child of DrawerLayout. Everything works fine, except the everything inside onClick() in MainActivity.java. After pressing the button button1 the result of the calculation is NaN which was working before. It has to do something with the change of the layout. I don't have a clue what causes this issue.
Maybe someone can help me out?
GitHub: https://github.com/ephlox/GradesCalculator2

MainActivity.java

package com.lob.gradescalculator;

import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import android.view.MenuInflater;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity {

    Toolbar toolbar;
    DrawerLayout drawerLayoutgesamt;
    ActionBarDrawerToggle drawerToggle;

    int sum = 0;
    int ects = 0;
    float mark = 0;
    NumberFormat numberFormat = new DecimalFormat("0.00");
    Button button1;
    TextView textView1;
    EditText editText1;
    EditText editText2;
    EditText editText3;

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

        toolbar = (Toolbar) findViewById(R.id.toolbar1);
        setSupportActionBar(toolbar);

        drawerLayoutgesamt = (DrawerLayout) findViewById(R.id.drawerlayoutgesamt);
        drawerToggle = new ActionBarDrawerToggle(MainActivity.this, drawerLayoutgesamt, R.string.auf, R.string.zu);
        drawerLayoutgesamt.setDrawerListener(drawerToggle);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        drawerToggle.syncState();

        button1 = (Button)findViewById(R.id.button1);
        textView1 = (TextView)findViewById(R.id.textView1);
        editText1 = (EditText)findViewById(R.id.editTextGDI);
        editText2 = (EditText)findViewById(R.id.editTextGDW);
        editText3 = (EditText)findViewById(R.id.editTextProgrammieren1);
        loadSavedPreferences();

        button1.setOnClickListener(
                new Button.OnClickListener() {
                    public void onClick(View v){

                        ViewGroup group = (ViewGroup)findViewById(R.id.activity_main);
                        for (int i = 0, count = group.getChildCount(); i < count; ++i) {
                            View view = group.getChildAt(i);
                            if (view instanceof EditText) {
                                if(view.equals(editText1) && !(editText1.getText().toString().matches(""))){ //GDI
                                    System.out.println("edittext1");
                                    ects += 5;
                                    try{ sum += Integer.parseInt(editText1.getText().toString()) *5; } catch(NumberFormatException n){}
                                }
                                else if(view.equals(editText2)&& !(editText2.getText().toString().matches(""))){ //GDW
                                    System.out.println("edittext2");
                                    ects += 5;
                                    try{ sum += Integer.parseInt(editText2.getText().toString()) *5; } catch(NumberFormatException n){}
                                }
                                else if(view.equals(editText3)&& !(editText3.getText().toString().matches(""))){
                                    System.out.println("edittext3");
                                    ects += 7;
                                    try{ sum += Integer.parseInt(editText3.getText().toString()) *7; } catch(NumberFormatException n){}
                                }
                            }
                        }

                        mark = (float)sum / (float)ects;
                        textView1.setText(String.valueOf(numberFormat.format(mark)));
                        savePreferences("editText1", editText1.getText().toString());
                        savePreferences("editText2", editText2.getText().toString());
                        savePreferences("editText3", editText3.getText().toString());

                        sum = 0;
                        ects = 0;
                        mark = 0;
                    }
                }
        );
    }

    private void loadSavedPreferences() {
        SharedPreferences sharedPreferences = PreferenceManager
                .getDefaultSharedPreferences(this);
        editText1.setText(sharedPreferences.getString("editText1", ""));
        editText2.setText(sharedPreferences.getString("editText2", ""));
        editText3.setText(sharedPreferences.getString("editText3", ""));
    }

    private void savePreferences(String key, String value) {
        SharedPreferences sharedPreferences = PreferenceManager
                .getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(key, value);
        editor.commit();
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        int id = item.getItemId();

        if(id == R.id.action_settings){
           return true;
        }
        if(drawerToggle.onOptionsItemSelected(item)){
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onPostCreate(@Nullable Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        drawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        drawerToggle.onConfigurationChanged(new Configuration());
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.lob.gradescalculator.MainActivity">

    <android.support.v4.widget.DrawerLayout
        android:layout_height="fill_parent"
        android:layout_width="fill_parent"
        android:id="@+id/drawerlayoutgesamt"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true">

        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:id="@+id/activitylayout"
            >

            <android.support.v7.widget.Toolbar
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:id="@+id/toolbar1"
                android:background="#c6d9ff"
                android:fitsSystemWindows="true"
                >
            </android.support.v7.widget.Toolbar>

            <TextView
                android:id="@+id/WIF_Title"
                android:text="Wirtschaftsinformatik B.Sc."
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="25dp"
                android:layout_x="23dp"
                android:layout_y="200dp"
                android:layout_below="@+id/toolbar1"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="10dp"/>

            <TextView
                android:id="@+id/textViewGDW"
                android:text="Grundlagen der Wirtschaftsinformatik"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="@style/TextAppearance.AppCompat.Body1"
                android:textStyle="normal|bold"
                android:textAlignment="textStart"
                android:layout_below="@+id/textViewGDI"
                android:layout_marginTop="30dp"
                android:layout_x="45dp"
                android:layout_y="344dp"
                android:layout_alignStart="@+id/textViewGDI" />
            <TextView
                android:id="@+id/TextViewProgrammieren1"
                android:text="Programmieren 1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="@style/TextAppearance.AppCompat.Body1"
                android:textStyle="normal|bold"
                android:textAlignment="textStart"
                android:layout_below="@+id/textViewGDW"
                android:layout_marginTop="32dp"
                android:layout_x="113dp"
                android:layout_y="238dp"
                android:layout_alignStart="@+id/textViewGDW" />

            <EditText
                android:id="@+id/editTextGDI"
                android:layout_width="50dp"
                android:layout_height="wrap_content"
                android:layout_below="@+id/WIF_Title"
                android:layout_alignParentEnd="true"
                android:layout_marginTop="10dp"
                android:layout_marginEnd="10dp"
                android:inputType="number"
                android:textColorHint="@drawable/selector"
                android:background="@drawable/roundedborders"
                android:digits="12345"
                android:maxLength="1"

                />

            <TextView
                android:id="@+id/textViewGDI"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"

                android:text="Grundlagen der Informatik"
                android:textAppearance="@style/TextAppearance.AppCompat.Body1"
                android:textStyle="normal|bold"
                android:textAlignment="center"
                android:layout_x="125dp"
                android:layout_y="184dp"
                android:layout_below="@+id/WIF_Title"
                android:layout_alignParentStart="true"
                android:layout_marginStart="3dp"
                android:layout_marginTop="15dp"/>

            <EditText
                android:id="@+id/editTextGDW"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:inputType="number"
                android:textColorHint="@drawable/selector"
                android:background="@drawable/roundedborders"
                android:ems="10"
                android:layout_x="69dp"
                android:layout_y="91dp"
                android:layout_alignBaseline="@+id/textViewGDW"
                android:layout_alignBottom="@+id/textViewGDW"
                android:layout_alignStart="@+id/editTextGDI"
                android:layout_alignEnd="@+id/editTextGDI" />

            <EditText
                android:id="@+id/editTextProgrammieren1"
                android:layout_height="wrap_content"
                android:inputType="number"
                android:textColorHint="@drawable/selector"
                android:background="@drawable/roundedborders"
                android:ems="10"
                android:layout_x="78dp"
                android:layout_y="264dp"
                android:layout_width="50dp"
                android:layout_alignBaseline="@+id/TextViewProgrammieren1"
                android:layout_alignBottom="@+id/TextViewProgrammieren1"
                android:layout_alignStart="@+id/editTextGDW"
                android:layout_alignEnd="@+id/editTextGDW" />

            <TextView
                android:id="@+id/textView1"
                android:text="..."
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="71dp"
                android:layout_x="23dp"
                android:layout_y="200dp"
                android:layout_above="@+id/button1"
                android:layout_centerHorizontal="true" />

            <Button
                android:id="@+id/button1"
                android:text="Berechne"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="75dp"
                android:layout_x="128dp"
                android:layout_y="442dp"
                android:layout_alignParentBottom="true"
                android:layout_alignEnd="@+id/textViewGDW" />

        </RelativeLayout>

        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:id="@+id/drayerlayoutsingle"
            android:layout_gravity="start"
            android:background="#fff">

        </RelativeLayout>

    </android.support.v4.widget.DrawerLayout>

</RelativeLayout>


答: Instead of pre-allocating space for one million ints, you can start with a small array and then allocate new space as needed. Of course, java.util.ArrayList does this for you.


问:
Navigation Bar click event - Android Application
I'm trying to handle a onClick event on the Navigation Bar in an Android Application.

Exactlyer, when the user clicks on the return button the Application must go back to the Main Activity ( in my case "Start" ) and not to the previous Activity.

In my application I have more Activities, which are all callable from every Activity, so when, for example, I'm in "Start", I click a Button and I come to "Karte", then from "Karte" I want to go to "Einstellungen", then from "Einstellungen" I want return to the Main Activity "Start", but I can't because when I click on the return button on the Nav. Bar I come only back to the previous Activity ("Karte").

If anyone knows how to handle this, please answer.

答:
1. After starting Einstellungen from Karte, just finish Karte activity to remove it from stack:

```<code>//Karte.java

Intent intentEinstellungen = new Intent(karte.this, Einstellungen.class);
startActivity(intentEinstellungen);

// Finish Karte
finish();
</code>```

2. When navigation back/home icon pressed from Einstellungen, just call  super.onBackPressed() from method onOptionsItemSelected() to finish the Einstellungen activity.

```<code>//Einstellungen.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    switch (id) {
        case android.R.id.home:
            super.onBackPressed();
            return true;

        default:
            return super.onOptionsItemSelected(item);
    }
}
</code>```

It will show Start because the Karte already pop out from stack.

Body:
1. After starting Einstellungen from Karte, just finish Karte activity to remove it from stack:

//Karte.java

Intent intentEinstellungen = new Intent(karte.this, Einstellungen.class);
startActivity(intentEinstellungen);

// Finish Karte
finish();

2. When navigation back/home icon pressed from Einstellungen, just call  super.onBackPressed() from method onOptionsItemSelected() to finish the Einstellungen activity.

//Einstellungen.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    switch (id) {
        case android.R.id.home:
            super.onBackPressed();
            return true;

        default:
            return super.onOptionsItemSelected(item);
    }
}

It will show Start because the Karte already pop out from stack.


问:
character to use when splitting strings in visual c#?
Ok, I'm racking my brains over this one.  It's pretty simple though (I think).

I'm currently creating a text file as a comma separated string of values.

Later, I read in that file data and then use the .split function to split the data by commas.

I discovered that sometimes one of the description fields in the data conatins an embedded comma, which ends up throwing the split command off.

Is there any special character I could use that could pretty much guarantee wouldn't be in the data, or is there a better way to accomplish this?  Thanks!

```<code>// Initial Load
fullString = fileName + "," + String.Join(",", fieldValues);

// Access later
String[] valuesArray = myString.Split(',');
</code>```

答:
Short answer, there's no "simple" way to do it using Split. The best you can hope for is to set the deliminator as something cooky that wouldn't ever get used (but even that's not a guarantee). </p>

<p>The simple method would be to used something like CsvHelper (get it through Nuget) or any of the other dozen or so packages that are designed for parsing CSV. </p>

Body:
Ok, I'm racking my brains over this one.  It's pretty simple though (I think).

I'm currently creating a text file as a comma separated string of values.

Later, I read in that file data and then use the .split function to split the data by commas.

I discovered that sometimes one of the description fields in the data conatins an embedded comma, which ends up throwing the split command off.

Is there any special character I could use that could pretty much guarantee wouldn't be in the data, or is there a better way to accomplish this?  Thanks!

// Initial Load
fullString = fileName + "," + String.Join(",", fieldValues);

// Access later
String[] valuesArray = myString.Split(',');

Body:
Short answer, there's no "simple" way to do it using Split. The best you can hope for is to set the deliminator as something cooky that wouldn't ever get used (but even that's not a guarantee).

The simple method would be to used something like CsvHelper (get it through Nuget) or any of the other dozen or so packages that are designed for parsing CSV.