问:
How to use JavaScript and offsetWidth to line up tables?
I've inherited this project that goes about things in an old-fashioned way.  For instance, it uses tables for layout, which is bad enough, but then it breaks apart headers and content into two separate tables (see my code snippet).

It's not really practical to go about re-writing the markup, so the solution will have to be a JavaScript one, combined with CSS probably.  Keep in mind that I've vastly simplified the issue for the purposes here to make things less confusing; in reality, the problem stretches over many different files.

Using JavaScript (see the snippet), I'm able to mostly line up the headers with the body.  The idea is to wait until the page loads, find the widths of the body elements, and then apply them to the headers to make it look like one table.  As you can see, it doesn't exactly match up.  This is in part because of the CSS borders, but life is messy and borders happen.  It's not realistic to remove all additional CSS just to make things line up.

Can you help me get these tables to line up and look like one table?

Edit:

To be a bit clearer on the requirements, the table needs to be sized dynamically, based on the widths of the content in the body table.  The content might change, so it won't be sufficient to hard-code widths.

window.onload = function() {
  var bodyCols = document.getElementsByClassName('bodyCol');
  var headCols = document.getElementsByClassName('headCol');

  for (var i=0; i<bodyCols.length; i++) {
    headCols[i].style.minWidth = bodyCols[i].offsetWidth + 'px';
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#headTable {
  width: 100%;
}

.headCol {
  border: 5px solid red;
}

#bodyTable {
  width: 100%;
}

.bodyCol {
  border: 5px solid blue;
}</code>```

        Hey!

        Wait!

        I've got a new complaint

        Forever in debt

        to your priceless

        advice

```

答:
I spent some time on this and came up with a jQuery solution.  Now, I didn't mention jQuery in the question and ideally I wouldn't have to include it in my project just for this one problem.  However, it does solve the problem nicely and I don't know of a way to do it otherwise.  I will leave off marking this as the correct answer for now in the hopes someone can show me how to do this with plain JavaScript.

$(function() {
  $('.bodyCol').each(function(index) {
    $('.headCol:eq(' + index + ')').innerWidth($(this).innerWidth());
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#headTable {
  width: 100%;
}

.headCol {
  border: 5px solid red;
}

#bodyTable {
  width: 100%;
}

.bodyCol {
  border: 5px solid blue;
}</code>```

        Hey!

        Wait!

        I've got a new complaint

        Forever in debt

        to your priceless

        advice

```

Body:
I've inherited this project that goes about things in an old-fashioned way.  For instance, it uses tables for layout, which is bad enough, but then it breaks apart headers and content into two separate tables (see my code snippet).

It's not really practical to go about re-writing the markup, so the solution will have to be a JavaScript one, combined with CSS probably.  Keep in mind that I've vastly simplified the issue for the purposes here to make things less confusing; in reality, the problem stretches over many different files.

Using JavaScript (see the snippet), I'm able to mostly line up the headers with the body.  The idea is to wait until the page loads, find the widths of the body elements, and then apply them to the headers to make it look like one table.  As you can see, it doesn't exactly match up.  This is in part because of the CSS borders, but life is messy and borders happen.  It's not realistic to remove all additional CSS just to make things line up.

Can you help me get these tables to line up and look like one table?

Edit:

To be a bit clearer on the requirements, the table needs to be sized dynamically, based on the widths of the content in the body table.  The content might change, so it won't be sufficient to hard-code widths.

window.onload = function() {
  var bodyCols = document.getElementsByClassName('bodyCol');
  var headCols = document.getElementsByClassName('headCol');

  for (var i=0; i<bodyCols.length; i++) {
    headCols[i].style.minWidth = bodyCols[i].offsetWidth + 'px';
  }
}

#headTable {
  width: 100%;
}

.headCol {
  border: 5px solid red;
}

#bodyTable {
  width: 100%;
}

.bodyCol {
  border: 5px solid blue;
}

        Hey!

        Wait!

        I've got a new complaint

        Forever in debt

        to your priceless

        advice

Body:
I spent some time on this and came up with a jQuery solution.  Now, I didn't mention jQuery in the question and ideally I wouldn't have to include it in my project just for this one problem.  However, it does solve the problem nicely and I don't know of a way to do it otherwise.  I will leave off marking this as the correct answer for now in the hopes someone can show me how to do this with plain JavaScript.

$(function() {
  $('.bodyCol').each(function(index) {
    $('.headCol:eq(' + index + ')').innerWidth($(this).innerWidth());
  });
});

#headTable {
  width: 100%;
}

.headCol {
  border: 5px solid red;
}

#bodyTable {
  width: 100%;
}

.bodyCol {
  border: 5px solid blue;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="headTable">
  <tbody>
    <tr>
      <td class="headCol">
        Hey!
      </td>
      <td class="headCol">
        Wait!
      </td>
      <td class="headCol">
        I've got a new complaint
      </td>
    </tr>
  </tbody>
</table>
<table id="bodyTable">
  <tbody>
    <tr>
      <td class="bodyCol">
        Forever in debt
      </td>
      <td class="bodyCol">
        to your priceless
      </td>
      <td class="bodyCol">
        advice
      </td>
    </tr>
  </tbody>
</table>


来源: stackexchange

问:
Automatically create #region with same name at #endregion
I'm wondering if there is a way to make #region Some Region #endregion Some Region.
If there is no way for doing it then maybe is it possible with Resharper?

Hope it's clear what I'm trying to achive here.

Edit:

```<code><?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
    <Header>
        <Title>#region</Title>
        <Shortcut>#region</Shortcut>
        <Description>Code snippet for #region</Description>
        <Author>Microsoft Corporation</Author>
        <SnippetTypes>
            <SnippetType>Expansion</SnippetType>
            <SnippetType>SurroundsWith</SnippetType>
        </SnippetTypes>
    </Header>
    <Snippet>
        <Declarations>
            <Literal>
                <ID>name</ID>
                <ToolTip>Region name</ToolTip>
                <Default>MyRegion</Default>
            </Literal>
        </Declarations>
        <Code Language="csharp"><![CDATA[#region $name$
    $selected$ $end$
#endregion $name$]]>
        </Code>
    </Snippet>
</CodeSnippet>
</CodeSnippets>
</code>```

Second edit:
It's work but only when I make insert snippet. From intellisense this using some other snippet I gues.

So is there a way to add my region from intellisense not from insert snippet menu?

答:
Visual Studio 2017

Type #r TAB TAB, then type the name of the region.

This is built in behavior.

ContentLicense: CC BY-SA 3.0

Body:
I'm wondering if there is a way to make #region Some Region #endregion Some Region.
If there is no way for doing it then maybe is it possible with Resharper?

Hope it's clear what I'm trying to achive here.

Edit:

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">

        <Title>#region</Title>
        <Shortcut>#region</Shortcut>
        <Description>Code snippet for #region</Description>
        <Author>Microsoft Corporation</Author>
        <SnippetTypes>
            <SnippetType>Expansion</SnippetType>
            <SnippetType>SurroundsWith</SnippetType>
        </SnippetTypes>

    <Snippet>
        <Declarations>
            <Literal>
                <ID>name</ID>
                <ToolTip>Region name</ToolTip>
                <Default>MyRegion</Default>
            </Literal>
        </Declarations>
        <![CDATA[#region $name$
    $selected$ $end$
#endregion $name$]]>

    </Snippet>
</CodeSnippet>
</CodeSnippets>

Second edit:
It's work but only when I make insert snippet. From intellisense this using some other snippet I gues.

So is there a way to add my region from intellisense not from insert snippet menu?


问:
ActiveRecord where and order on via-table
I have three database table:

product (id, name)

product_has_adv (product,advantage,sort,important)

advantage (id, text)

In ProductModel I defined this:

```<code>public function getAdvantages()
    {
        return $this->hasMany(AdvantageModel::className(), ['id' => 'advantage'])
            ->viaTable('product_has_advantage', ['product' => 'id']);
    }
</code>```

I get the advantages without any problems.

But now I need to add a where product_has_advantage.important = 1 clausel and also sort the advantages by the sort-columen in the product_has_advantage-table.

How and where I have to realize it?

答:
Using viaTable methods with relations will cause two separate queries, but if you don't need link() method you can use innerJoin in the following way to sort by product_has_advantage table:

```<code>public function getAdvantages()
{
    $query = AdvantageModel::find();
    $query->multiple = true;
    $query->innerJoin('product_has_advantage','product_has_advantage.advantage = advantage.id');
    $query->andWhere(['product_has_advantage.product' => $this->id, 'product_has_advantage.important' => 1]);
    $query->orderBy(['product_has_advantage.sort' => SORT_DESC]);
    return $query;
}
</code>```

Note than $query->multiple = true allows you to use this method as Yii2 hasMany relation.

Body:
I have three database table:

product (id, name)

product_has_adv (product,advantage,sort,important)

advantage (id, text)

In ProductModel I defined this:

public function getAdvantages()
    {
        return $this->hasMany(AdvantageModel::className(), ['id' => 'advantage'])
            ->viaTable('product_has_advantage', ['product' => 'id']);
    }

I get the advantages without any problems.

But now I need to add a where product_has_advantage.important = 1 clausel and also sort the advantages by the sort-columen in the product_has_advantage-table.

How and where I have to realize it?

Body:
Using viaTable methods with relations will cause two separate queries, but if you don't need link() method you can use innerJoin in the following way to sort by product_has_advantage table:

public function getAdvantages()
{
    $query = AdvantageModel::find();
    $query->multiple = true;
    $query->innerJoin('product_has_advantage','product_has_advantage.advantage = advantage.id');
    $query->andWhere(['product_has_advantage.product' => $this->id, 'product_has_advantage.important' => 1]);
    $query->orderBy(['product_has_advantage.sort' => SORT_DESC]);
    return $query;
}

Note than $query->multiple = true allows you to use this method as Yii2 hasMany relation.


问:
Redirecting an HTTP POST
Ok, so in my web app's API I have an incoming HTTP post request.
I would like to pass that POST request on to a different server, without losing the data in the POST header. Is this possible? which type of redirect would I use? php examples?

Edit: The HTTP request is coming from a mobile app, not a web browser.

Thanks!

答:
I used the following code to redirect a post. In my case I am using only application/octet-stream content type so make sure you take that into consideration.

```<code>$request = file_get_contents ( "php://input" );

$arrContextOptions=array(
        "http" => array(
                "method" => "POST",
                "header" =>
                'Content-Type: application/octet-stream'. "\r\n".
                'Content-Length: ' . strlen($request) . "\r\n",
                "content" => $request,
        ),
        "ssl"=>array(
                "allow_self_signed"=>true,
                "verify_peer"=>false,
        ),
);
$arrContextOptions = stream_context_create($arrContextOptions);

header ( "HTTP/1.1" );
header ( "Content-Type: application/octet-stream" );

$result =  file_get_contents('http://thenewaddress.yes.it.works', false, $arrContextOptions);

file_put_contents("php://output", $result);
</code>```

ContentLicense: CC BY-SA 2.5

Title: Redirecting an HTTP POST

Body:
I used the following code to redirect a post. In my case I am using only application/octet-stream content type so make sure you take that into consideration.

$request = file_get_contents ( "php://input" );

$arrContextOptions=array(
        "http" => array(
                "method" => "POST",
                "header" =>
                'Content-Type: application/octet-stream'. "\r\n".
                'Content-Length: ' . strlen($request) . "\r\n",
                "content" => $request,
        ),
        "ssl"=>array(
                "allow_self_signed"=>true,
                "verify_peer"=>false,
        ),
);
$arrContextOptions = stream_context_create($arrContextOptions);

header ( "HTTP/1.1" );
header ( "Content-Type: application/octet-stream" );

$result =  file_get_contents('http://thenewaddress.yes.it.works', false, $arrContextOptions);

file_put_contents("php://output", $result);


问:
Can the NOT operator work on multiple conditions present in parenthesis?
I run following query in MySQL :

```<code>SELECT * FROM Customers
WHERE NOT Country='Germany' AND NOT Country='USA';
</code>```

It returned me exactly the correct expected result.

After that I run following query :

```<code>SELECT * FROM Customers
WHERE NOT (Country='Germany' AND Country='USA');
</code>```

This time it returned me all the records present in the table(result-set of the query SELECT * FROM Customers;)

I'm not understanding why the NOT operator is not working in second query with parenthesis?

You can go to this link and check :

```<code>https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_where_not_and
</code>```

答:
You should be using a OR condition rather since the same column can't take multiple value at any point in time and thus your condition will bound to return false. Moreover, instead of using multiple stacked OR condition you should use IN operator like

```<code>WHERE Country IN ('Germany', 'USA');
</code>```

(OR)

```<code>WHERE Country NOT IN ('Germany', 'USA');
</code>```

Your current condition will be evaluated as follows: (Country='Germany' AND Country='USA') will return false and NOT false will return true. Thus making your WHERE part true and returning all result

Body:
I run following query in MySQL :

SELECT * FROM Customers
WHERE NOT Country='Germany' AND NOT Country='USA';

It returned me exactly the correct expected result.

After that I run following query :

SELECT * FROM Customers
WHERE NOT (Country='Germany' AND Country='USA');

This time it returned me all the records present in the table(result-set of the query SELECT * FROM Customers;)

I'm not understanding why the NOT operator is not working in second query with parenthesis?

You can go to this link and check :

https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_where_not_and

Body:
You should be using a OR condition rather since the same column can't take multiple value at any point in time and thus your condition will bound to return false. Moreover, instead of using multiple stacked OR condition you should use IN operator like

WHERE Country IN ('Germany', 'USA');

(OR)

WHERE Country NOT IN ('Germany', 'USA');

Your current condition will be evaluated as follows: (Country='Germany' AND Country='USA') will return false and NOT false will return true. Thus making your WHERE part true and returning all result


问:
How to make an observer to return as observable?
I'm new to rxjs and would like some help on how to solve this.

I want to pass an Observer to onAuthStateChanged(), which takes an observer object.  The observer would do some work and emit a boolean value such that the boolean value can be returned as an Observable.  How do I go about implement this bridge of from observable to observer?

```<code>export class AuthGuard implements CanActivate {

constructor(private firebase: FirebaseService, private router: Router) {
}

canActivate(): Observable<boolean> {
    this.firebase.auth.onAuthStateChanged(/* an observer */)
    return /* an Observable<boolean> */
    }
}
</code>```

答:
Similar approach:

./auth-guard.ts

```<code>import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';

import { AuthService } from '../shared/auth.service';

@Injectable()
export class AuthGuard implements CanActivate {

  constructor(
    private router: Router,
    private authService: AuthService) { }

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> | Promise<boolean> | boolean {

    return this.authService.authState.map((auth) => {
      if (auth == null) {
        this.router.navigate(['auth']);
        return false;
      } else {
        return true;
      }
    }).first();

  }
}
</code>```

./shared/auth.service.ts

```<code>import { Observable } from 'rxjs/Observable';
import { Observer } from 'rxjs/Observer';
import { FirebaseApp } from '../shared/firebase';

@Injectable()
export class AuthService {

  public auth: firebase.auth.Auth;
  public authState: Observable<firebase.User>;

  constructor(public app: FirebaseApp) {
    this.auth = app.auth();
    this.authState = this.authStateObservable(app);
  }

  /**
   * @function
   * @desc Create an Observable of Firebase authentication state
   */
  public authStateObservable(app: FirebaseApp): Observable<firebase.User> {
    const authState = Observable.create((observer: Observer<firebase.User>) => {
      this.auth.onAuthStateChanged(
        (user?: firebase.User) => observer.next(user),
        (error: firebase.auth.Error) => observer.error(error),
        () => observer.complete()
      );
    });
    return authState;
  }
}
</code>```

./shared/firebase.ts

```<code>import * as firebase from 'firebase';

export class FirebaseApp implements firebase.app.App {

  name: string;
  options: {};
  auth: () => firebase.auth.Auth;
  database: () => firebase.database.Database;
  messaging: () => firebase.messaging.Messaging;
  storage: () => firebase.storage.Storage;
  delete: () => firebase.Promise<any>;

  constructor() {
    return firebase.initializeApp({
      apiKey: 'AIzaSyC6pDjAGuqXtVsU15erxVT99IdB0t4nln4',
      authDomain: 'inobrax-ebs-16552.firebaseapp.com',
      databaseURL: 'https://inobrax-ebs-16552.firebaseio.com',
      storageBucket: 'inobrax-ebs-16552.appspot.com',
      messagingSenderId: '383622803653'
    });
  }

}
</code>```

Body:
I'm new to rxjs and would like some help on how to solve this.

I want to pass an Observer to onAuthStateChanged(), which takes an observer object.  The observer would do some work and emit a boolean value such that the boolean value can be returned as an Observable.  How do I go about implement this bridge of from observable to observer?

export class AuthGuard implements CanActivate {

constructor(private firebase: FirebaseService, private router: Router) {
}

canActivate(): Observable<boolean> {
    this.firebase.auth.onAuthStateChanged(/* an observer */)
    return /* an Observable<boolean> */
    }
}

Body:
Similar approach:

./auth-guard.ts

import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';

import { AuthService } from '../shared/auth.service';

@Injectable()
export class AuthGuard implements CanActivate {

  constructor(
    private router: Router,
    private authService: AuthService) { }

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> | Promise<boolean> | boolean {

    return this.authService.authState.map((auth) => {
      if (auth == null) {
        this.router.navigate(['auth']);
        return false;
      } else {
        return true;
      }
    }).first();

  }
}

./shared/auth.service.ts

import { Observable } from 'rxjs/Observable';
import { Observer } from 'rxjs/Observer';
import { FirebaseApp } from '../shared/firebase';

@Injectable()
export class AuthService {

  public auth: firebase.auth.Auth;
  public authState: Observable<firebase.User>;

  constructor(public app: FirebaseApp) {
    this.auth = app.auth();
    this.authState = this.authStateObservable(app);
  }

  /**
   * @function
   * @desc Create an Observable of Firebase authentication state
   */
  public authStateObservable(app: FirebaseApp): Observable<firebase.User> {
    const authState = Observable.create((observer: Observer<firebase.User>) => {
      this.auth.onAuthStateChanged(
        (user?: firebase.User) => observer.next(user),
        (error: firebase.auth.Error) => observer.error(error),
        () => observer.complete()
      );
    });
    return authState;
  }
}

./shared/firebase.ts

import * as firebase from 'firebase';

export class FirebaseApp implements firebase.app.App {

  name: string;
  options: {};
  auth: () => firebase.auth.Auth;
  database: () => firebase.database.Database;
  messaging: () => firebase.messaging.Messaging;
  storage: () => firebase.storage.Storage;
  delete: () => firebase.Promise<any>;

  constructor() {
    return firebase.initializeApp({
      apiKey: 'AIzaSyC6pDjAGuqXtVsU15erxVT99IdB0t4nln4',
      authDomain: 'inobrax-ebs-16552.firebaseapp.com',
      databaseURL: 'https://inobrax-ebs-16552.firebaseio.com',
      storageBucket: 'inobrax-ebs-16552.appspot.com',
      messagingSenderId: '383622803653'
    });
  }

}


问:
Passing parameter to Route in React Router
I have defined a route which cannot be accessed unless the user has logged in. The code for this is as follows:

```<code>    const App = ({ userLoggedIn }) => {
return (
        <Router>
          <div className="App">
            <Header userLoggedIn={ userLoggedIn }/>
            <ProtectedRoute path='/content' component={ Day } userLoggedIn={ userLoggedIn } />
            <Footer />
          </div>
        </Router>
      );
    }
</code>```

I am passing the userLoggedIn as parameter as the App is keeping the state of it. I am defining ProtectedRoute in a similar way as the Auth example in React Router documentation.

```<code>const ProtectedRoute = ({ userLoggedIn, component, ...rest }) => (
  <Route {...rest} render={ props => (
    userLoggedIn ? (
      React.createElement(component, props)
    ) : (
      <Redirect to={{
        pathname: '/login',
        state: { from: props.location }
      }}/>
    )
  )}/>
)
</code>```

But userLoggedIn is always null (even when the value is not null before calling the ProtectedRoute).

I have created a simpler example which I'm testing in the App. I have added the following line:

```<code><TestRoute path='/test' userLoggedIn={ userLoggedIn }/>
</code>```

And created the TestRoute component as follows:

```<code>    const TestRoute = ({ userLoggedIn }) => {
  console.log(userLoggedIn);
  return (
    <Redirect to={{
      pathname: userLoggedIn ? '/yes' : '/no'
    }}/>
  )
}
</code>```

What I see now is than in the console appears null twice and then the real value for userLoggedIn... I guess the first time the component receives the null redirects to /no so when the real value "arrives" it doesn't go to /yes as it should...

How can I access the userLoggedIn param I'm passing? Does anyone has a similar example?

Thanks

答:
You access router properties via props.route i.e. props.route.userLoggedIn.

If your component isn't the top level one you can wrap it in withRouter or access it via the context in v4 but looks like you won't need to.

Body:
I have defined a route which cannot be accessed unless the user has logged in. The code for this is as follows:

    const App = ({ userLoggedIn }) => {
return (
        <Router>

            <ProtectedRoute path='/content' component={ Day } userLoggedIn={ userLoggedIn } />

        </Router>
      );
    }

I am passing the userLoggedIn as parameter as the App is keeping the state of it. I am defining ProtectedRoute in a similar way as the Auth example in React Router documentation.

const ProtectedRoute = ({ userLoggedIn, component, ...rest }) => (
  <Route {...rest} render={ props => (
    userLoggedIn ? (
      React.createElement(component, props)
    ) : (
      <Redirect to={{
        pathname: '/login',
        state: { from: props.location }
      }}/>
    )
  )}/>
)

But userLoggedIn is always null (even when the value is not null before calling the ProtectedRoute).

I have created a simpler example which I'm testing in the App. I have added the following line:

<TestRoute path='/test' userLoggedIn={ userLoggedIn }/>

And created the TestRoute component as follows:

    const TestRoute = ({ userLoggedIn }) => {
  console.log(userLoggedIn);
  return (
    <Redirect to={{
      pathname: userLoggedIn ? '/yes' : '/no'
    }}/>
  )
}

What I see now is than in the console appears null twice and then the real value for userLoggedIn... I guess the first time the component receives the null redirects to /no so when the real value "arrives" it doesn't go to /yes as it should...

How can I access the userLoggedIn param I'm passing? Does anyone has a similar example?

Thanks


问:
Node.js For-Loop and Readline Function Calls?
I'm trying to input a series of test scores and determine their average in JavaScript, and I figured I'd try out Node.js. The function readTestScores() utilizes readline's question() method -- from Node.js's Readline module to obtain a final exam score with a nested for-loop on the inside, with its own call to question() to obtain seven test scores. See below (yes, I know, my code looks messy):

```<code>function readTestScores() {
    var score = 0;

    rl.question('Enter exam score:', (examScore) => {
        console.log("Enter test scores: ");
        for (var i=0; i < 7; i++) {
            rl.question('', (score) => {
            test_avg += score;
            });
        }
        rl.close();
    });
    test_avg /= 7;
}
</code>```

When I run my code, when execution gets to the for-loop it skips all of the question() calls until the very end, and I can only input one value before the program terminates. Is there a way I can correct this?

Edit: Here's the code I used to create the readline interface:

```<code>const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});
</code>```

答:
Here is some code to calculate an average using Readline, based on the tiny cli tutorial:</p>

```<code>'use strict';

var aiScores = [];
var iAverage;

function add(a, b) {
    return a + b;
}

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.setPrompt('Enter exam score > ');
rl.prompt();

rl.on('line', (line) => {
  console.log(line);
  if (Number.isInteger(parseFloat(line))) {
      aiScores.push(parseFloat(line));
      console.log(aiScores);
      console.log(parseFloat(line));
      iAverage = (aiScores.reduce(add, 0)/aiScores.length);
      console.log('Current average = ' + iAverage);
  } else {
      switch(line.trim()) {
        case 'hello':
          console.log('world!');
        case 'close':
          rl.close();
          break;
        default:
          console.log(`Say what? I might have heard '${line.trim()}'`);
          break;
      }
  }
  rl.prompt();
}).on('close', () => {
  console.log('Have a great day!');
  process.exit(0);
});
</code>```

Body:
I'm trying to input a series of test scores and determine their average in JavaScript, and I figured I'd try out Node.js. The function readTestScores() utilizes readline's question() method -- from Node.js's Readline module to obtain a final exam score with a nested for-loop on the inside, with its own call to question() to obtain seven test scores. See below (yes, I know, my code looks messy):

function readTestScores() {
    var score = 0;

    rl.question('Enter exam score:', (examScore) => {
        console.log("Enter test scores: ");
        for (var i=0; i < 7; i++) {
            rl.question('', (score) => {
            test_avg += score;
            });
        }
        rl.close();
    });
    test_avg /= 7;
}

When I run my code, when execution gets to the for-loop it skips all of the question() calls until the very end, and I can only input one value before the program terminates. Is there a way I can correct this?

Edit: Here's the code I used to create the readline interface:

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

Body:
Here is some code to calculate an average using Readline, based on the tiny cli tutorial:

'use strict';

var aiScores = [];
var iAverage;

function add(a, b) {
    return a + b;
}

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.setPrompt('Enter exam score > ');
rl.prompt();

rl.on('line', (line) => {
  console.log(line);
  if (Number.isInteger(parseFloat(line))) {
      aiScores.push(parseFloat(line));
      console.log(aiScores);
      console.log(parseFloat(line));
      iAverage = (aiScores.reduce(add, 0)/aiScores.length);
      console.log('Current average = ' + iAverage);
  } else {
      switch(line.trim()) {
        case 'hello':
          console.log('world!');
        case 'close':
          rl.close();
          break;
        default:
          console.log(`Say what? I might have heard '${line.trim()}'`);
          break;
      }
  }
  rl.prompt();
}).on('close', () => {
  console.log('Have a great day!');
  process.exit(0);
});


问:
Xcode 8.1 setting for deployment devices
How do I set my app for both iphone and ipad using xcode 8.1?

When I go to Targets -> General -> Deployment Info -> Devices and select Universal, I again get a tab below as iphone and ipad.<img src="https://i.stack.imgur.com/lA46i.png" alt=""> Does that mean a single build will not generate an app that is compatible for both ipad and iphone?

If I select the deployment device as only iphone, then the app when loaded on the ipad is not full screen and has a black border.
How can I build an app that is full screen on both ipad and iphone ?

答:
In order to make an application work in both iPhone & iPad then need to follow below steps.

*Before create an project please select universal in device section.
*

In application: didFinishLaunchingWithOptions: put a condition to check the device.
If the device is iPad then load the iPad screen and if the device is iPhone then load the iPhone screen.
Make sure follow the MVC pattern, So that it is easy to populate the data in both the screens.
In application: didFinishLaunchingWithOptions: put a condition to check the device.
If the device is iPad then load the iPad screen and if the device is iPhone then load the iPhone screen.
Make sure follow the MVC pattern, So that it is easy to populate the data in both the screens.


问:
Why am I receiving a JSON exception trying to load data from host url?
I keep receiving a JSON exception. Data will not load.

PHP CODE:

```<code>mysql_connect("somedbuser.byethost13.com","user", "pass") or die(mysql_error());

mysql_select_db("some_database");

$id = $_GET["id"];

$sql=mysql_query("select * from brewery_data where id between ($id+1) and ($id+2)");

while($row=mysql_fetch_assoc($sql))
$output[]=$row;

header('Content-Type:Application/json');

echo(json_encode($output));

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

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

    private AutoCompleteTextView actvBreweryName;
    private AutoCompleteTextView actvBreweryState;
    private RecyclerView recyclerView;
    private LinearLayoutManager linearLayoutManager;
    private CustomAdapter adapter;
    private List<BreweryData> brewery_data_list;
    String[] breweryNames;

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

        actvBreweryName = (AutoCompleteTextView) findViewById(R.id.actv_brewery_name);
        actvBreweryState = (AutoCompleteTextView) findViewById(R.id.actv_state);
        cbAdditives = (CheckBox) findViewById(R.id.cb_additives);
        recyclerView = (RecyclerView) findViewById(R.id.brewery_recycler_view);

        brewery_data_list = new ArrayList<>();
        load_data_from_server(0);

        linearLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(linearLayoutManager);

        adapter = new CustomAdapter(this, brewery_data_list);
        recyclerView.setAdapter(adapter);

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                if (linearLayoutManager.findLastCompletelyVisibleItemPosition() == brewery_data_list.size()-1) {
                    load_data_from_server(brewery_data_list.get(brewery_data_list.size()-1).getId());
                }
            }
        });

        for (int i = 0; i < brewery_data_list.size(); i++) {
            breweryNames[i] = brewery_data_list.get(i).getName();
        }

        ArrayAdapter<String> stateAdapter = new ArrayAdapter<>
                (this, android.R.layout.select_dialog_item, states);
        actvBreweryState.setThreshold(1);
        actvBreweryState.setAdapter(stateAdapter);
    }

    private void load_data_from_server(final int id) {
        AsyncTask<Integer,Void,Void> task = new AsyncTask<Integer, Void, Void>() {

            @Override
            protected Void doInBackground(Integer... integers) {
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder().url("http://thebeerguru.byethost13.com/conn_all.php?id="+id).build();
                try {
                    Response response = client.newCall(request).execute();

                    JSONArray array = new JSONArray(response.body().string());

                    for (int i=0; i<array.length(); i++) {
                        JSONObject object = array.getJSONObject(i);

                        BreweryData data = new BreweryData(
                                object.getInt("id"),
                                object.getString("name"),
                                object.getString("image_link"),
                                object.getString("city"),
                                object.getString("state"),
                                object.getString("phone"),
                                object.getString("website"),
                                object.getString("year_established"),
                                object.getInt("rating"),
                                object.getString("featured"));

                        brewery_data_list.add(data);
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    System.out.println("End of Content");
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                adapter.notifyDataSetChanged();
            }
        };
        task.execute(id);
    }
}
</code>```

JSON DATA:

```<code>[{
    "id": "1",
    "name": "57 Brew Pub & Bistro",
    "image_link": "https:\/\/static.wixstatic.com\/media\/d39f67_ffb7b66c09694eea85479d7a478b64a7~mv2.png\/v1\/fill\/w_278,h_209,al_c,usm_0.66_1.00_0.01\/d39f67_ffb7b66c09694eea85479d7a478b64a7~mv2.png",
    "city": "Greenville",
    "state": "MI",
    "phone": "(616) 712-6226",
    "website": "57brewpub.com",
    "year_established": "N.A.",
    "rating": "0",
    "featured": "true"
}]
</code>```

答:
The problem is that the web host that I am utilizing (Byet Host) implements a simple security antibots module named testcookie-nginx-module for L7 DDoS attack mitigation.

https://kyprizel.github.io/testcookie-nginx-module/

The testcookie-nginx-module makes a 2-step validation:

1) The first time that a HTTP request is done, the module returns a javascript instead of the JSON we are expecting. This script is executed on the client (tipically a web browser) and generates a validation cookie containing an AES key.

2) The script adds the validation cookie to the document and redirects it to the url we actually want to access. The testcookie-nginx-module validates the cookie AES key and lets the request hit the url that will respond with the JSON data we want to access.
On the following HTTP requests the client will have stored the cookie and will add it to the request skipping the step 1.

We just need to add a cookie to the HTTP request to pass the testcookie-nginx-module.

These links should help optimize the code and aid future developers with the same issue:

ByetHost server passing html values "Checking your browser" with JSON String

and

Add cookie to client request OkHttp

:-)

Simply calling .addHeader worked for me.

```<code>        @Override
        protected Void doInBackground(Integer... integers) {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url("http://thebeerguru.byethost13.com/conn_all.php?id="+id)
                    .addHeader("Cookie", "__test=THE_CONTENT_OF_MY_COOKIE; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/")
                    .build();

            try {
                Response response = client.newCall(request).execute();

                JSONArray array = new JSONArray(response.body().string());
</code>```

Thanks to everyone for their counsel and support!

Body:
I keep receiving a JSON exception. Data will not load.

PHP CODE:

mysql_connect("somedbuser.byethost13.com","user", "pass") or die(mysql_error());

mysql_select_db("some_database");

$id = $_GET["id"];

$sql=mysql_query("select * from brewery_data where id between ($id+1) and ($id+2)");

while($row=mysql_fetch_assoc($sql))
$output[]=$row;

header('Content-Type:Application/json');

echo(json_encode($output));

mysql_close();
?>

public class BrowseBrewery extends MainActivity {

    private AutoCompleteTextView actvBreweryName;
    private AutoCompleteTextView actvBreweryState;
    private RecyclerView recyclerView;
    private LinearLayoutManager linearLayoutManager;
    private CustomAdapter adapter;
    private List<BreweryData> brewery_data_list;
    String[] breweryNames;

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

        actvBreweryName = (AutoCompleteTextView) findViewById(R.id.actv_brewery_name);
        actvBreweryState = (AutoCompleteTextView) findViewById(R.id.actv_state);
        cbAdditives = (CheckBox) findViewById(R.id.cb_additives);
        recyclerView = (RecyclerView) findViewById(R.id.brewery_recycler_view);

        brewery_data_list = new ArrayList<>();
        load_data_from_server(0);

        linearLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(linearLayoutManager);

        adapter = new CustomAdapter(this, brewery_data_list);
        recyclerView.setAdapter(adapter);

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                if (linearLayoutManager.findLastCompletelyVisibleItemPosition() == brewery_data_list.size()-1) {
                    load_data_from_server(brewery_data_list.get(brewery_data_list.size()-1).getId());
                }
            }
        });

        for (int i = 0; i < brewery_data_list.size(); i++) {
            breweryNames[i] = brewery_data_list.get(i).getName();
        }

        ArrayAdapter<String> stateAdapter = new ArrayAdapter<>
                (this, android.R.layout.select_dialog_item, states);
        actvBreweryState.setThreshold(1);
        actvBreweryState.setAdapter(stateAdapter);
    }

    private void load_data_from_server(final int id) {
        AsyncTask<Integer,Void,Void> task = new AsyncTask<Integer, Void, Void>() {

            @Override
            protected Void doInBackground(Integer... integers) {
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder().url("http://thebeerguru.byethost13.com/conn_all.php?id="+id).build();
                try {
                    Response response = client.newCall(request).execute();

                    JSONArray array = new JSONArray(response.body().string());

                    for (int i=0; i<array.length(); i++) {
                        JSONObject object = array.getJSONObject(i);

                        BreweryData data = new BreweryData(
                                object.getInt("id"),
                                object.getString("name"),
                                object.getString("image_link"),
                                object.getString("city"),
                                object.getString("state"),
                                object.getString("phone"),
                                object.getString("website"),
                                object.getString("year_established"),
                                object.getInt("rating"),
                                object.getString("featured"));

                        brewery_data_list.add(data);
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    System.out.println("End of Content");
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                adapter.notifyDataSetChanged();
            }
        };
        task.execute(id);
    }
}

JSON DATA:

[{
    "id": "1",
    "name": "57 Brew Pub & Bistro",
    "image_link": "https:\/\/static.wixstatic.com\/media\/d39f67_ffb7b66c09694eea85479d7a478b64a7~mv2.png\/v1\/fill\/w_278,h_209,al_c,usm_0.66_1.00_0.01\/d39f67_ffb7b66c09694eea85479d7a478b64a7~mv2.png",
    "city": "Greenville",
    "state": "MI",
    "phone": "(616) 712-6226",
    "website": "57brewpub.com",
    "year_established": "N.A.",
    "rating": "0",
    "featured": "true"
}]

Body:
The problem is that the web host that I am utilizing (Byet Host) implements a simple security antibots module named testcookie-nginx-module for L7 DDoS attack mitigation.

https://kyprizel.github.io/testcookie-nginx-module/

The testcookie-nginx-module makes a 2-step validation:

1) The first time that a HTTP request is done, the module returns a javascript instead of the JSON we are expecting. This script is executed on the client (tipically a web browser) and generates a validation cookie containing an AES key.

2) The script adds the validation cookie to the document and redirects it to the url we actually want to access. The testcookie-nginx-module validates the cookie AES key and lets the request hit the url that will respond with the JSON data we want to access.
On the following HTTP requests the client will have stored the cookie and will add it to the request skipping the step 1.

We just need to add a cookie to the HTTP request to pass the testcookie-nginx-module.

These links should help optimize the code and aid future developers with the same issue:

ByetHost server passing html values "Checking your browser" with JSON String

and

Add cookie to client request OkHttp

:-)

Simply calling .addHeader worked for me.

        @Override
        protected Void doInBackground(Integer... integers) {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url("http://thebeerguru.byethost13.com/conn_all.php?id="+id)
                    .addHeader("Cookie", "__test=THE_CONTENT_OF_MY_COOKIE; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/")
                    .build();

            try {
                Response response = client.newCall(request).execute();

                JSONArray array = new JSONArray(response.body().string());

Thanks to everyone for their counsel and support!


问:
How to integrate AsMock into AsUnit 4?
Trying to update AsMock mocking framework to v.1.0, and use it with AsUnit 4. But in runtime get a VerifyError (1153, inacceptible override) at the line with [RunWith("asmock.integration.asunit.ASMockRunner")] metatag in the test case class. I use FlashDevelop as an IDE. Have no idea, what's wrong. Could anyone help?</p>

答:
Have you added the includes line to the Flex Compiler arguments field within Eclipse/Flash Developer?

You need to include

-includes asmock.integration.asunit.ASMockRunner

see http://asmock.sourceforge.net/wiki/Installation

Title: How to integrate AsMock into AsUnit 4?


问:
PGError:Error: must be owner of relation
I have using rails application with PostgreSql database.
My application is working fine with PostgreSql.
I want to run my migration on server, I run a command RAILS_ENV=production rake db:migrate
then I get following error:

PGError:Error: must be owner of
  relation table_name

I don't understand why this error occurs?
Please suggest any solution to resolve this error.

Thanks!

答:
You want to change something in the table, but you don't have the permissions to do so. Only the owner of the table can do so.

Use a different database role, the owners role, and you're fine.


问:
How can I merge two object arrays by index in JavaScript?
What would be the best way to combine the two arrays below to get the desired result. I would want them to be combined by index.

Input is:

```<code>var array1 = [[1,2,3,4],[4,5,6,7]]
var array2 = [[a,b,c,d],[e,f,g,h]]
</code>```

Desired output would be:

```<code>var array3 =[{
              array1:[1,2,3,4],
              array2:[a,b,c,d]
             },
             {
              array1:[4,5,6,7],
              array2:[a,b,c,d]
             }]
</code>```

Any variation of the output would work as long as they are grouped by indexes. Thanks in advance.

EDIT: not a duplicate of what was suggestion. Suggestion out [a,1,b,2] and does not group the way the desired output shows.

答:
You can use the array map function:

var array1 = [[1,2,3,4],[4,5,6,7]];
var array2 = [['a','b','c','d'],['e','f','g','h']];

var array3 = array1.map(function (e, i) {
    return [e, array2[i]];
});

console.log(array3);```

Body:
What would be the best way to combine the two arrays below to get the desired result. I would want them to be combined by index.

Input is:

var array1 = [[1,2,3,4],[4,5,6,7]]
var array2 = [[a,b,c,d],[e,f,g,h]]

Desired output would be:

var array3 =[{
              array1:[1,2,3,4],
              array2:[a,b,c,d]
             },
             {
              array1:[4,5,6,7],
              array2:[a,b,c,d]
             }]

Any variation of the output would work as long as they are grouped by indexes. Thanks in advance.

EDIT: not a duplicate of what was suggestion. Suggestion out [a,1,b,2] and does not group the way the desired output shows.


问:
i need to make i program that prints out a shuffled deck of cards and a sorted deck of cards
Create a array of random card.
Output this array in a formatted print statement using a toString method (unsorted).
Use the selection sort to sort your array.
Sort from highest card in the deck to the lowest.
Ascending alphabetical order: clubs (lowest), followed by diamonds, hearts, and spades (highest)
 The highest card in the deck is the ACE of Spades, the lowest is the 2 of Clubs.
Output a sorted array using the toString method.
Also print out the number iterations

i am a starter coder and need help with this here is some of what i started.

```<code>public class DeckOfCards2 {
  public static void main(String[] args) {
    int[] deck = new int[52];
    String[] suits = {"Spades", "Hearts", "Diamonds", "Clubs"};
    String[] ranks = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};

    // Initialize cards
    for (int i = 0; i < deck.length; i++) {
      deck[i] = i;
    }

    // Shuffle the cards
    for (int i = 0; i < deck.length; i++) {
      int index = (int)(Math.random() * deck.length);
      int temp = deck[i];
      deck[i] = deck[index];
      deck[index] = temp;
    }

    // Display the all the cards
    for (int i = 0; i < 52; i++) {
      String suit = suits[deck[i] / 13];
      String rank = ranks[deck[i] % 13];
      System.out.println( rank + " of " + suit);
    }
  }
}
</code>```

答:
This seems like an assignment of sorts so I'm not going to flat out give you the answer, but I can point you in the right direction for most of this so you can figure it out on your own.

First thing is first, you're going to need a toString method in your class. These typically look like the following:

```<code>public String toString(array[]){

    // your code here
    return text;

}
</code>```

The method takes in an array parameter (which is the data you need to print). Inside this, you probably want a for-loop or while-loop of some kind just to loop through the array and add each element to a string instance variable using something like

```<code>text = text + array[i];
</code>```

That way you can add every value in your array to the string, and then just return that string.

Next, the problem states that you have to create a "random array of random card". You already have the code here that generates a random card. Instead, you need to add the results to your new random array instead of printing them out. This is now your master unsorted array. In your main method, you can do something along the lines of

```<code>// prints out unsorted array
System.out.println(toString(array));
</code>```

where array is the name for your random unsorted array.

Next begins the process of creating your sorted array. Read more here on example code for a selection sort: http://www.javatpoint.com/selection-sort-in-java

As the problem says above, make sure to count your iterations. This can be easily accomplished with an incrementing counting variable.

```<code>count++;
</code>```

Once the array is sorted, just send it to the toString() method like we did before, and then just make sure to print out your counting variable.

Body:
Create a array of random card.
Output this array in a formatted print statement using a toString method (unsorted).
Use the selection sort to sort your array.
Sort from highest card in the deck to the lowest.
Ascending alphabetical order: clubs (lowest), followed by diamonds, hearts, and spades (highest)
 The highest card in the deck is the ACE of Spades, the lowest is the 2 of Clubs.
Output a sorted array using the toString method.
Also print out the number iterations

i am a starter coder and need help with this here is some of what i started.

public class DeckOfCards2 {
  public static void main(String[] args) {
    int[] deck = new int[52];
    String[] suits = {"Spades", "Hearts", "Diamonds", "Clubs"};
    String[] ranks = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};

    // Initialize cards
    for (int i = 0; i < deck.length; i++) {
      deck[i] = i;
    }

    // Shuffle the cards
    for (int i = 0; i < deck.length; i++) {
      int index = (int)(Math.random() * deck.length);
      int temp = deck[i];
      deck[i] = deck[index];
      deck[index] = temp;
    }

    // Display the all the cards
    for (int i = 0; i < 52; i++) {
      String suit = suits[deck[i] / 13];
      String rank = ranks[deck[i] % 13];
      System.out.println( rank + " of " + suit);
    }
  }
}

Body:
This seems like an assignment of sorts so I'm not going to flat out give you the answer, but I can point you in the right direction for most of this so you can figure it out on your own.

First thing is first, you're going to need a toString method in your class. These typically look like the following:

public String toString(array[]){

    // your code here
    return text;

}

The method takes in an array parameter (which is the data you need to print). Inside this, you probably want a for-loop or while-loop of some kind just to loop through the array and add each element to a string instance variable using something like

text = text + array[i];

That way you can add every value in your array to the string, and then just return that string.

Next, the problem states that you have to create a "random array of random card". You already have the code here that generates a random card. Instead, you need to add the results to your new random array instead of printing them out. This is now your master unsorted array. In your main method, you can do something along the lines of

// prints out unsorted array
System.out.println(toString(array));

where array is the name for your random unsorted array.

Next begins the process of creating your sorted array. Read more here on example code for a selection sort: http://www.javatpoint.com/selection-sort-in-java

As the problem says above, make sure to count your iterations. This can be easily accomplished with an incrementing counting variable.

count++;

Once the array is sorted, just send it to the toString() method like we did before, and then just make sure to print out your counting variable.


问:
Printing odd numbers
I would like help to find a short and small program in C++ to print out all odd number from 1 to 100 using a loop. Is that possible?</p>

答:
Err, guys...

There's also for(int i = 1; i < 100; i += 2)...

OwnerDisplayName: BE Student

Title: Printing odd numbers


问:
When do I need to use a $ to refer to a variable in Bash?
For example, in my code sometime I do

```<code>$var
</code>```

and sometimes I just do

```<code>var
</code>```

Here is a more concrete example:

```<code>upstream() {
    push server_shared_shortname
    ssh $server_shared -t "cd  ~/public_html; git pull -q ~/root.git master"
}
</code>```

答:
$var is for a variable expansion: you use it when you want Bash to substitute in the value of the variable. So, for example, this:

```<code>var=foo
echo "$var"
</code>```

sets the variable var to the value foo, and then runs the command echo foo.

Edited to add a few things:

$ also has some other related uses; for example, $( ... ) runs the command ..., capturing its output, and expands to that output (minus trailing newlines), and $(( ... )) evaluates the arithmetic expression ... and expands its result:

```<code>cat $(echo foo)      # equivalent to:  cat foo
cat $((2+3))         # equivalent to:  cat 5
</code>```

As codeforester alludes to below, you don't actually need the $ to expand a variable in "arithmetic expressions" (where everything is interpreted as a number), such as are found in (( ... )), $(( ... )), let ..., array indices, and the right-hand-side of variable assignments when the variable has been declared as an integer variable.

The Bash Reference Manual, at http://www.gnu.org/software/bash/manual/bashref.html, is detailed and of high quality. It can take a bit of mental adjustment to start thinking the way that Bash does, but it's worth it IMHO.

Body:
For example, in my code sometime I do

$var

and sometimes I just do

var

Here is a more concrete example:

upstream() {
    push server_shared_shortname
    ssh $server_shared -t "cd  ~/public_html; git pull -q ~/root.git master"
}

Body:
$var is for a variable expansion: you use it when you want Bash to substitute in the value of the variable. So, for example, this:

var=foo
echo "$var"

sets the variable var to the value foo, and then runs the command echo foo.

Edited to add a few things:

$ also has some other related uses; for example, $( ... ) runs the command ..., capturing its output, and expands to that output (minus trailing newlines), and $(( ... )) evaluates the arithmetic expression ... and expands its result:

cat $(echo foo)      # equivalent to:  cat foo
cat $((2+3))         # equivalent to:  cat 5

As codeforester alludes to below, you don't actually need the $ to expand a variable in "arithmetic expressions" (where everything is interpreted as a number), such as are found in (( ... )), $(( ... )), let ..., array indices, and the right-hand-side of variable assignments when the variable has been declared as an integer variable.

The Bash Reference Manual, at http://www.gnu.org/software/bash/manual/bashref.html, is detailed and of high quality. It can take a bit of mental adjustment to start thinking the way that Bash does, but it's worth it IMHO.


问:
How to gray out an html checkbox?
I want to make readonly checkbox.  Like this:

<input type="checkbox" onclick="return false;">
```

I want the checkbox to look like it is disabled or grayed out.

How can I do this?

答:
Simple, css-only way to gray-out a disabled checkbox.</p>

```<code>input[type=checkbox][disabled] {
    filter: invert(25%);
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to gray out an html checkbox?

Body:
I want to make readonly checkbox.  Like this:

<input type="checkbox" onclick="return false;">

I want the checkbox to look like it is disabled or grayed out.

How can I do this?

Body:
Simple, css-only way to gray-out a disabled checkbox.

input[type=checkbox][disabled] {
    filter: invert(25%);
}


问:
Modifying value before get call
I have a property that is dependent on some other properties, code looks like this:

```<code>        get
        {
            if (this.FuelType == "Benzin")
            {
                if (this.KmPrL >= 18)
                {
                    return 'A';
                }
                else if (this.KmPrL < 18 && this.KmPrL >= 14)
                {
                    return 'B';
                }
                else if (this.KmPrL < 14 && this.KmPrL >= 10)
                {
                    return 'C';
                }
                else
                {
                    return 'D';
                }
            }
        }
</code>```

Now I have another class that overrides this get, and I would like it to use this get call, but with the KmPrL value multiplied by 0.7, but without actually modifying the property KmPrL permanently.
How would I go about doing that?

答:
I would change your property getter to use your factor in the check. Then in the override provide the factor as 0.7.

```<code>public virtual char FuelRating
{
    get
    {
        return CalculateRating(this.FuelType, this.KmPrL, 1.0);
    }
}

internal char CalculateRating(string fuelType, double kmprl, double factor)
{
    double x = kmprl * factor;
    if (this.FuelType == "Benzin")
    {
        if (x >= 18)
        {
            return 'A';
        }
        else if (x < 18 && x >= 14)
        {
            return 'B';
        }
        else if (x < 14 && x >= 10)
        {
            return 'C';
        }
        else
        {
            return 'D';
        }
    }
    else
        return char.MinValue;       // not clear what is expected for other fuel types.
}
</code>```

Then in your derived class you would have:

```<code>public override char FuelRating
{
    get
    {
        return CalculateRating(this.FuelType, this.KmPrL, 0.7);
    }
}
</code>```

Finally as an aside, you should be careful with doing complex logic in your property getter. Properties are supposed to be light weight, and if there costly operations within them, you may run into performance problems.

Title: Modifying value before get call

Body:
I have a property that is dependent on some other properties, code looks like this:

        get
        {
            if (this.FuelType == "Benzin")
            {
                if (this.KmPrL >= 18)
                {
                    return 'A';
                }
                else if (this.KmPrL < 18 && this.KmPrL >= 14)
                {
                    return 'B';
                }
                else if (this.KmPrL < 14 && this.KmPrL >= 10)
                {
                    return 'C';
                }
                else
                {
                    return 'D';
                }
            }
        }

Now I have another class that overrides this get, and I would like it to use this get call, but with the KmPrL value multiplied by 0.7, but without actually modifying the property KmPrL permanently.
How would I go about doing that?

Body:
I would change your property getter to use your factor in the check. Then in the override provide the factor as 0.7.

public virtual char FuelRating
{
    get
    {
        return CalculateRating(this.FuelType, this.KmPrL, 1.0);
    }
}

internal char CalculateRating(string fuelType, double kmprl, double factor)
{
    double x = kmprl * factor;
    if (this.FuelType == "Benzin")
    {
        if (x >= 18)
        {
            return 'A';
        }
        else if (x < 18 && x >= 14)
        {
            return 'B';
        }
        else if (x < 14 && x >= 10)
        {
            return 'C';
        }
        else
        {
            return 'D';
        }
    }
    else
        return char.MinValue;       // not clear what is expected for other fuel types.
}

Then in your derived class you would have:

public override char FuelRating
{
    get
    {
        return CalculateRating(this.FuelType, this.KmPrL, 0.7);
    }
}

Finally as an aside, you should be careful with doing complex logic in your property getter. Properties are supposed to be light weight, and if there costly operations within them, you may run into performance problems.


问:
Why doesn't my .htaccess work when the URL includes a real file name?
I'm trying to pass all requests within a certain subdirectory to a file called "handler.php".  The .htaccess I have in place works if the URL is not an actual file name, but not if I enter the name of a real file; it instead loads that file directly, never hitting handler.php.

Could someone explain to me what I'm doing wrong here?  The .htaccess file looks like this:

```<code>RewriteEngine On

RewriteRule ^$ handler.php?url=$1
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /handler.php?url=$1 [L,QSA]
</code>```

Is there something I'm doing wrong here?  I want all requests to pass the url into handler.php.

答:
The rule doesn't match real files, because the conditions say so

```<code>RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
</code>```

These conditions match, if the request does not (!) match a real file (-f) and if it doesn't match a real directory (-d).

If you want to handle all requests no matter what, remove these conditions. You can also remove the first rule, because it is handled by this one too. This leaves just the second rule, but you must prevent a rewrite loop with another condition

```<code>RewriteCond %{REQUEST_URI} !^/handler\.php
RewriteRule ^(.*)$ /handler.php?url=$1 [L,QSA]
</code>```

Body:
I'm trying to pass all requests within a certain subdirectory to a file called "handler.php".  The .htaccess I have in place works if the URL is not an actual file name, but not if I enter the name of a real file; it instead loads that file directly, never hitting handler.php.

Could someone explain to me what I'm doing wrong here?  The .htaccess file looks like this:

RewriteEngine On

RewriteRule ^$ handler.php?url=$1
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /handler.php?url=$1 [L,QSA]

Is there something I'm doing wrong here?  I want all requests to pass the url into handler.php.

Body:
The rule doesn't match real files, because the conditions say so

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

These conditions match, if the request does not (!) match a real file (-f) and if it doesn't match a real directory (-d).

If you want to handle all requests no matter what, remove these conditions. You can also remove the first rule, because it is handled by this one too. This leaves just the second rule, but you must prevent a rewrite loop with another condition

RewriteCond %{REQUEST_URI} !^/handler\.php
RewriteRule ^(.*)$ /handler.php?url=$1 [L,QSA]


问:
Entity Framework interceptor for log Debug.Write web.config
I want to create a Debug.Write logger on my project while development time. So I can do this on code configuration like this:

```<code>    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        Action<string> print = message => Debug.WriteLine(message);
        Database.Log =print;
    }
</code>```

But I want to add this on web.config file as entity framework section element. Is there any way to do this?

```<code><interceptors>
  <interceptor type="System.Data.Entity.Infrastructure.Interception.DatabaseLogger, EntityFramework">
      ??????
  </interceptor>
</interceptors>
</code>```

答:
You can configure the interceptor either by using config file or code-based configuration.

See the following on how to do this (includes demo):

http://www.entityframeworktutorial.net/entityframework6/database-command-interception.aspx

Assuming you have the following interceptor

```<code> EFCommandInterceptor: IDbCommandInterceptor
</code>```

Config

```<code><entityFramework>
    <interceptors>
        <interceptor type="EF6DBFirstTutorials.EFCommandInterceptor, EF6DBFirstTutorials">
        </interceptor>
    </interceptors>
</entityFramework>
</code>```

Code

```<code>public class EF6CodeConfig : DbConfiguration
{
    public EF6CodeConfig()
    {
        this.AddInterceptor(new EFCommandInterceptor());
    }
}
</code>```

Body:
I want to create a Debug.Write logger on my project while development time. So I can do this on code configuration like this:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        Action<string> print = message => Debug.WriteLine(message);
        Database.Log =print;
    }

But I want to add this on web.config file as entity framework section element. Is there any way to do this?

<interceptors>
  <interceptor type="System.Data.Entity.Infrastructure.Interception.DatabaseLogger, EntityFramework">
      ??????
  </interceptor>
</interceptors>

Body:
You can configure the interceptor either by using config file or code-based configuration.

See the following on how to do this (includes demo):

http://www.entityframeworktutorial.net/entityframework6/database-command-interception.aspx

Assuming you have the following interceptor

 EFCommandInterceptor: IDbCommandInterceptor

Config

<entityFramework>
    <interceptors>
        <interceptor type="EF6DBFirstTutorials.EFCommandInterceptor, EF6DBFirstTutorials">
        </interceptor>
    </interceptors>
</entityFramework>

Code

public class EF6CodeConfig : DbConfiguration
{
    public EF6CodeConfig()
    {
        this.AddInterceptor(new EFCommandInterceptor());
    }
}


问:
SVG online no background color
I came across a problem with my SVG-file. When opening the document directly in the browser the SVG-file looks good.

```<code>http://imgh.us/websdeign-icon@3x.svg
</code>```

But when i'm using codepen or drop it on to my server the black background disappears.

```<code>https://codepen.io/anon/pen/vxvBOV
</code>```

What is going on?

答:
It would seem that you have a base64 encoded image in your svg file (black background). It seems that browser is having difficulty in parsing svg file with base64 code embeded in it, if it's added as source to img tag. Try copying and pasting your svg code to codepen directly - you'll see that this time, the black background stays.

My advice is to either remove base64 images from the svg file, or embed svg code inline. Take a look at official W3 docs, to read more on the matter: https://www.w3.org/Graphics/SVG/IG/resources/svgprimer.html#SVG_in_HTML

Title: SVG online no background color

Body:
I came across a problem with my SVG-file. When opening the document directly in the browser the SVG-file looks good.

http://imgh.us/websdeign-icon@3x.svg

But when i'm using codepen or drop it on to my server the black background disappears.

https://codepen.io/anon/pen/vxvBOV

What is going on?


问:
ReactJS - cannot read property 'props' of undefined
I am practicing React native. When I compile the following program, I am getting Cannot read property 'props' of undefined error for Details.js. Kindly let me know as to what went wrong here.

Layout.js

```<code>import React, {Component} from 'react';
import Header from './Header';
import Details from './Details';

export default class Layout extends React.Component {
constructor(props){
  super(props);
    this.state = {
                     heading: "Welcome no-name guy!",
                     header: "I am your header",
                     footer: "I am your footer"
                 };
               }

render() {
   return (
           <div>
            <Header headerprop={this.state.header} />
            <Details detailprop={this.state.heading} />
          </div>
          );
         }
}
</code>```

Details.js

```<code>import React from 'react';

const Details = (detailprop) => {
 return (
  <div className="heading-style">{this.props.detailprop}</div>
 );
 };
Details.bind(this);
export default Details;
</code>```

Header.js

```<code>import React, {Component} from 'react';

export default class Header extends React.Component {
 render(){
           return(
                   <div>{this.props.headerprop}</div>
                 );
          }
 }
</code>```

答:
Details.js is a stateless functional react component. https://facebook.github.io/react/docs/components-and-props.html

It receives props as its argument. You don't need this here.

```<code>import React from 'react';

const Details = (props) => {
 return (
  <div className="heading-style">{props.detailprop}</div>
 );
 };
Details.bind(this); // you don't need this
export default Details;
</code>```

Also, div elements will not work for react-native . Please refer react native docs https://facebook.github.io/react-native/

Body:
I am practicing React native. When I compile the following program, I am getting Cannot read property 'props' of undefined error for Details.js. Kindly let me know as to what went wrong here.

Layout.js

import React, {Component} from 'react';
import Header from './Header';
import Details from './Details';

export default class Layout extends React.Component {
constructor(props){
  super(props);
    this.state = {
                     heading: "Welcome no-name guy!",
                     header: "I am your header",
                     footer: "I am your footer"
                 };
               }

render() {
   return (

          );
         }
}

Details.js

import React from 'react';

const Details = (detailprop) => {
 return (

{this.props.detailprop}

 );
 };
Details.bind(this);
export default Details;

Header.js

import React, {Component} from 'react';

export default class Header extends React.Component {
 render(){
           return(

{this.props.headerprop}

                 );
          }
 }

Body:
Details.js is a stateless functional react component. https://facebook.github.io/react/docs/components-and-props.html

It receives props as its argument. You don't need this here.

import React from 'react';

const Details = (props) => {
 return (
  <div className="heading-style">{props.detailprop}</div>
 );
 };
Details.bind(this); // you don't need this
export default Details;

Also, div elements will not work for react-native . Please refer react native docs https://facebook.github.io/react-native/


问:
Two divs: the first one is floated and the position of the second one depends on its width, why?
I have two divs. The first one is width: 50% and the second on is width: 80%. When I set float: left to the first one, the text of the second one is placed on the right of the first one. That's ok, it is what I expect. See the code here:

floated div

second div
```
</div>
</div>
</p>

<p><strong>The doubt</strong>: if I set <code>width: 30%</code> to the second div. The div is placed below the first one, why? Check the snippet:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>      <div style="float: left; width: 50%; background: orange">floated div</div>
      <div style="width: 30%; background: red">second div</div> </code>```

答:
float doesn't cause block elements to display side by side or wrap necessarily. Using float will cause text and inline elements that come after the floated element to wrap around it. So if the second div is wider than the first, the text in the second will wrap around the first. If the second div is more narrow (or the same size) as the first, it won't wrap since the second div is not just text or an inline element.

https://developer.mozilla.org/en-US/docs/Web/CSS/float

The float CSS property specifies that an element should be taken from the normal flow and placed along the left or right side of its container, where text and inline elements will wrap around it.

Body:
I have two divs. The first one is width: 50% and the second on is width: 80%. When I set float: left to the first one, the text of the second one is placed on the right of the first one. That's ok, it is what I expect. See the code here:

floated div

second div

The doubt: if I set width: 30% to the second div. The div is placed below the first one, why? Check the snippet:

floated div

second div


问:
How to parse parts of a string and insert them into columns
I have a column in my database that stores data like so:

```<code> Description - (Width 1 Height 1)
</code>```

I need to parse this string and insert the Width and Height into 2 new columns.

I currently have this query:

```<code>SELECT CASE
        WHEN Description LIKE '%Width %' THEN SUBSTRING(Description, CHARINDEX('Width ', Description) + 6, 1)
      END AS Width,
      CASE
        WHEN Description LIKE '%Height %' THEN SUBSTRING(Description, CHARINDEX('Height ', Description) + 7, 1)
      END AS Height
FROM table
</code>```

It works great with this query, but if I have an entry like this, it only grabs the first digit:

```<code>Description - (Width 25 Height 10)
</code>```

I know this is because I am using '1' as the length of my SUBSTRING, but I am not sure how I can make this work properly.

答:
SQL Server does not make parsing strings easy.

```<code>SELECT LEFT(v.wstr, CHARINDEX(' ', v.wstr + ' ') - 1) as width,
       LEFT(v.hstr, CHARINDEX(' ', v.hstr + ' ') - 1) as width,
FROM table OUTER APPLY
     (VALUES (STUFF(Description, 1, CHARINDEX('Width ', Description + 'Width ') + 6, ''),
              STUFF(Description, 1, CHARINDEX('Height ', Description + 'Height ') + 7, ''),
             )
     ) v(wstr, hstr);
</code>```

Notes:

Unlike your version, this returns an empty string when the values are not present, rather than NULL (it is easy to add the CASE back in).

Like your version, this assumes that the pattern ends with a space.

Like your version, this assumes that "Width" and "Height" do not appear in the description.

Body:
I have a column in my database that stores data like so:

 Description - (Width 1 Height 1)

I need to parse this string and insert the Width and Height into 2 new columns.

I currently have this query:

SELECT CASE
        WHEN Description LIKE '%Width %' THEN SUBSTRING(Description, CHARINDEX('Width ', Description) + 6, 1)
      END AS Width,
      CASE
        WHEN Description LIKE '%Height %' THEN SUBSTRING(Description, CHARINDEX('Height ', Description) + 7, 1)
      END AS Height
FROM table

It works great with this query, but if I have an entry like this, it only grabs the first digit:

Description - (Width 25 Height 10)

I know this is because I am using '1' as the length of my SUBSTRING, but I am not sure how I can make this work properly.

Body:
SQL Server does not make parsing strings easy.

SELECT LEFT(v.wstr, CHARINDEX(' ', v.wstr + ' ') - 1) as width,
       LEFT(v.hstr, CHARINDEX(' ', v.hstr + ' ') - 1) as width,
FROM table OUTER APPLY
     (VALUES (STUFF(Description, 1, CHARINDEX('Width ', Description + 'Width ') + 6, ''),
              STUFF(Description, 1, CHARINDEX('Height ', Description + 'Height ') + 7, ''),
             )
     ) v(wstr, hstr);

Notes:

Unlike your version, this returns an empty string when the values are not present, rather than NULL (it is easy to add the CASE back in).

Like your version, this assumes that the pattern ends with a space.

Like your version, this assumes that "Width" and "Height" do not appear in the description.


问:
You have an error in your SQL syntax- PHP
I am trying to update my table row but can't get success.

here is error that coming.

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Current_date = '2017-03-30', Content = 'This is first notification te' at line 2

here is my code

```<code>if(!empty($_FILES) || isset($_FILES['Details_file'])){
    $filetmp = $_FILES["Details_file"]["tmp_name"];
    $filename = $_FILES["Details_file"]["name"];
    $filetype = $_FILES["Details_file"]["type"];
    $filepath = "notification/".$filename;

    move_uploaded_file($filetmp, $filepath);

    echo $_POST['post_date'];
    $stmt = $con1->prepare("UPDATE notification SET
        Current_date = '".$_POST['post_date']."',
        Content = '".$_POST['Content']."',
        File_name= '".$filename."',
        File_path ='".$filepath."',
        Apply_link = '".$_POST['apply_now']."',
        Last_date = '".$_POST['Last_date']."'
        WHERE id = '".$_POST['fetch_id']."'") or die(mysqli_error($con1));

    $stmt->execute();
    $stmt->close();
}
</code>```

any one can tell me what is problem with my code here.

答:
There is no point in prepare() and execute() if you aren't using them properly. Try this instead:

```<code>$query = "UPDATE notification SET `Current_date`=?, `Content`=?, `File_name`=?, `File_path`=?, `Apply_link`=?, `Last_date`=? WHERE `id`=?";
$stmt = $con1->prepare($query);
$stmt->bind_param("ssssssi", $_POST['post_date'], $_POST['Content'], $filename, $filepath, $_POST['apply_now'], $_POST['Last_date'], $_POST['fetch_id']);
$stmt->execute();
$stmt->close();
</code>```

You'll want to check the return values of each step (prepare, bind, execute) to ensure there are no errors being returned.

Body:
I am trying to update my table row but can't get success.

here is error that coming.

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Current_date = '2017-03-30', Content = 'This is first notification te' at line 2

here is my code

if(!empty($_FILES) || isset($_FILES['Details_file'])){
    $filetmp = $_FILES["Details_file"]["tmp_name"];
    $filename = $_FILES["Details_file"]["name"];
    $filetype = $_FILES["Details_file"]["type"];
    $filepath = "notification/".$filename;

    move_uploaded_file($filetmp, $filepath);

    echo $_POST['post_date'];
    $stmt = $con1->prepare("UPDATE notification SET
        Current_date = '".$_POST['post_date']."',
        Content = '".$_POST['Content']."',
        File_name= '".$filename."',
        File_path ='".$filepath."',
        Apply_link = '".$_POST['apply_now']."',
        Last_date = '".$_POST['Last_date']."'
        WHERE id = '".$_POST['fetch_id']."'") or die(mysqli_error($con1));

    $stmt->execute();
    $stmt->close();
}

any one can tell me what is problem with my code here.

Body:
There is no point in prepare() and execute() if you aren't using them properly. Try this instead:

$query = "UPDATE notification SET `Current_date`=?, `Content`=?, `File_name`=?, `File_path`=?, `Apply_link`=?, `Last_date`=? WHERE `id`=?";
$stmt = $con1->prepare($query);
$stmt->bind_param("ssssssi", $_POST['post_date'], $_POST['Content'], $filename, $filepath, $_POST['apply_now'], $_POST['Last_date'], $_POST['fetch_id']);
$stmt->execute();
$stmt->close();

You'll want to check the return values of each step (prepare, bind, execute) to ensure there are no errors being returned.


问:
What does the jsr keyword mean?
I'm looking at some Java code, and I've noticed the following:

```<code>if (!foo(bar, baz, qux)) {
    i = 0; jsr 433;
}
</code>```

javac chokes on it, saying it's not a statement and that a semicolon is expected after the keyword jsr.

I did some Googling, and I found some code containing the same thing, which leads me to believe it's there intentionally (even though they weren't able to get it to compile either). So what does jsr do? How does one get code containing it to compile?

答:
JSR (which stands for Jump Subroutine) is part of the Java Virtual Machine Specification. It's a instruction set for the JVM.

Brief description

The address of the opcode of the
  instruction immediately following this
  jsr instruction is pushed onto the
  operand stack as a value of type
  returnAddress.

This can be found on the JVM book 2nd edition.

Title: What does the jsr keyword mean?

Body:
I'm looking at some Java code, and I've noticed the following:

if (!foo(bar, baz, qux)) {
    i = 0; jsr 433;
}

javac chokes on it, saying it's not a statement and that a semicolon is expected after the keyword jsr.

I did some Googling, and I found some code containing the same thing, which leads me to believe it's there intentionally (even though they weren't able to get it to compile either). So what does jsr do? How does one get code containing it to compile?


问:
Can I change the MCU sleeping mode programmatically on FreeRTOS?
I am a new been on FreeRTOS and working on a board that uses the

Cortex-M4 Processor and the FreeRTOS

"FreeRTOS V7.4.2 - Copyright (C) 2013 Real Time Engineers Ltd."

Can I change the MCU mode programmatically or through a debugger?

I want to make sure the MCU is NOT in sleeping mode. I looked at this thread but did not help much.

Entering sleep mode on arm cortex m4

thank you.

答:
Unless you specifically set the processor to enter sleep mode it will not be in sleep mode. You shouldn't have to do anything. You are also using quite an old version of FreeRTOS, I would recommend downloading 9.0.0.

See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0553a/BABHHGEB.html

for info on how to enter sleep mode.


问:
Waiting for get request response from JS does not work
In my javascript code I have:

```<code>function getThing(){
    var url = "myhost/thing";
    var x = new XMLHttpRequest();
    x.open("GET", url, false);
    x.onload = function (){
        return x.responseText
    }
    x.send(null);
}

console.log(getThing())
</code>```

And console log gives me undefined.

What am I doing wrong?

答:
Your HTTP request is executed asynchronously, and getThing is not returning anything other than undefined. Instead, your onload handler is returning the requested value, which is not used.

Instead, you need to wait with logging until the call has returned:

```<code>function getThing(){
    var url = "myhost/thing";
    var x = new XMLHttpRequest();
    x.open("GET", url);
    x.onload = function (){
        console.log(x.responseText);
    }
    x.send(null);
}

getThing();
</code>```

Body:
In my javascript code I have:

function getThing(){
    var url = "myhost/thing";
    var x = new XMLHttpRequest();
    x.open("GET", url, false);
    x.onload = function (){
        return x.responseText
    }
    x.send(null);
}

console.log(getThing())

And console log gives me undefined.

What am I doing wrong?

Body:
Your HTTP request is executed asynchronously, and getThing is not returning anything other than undefined. Instead, your onload handler is returning the requested value, which is not used.

Instead, you need to wait with logging until the call has returned:

function getThing(){
    var url = "myhost/thing";
    var x = new XMLHttpRequest();
    x.open("GET", url);
    x.onload = function (){
        console.log(x.responseText);
    }
    x.send(null);
}

getThing();


问:
Can the NOT operator work on multiple conditions present in parenthesis?
I run following query in MySQL :

```<code>SELECT * FROM Customers
WHERE NOT Country='Germany' AND NOT Country='USA';
</code>```

It returned me exactly the correct expected result.

After that I run following query :

```<code>SELECT * FROM Customers
WHERE NOT (Country='Germany' AND Country='USA');
</code>```

This time it returned me all the records present in the table(result-set of the query SELECT * FROM Customers;)

I'm not understanding why the NOT operator is not working in second query with parenthesis?

You can go to this link and check :

```<code>https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_where_not_and
</code>```

答:
You got bitten by operator priority. Parentheses are your friend, you see.

```<code>WHERE NOT Country='Germany' AND NOT Country='USA';
</code>```

actually means, since NOT has precedence over AND:

```<code>WHERE (NOT Country='Germany') AND (NOT Country='USA');
</code>```

Since "NOT a=b" is "a!=b", this means:

```<code>WHERE Country!='Germany' AND Country!='USA';
</code>```

which, as the others pointed out, looks muuuuch better like this:

```<code>WHERE Country NOT IN ('Germany', 'USA');
</code>```

Now, next topic. This one:

```<code>WHERE NOT (Country='Germany' AND Country='USA');
</code>```

Country can not be Germany and USA at the same time, so the stuff inside the () is always FALSE, so this equates to:

```<code>WHERE NOT (FALSE);
</code>```

i.e.

```<code>WHERE TRUE;
</code>```

ie, you get your whole table.

Body:
I run following query in MySQL :

SELECT * FROM Customers
WHERE NOT Country='Germany' AND NOT Country='USA';

It returned me exactly the correct expected result.

After that I run following query :

SELECT * FROM Customers
WHERE NOT (Country='Germany' AND Country='USA');

This time it returned me all the records present in the table(result-set of the query SELECT * FROM Customers;)

I'm not understanding why the NOT operator is not working in second query with parenthesis?

You can go to this link and check :

https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_where_not_and

Body:
You got bitten by operator priority. Parentheses are your friend, you see.

WHERE NOT Country='Germany' AND NOT Country='USA';

actually means, since NOT has precedence over AND:

WHERE (NOT Country='Germany') AND (NOT Country='USA');

Since "NOT a=b" is "a!=b", this means:

WHERE Country!='Germany' AND Country!='USA';

which, as the others pointed out, looks muuuuch better like this:

WHERE Country NOT IN ('Germany', 'USA');

Now, next topic. This one:

WHERE NOT (Country='Germany' AND Country='USA');

Country can not be Germany and USA at the same time, so the stuff inside the () is always FALSE, so this equates to:

WHERE NOT (FALSE);

i.e.

WHERE TRUE;

ie, you get your whole table.


问:
Jms How to know subscriber is not alive anymore
I have a distributed system application that uses JBoss as an application server. I have a client application that serves as a simulation engine. When client is up, it sends an registration message(JMS message)  to Server, then some field is set in the database. When Server is up, it sends a message ( a topic) to all clients to check that they are alive.  If clients are alive, they can read message and send a response to server (queue) that it is alive.

If user close client normally, client send a message to server that I will unregister. Then server unregisters it. This is done in database side.

If user close client abnormally(kill) , then client can not send a message to server for unregistration. Then server does not know this client is not alive anymore.  This causes inconsistency in my application. So I need a way to understand that client subscribed a topic is not subscribed anymore.

Server sends a message to topic to check that clients are alive.

```<code>@Schedule(hour = "*", minute = "*", second = "30", persistent = false)
public void sendNodeStatusRequest() {
    Message msg = MessageFactory.createStatusRequestMessage();
    publishNodeMessage(msg);

}
</code>```

After a time, Server show following logs. Could I catch this warning from Java?

```<code>07:17:00,698 WARN  [org.hornetq.core.protocol.core.impl.RemotingConnectionImpl] Connection failure
 has been detected: Did not receive ping from /127.0.0.1:61888. It is likely
 the client has exited or crashed without closing its connection, or the
 network between the server and client has failed. The connection will now be  closed. [code=3]
 07:17:00,698 WARN  [org.hornetq.core.server.impl.ServerSessionImpl] Client
connection failed, clearing up resources for session 4e4e9dc6-153e-11e7-
 80fa-742b62812c29
</code>```

答:
To me the whole point of messaging system is decoupled communication. The sender (server in your case) send its stuff to the topic without actually knowing who will  get the message. The clients come and go, and they should be able to read the message whenever it (still) resides in the topic.

Now from your question I understand that the server keeps track of all the connected clients by means of receiving the message back to the dedicated queue.

So I'm asking myself - maybe its something wrong with the design here.

Let me propose slightly different way of implementation.
The server should not be aware of any client, at most (because your system seems to work this way) it should know that client A, B and C are alive now only because these clients passed to the server this knowledge.

Why just don't make clients sending the "keep-alive" message every, say 1 minute (or less, depending on your needs) to the server queue without prior message from the server.
The message can include some client identifier and probably time if its not added by the infrastructure or something)

So the server will just get this message and it will keep track in memory the list of available clients along with the last time they've sent something.
So if some client disconnects "gracefully" - it can send a special message to the server like "I'm client A and consider me disconnected". Otherwise (abnormal termination/network outage/whatever) - it just won't send anything, the server will have a special process that will check whether there are stale clients on the list and if it finds them - it knows that something went wrong.

Body:
I have a distributed system application that uses JBoss as an application server. I have a client application that serves as a simulation engine. When client is up, it sends an registration message(JMS message)  to Server, then some field is set in the database. When Server is up, it sends a message ( a topic) to all clients to check that they are alive.  If clients are alive, they can read message and send a response to server (queue) that it is alive.

If user close client normally, client send a message to server that I will unregister. Then server unregisters it. This is done in database side.

If user close client abnormally(kill) , then client can not send a message to server for unregistration. Then server does not know this client is not alive anymore.  This causes inconsistency in my application. So I need a way to understand that client subscribed a topic is not subscribed anymore.

Server sends a message to topic to check that clients are alive.

@Schedule(hour = "*", minute = "*", second = "30", persistent = false)
public void sendNodeStatusRequest() {
    Message msg = MessageFactory.createStatusRequestMessage();
    publishNodeMessage(msg);

}

After a time, Server show following logs. Could I catch this warning from Java?

07:17:00,698 WARN  [org.hornetq.core.protocol.core.impl.RemotingConnectionImpl] Connection failure
 has been detected: Did not receive ping from /127.0.0.1:61888. It is likely
 the client has exited or crashed without closing its connection, or the
 network between the server and client has failed. The connection will now be  closed. [code=3]
 07:17:00,698 WARN  [org.hornetq.core.server.impl.ServerSessionImpl] Client
connection failed, clearing up resources for session 4e4e9dc6-153e-11e7-
 80fa-742b62812c29


问:
Static variable accessed from null variable
Why is a null reference exception not thrown when I try to print the value of a static field value from an uninitialized instance of a class.

I expected a Null reference exception in the following code:

```<code>public class Check {

  static int i=1;

  public static void main(String []args)
  {
     Check ch = null;
     System.out.print(ch.i);
  }

}
</code>```

Produces output as: 1.

答:
Given that i is static (it can be accessed through the class directly, no need to use an instance for it), in the code ch.i, the compiler checks for the type of the reference of ch (Check) and use it for accessing the variable i instead of using the class instance. This mean null (the instance) is not used at all (thus we don't get any exception).

That's it, the output of Check.i is 1.

Body:
Why is a null reference exception not thrown when I try to print the value of a static field value from an uninitialized instance of a class.

I expected a Null reference exception in the following code:

public class Check {

  static int i=1;

  public static void main(String []args)
  {
     Check ch = null;
     System.out.print(ch.i);
  }

}

Produces output as: 1.


问:
Printing odd numbers
I would like help to find a short and small program in C++ to print out all odd number from 1 to 100 using a loop. Is that possible?</p>

答:
I think I can beat Benoit ;-)</p>

```<code>for(int i = 1; i < 100; i+=2) std::cout << i << std::endl;
</code>```

Title: Printing odd numbers

Body:
I think I can beat Benoit ;-)

for(int i = 1; i < 100; i+=2) std::cout << i << std::endl;


问:
how to correctly structure reducer when trying to do filter?
Looking at https://lodash.com/docs/4.17.4#filter

I have an array of objects, and each object looks something like this:

```<code>{
  id: 10005,
  title: 'Brooklyn Bridge by Night',
  author: 'Charles Gooding',
  takenOn: 'some date',
  description: 'Photo of the Brooklyn Bridge at night.  Taken from somewhere I am just making this up to be honest.',
  cameraId: 301,
  // some other stuff
}
</code>```

I am trying to do a quick filter and here's my reducer for FILTER_RESULTS.  How can I avoid having to use an array that is built up?

```<code>case 'FILTER_RESULTS':
  const results = [];
  state.photos.map((a) => {
    Object.keys(a).forEach((b) => {
      if (a[b].toLowerCase().includes(action.value.toLowerCase())) {
        results.push(a); // also a question on this one
      }
    });
    return results;
  });
  return {
    ...state,
    state.photosFilter: results
  }
</code>```

Also, how can I make sure that the object I push into results is unique?  Thanks

答:
Make small, narrow functions; they are easy to understand and combine.

```<code>function includesAttributes(thing, target) {
   return _.some(Object.keys(thing),
                 (key) => thing[key].toLowerCase().includes(target.toLowerCase()));
}
</code>```

Then

```<code>case 'FILTER_RESULTS':
  return state.photos.filter((record) => includesAttribute(record, action.value));
</code>```

Body:
Looking at https://lodash.com/docs/4.17.4#filter

I have an array of objects, and each object looks something like this:

{
  id: 10005,
  title: 'Brooklyn Bridge by Night',
  author: 'Charles Gooding',
  takenOn: 'some date',
  description: 'Photo of the Brooklyn Bridge at night.  Taken from somewhere I am just making this up to be honest.',
  cameraId: 301,
  // some other stuff
}

I am trying to do a quick filter and here's my reducer for FILTER_RESULTS.  How can I avoid having to use an array that is built up?

case 'FILTER_RESULTS':
  const results = [];
  state.photos.map((a) => {
    Object.keys(a).forEach((b) => {
      if (a[b].toLowerCase().includes(action.value.toLowerCase())) {
        results.push(a); // also a question on this one
      }
    });
    return results;
  });
  return {
    ...state,
    state.photosFilter: results
  }

Also, how can I make sure that the object I push into results is unique?  Thanks

Body:
Make small, narrow functions; they are easy to understand and combine.

function includesAttributes(thing, target) {
   return _.some(Object.keys(thing),
                 (key) => thing[key].toLowerCase().includes(target.toLowerCase()));
}

Then

case 'FILTER_RESULTS':
  return state.photos.filter((record) => includesAttribute(record, action.value));