问:
How to navigate nested components with react-router 4
I have a screen with buttons, common background and common title and changing nested components. Inside this screen I want to change nested components with a click of a button. Nested components must change each other in a circle with left and right button. So far I did a lots of attempts to achieve this ( I try to do it with withRouter), I give you code only of one of my attempts, but all of them didn't work. I don't get any errors, I see route in browser is changing but screen doesn't, I see only the first nested component. There is questions about this on SOF, but they related to older version of react-router.
Here my code, if you need more information feel free to ask in comments.

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

import { Link,
         BrowserRouter as Router,
         Route,
         Switch,
         withRouter } from 'react-router-dom';

import Info1 from './info/info1';
import Info2 from './info/info2';
import Info3 from './info/info3';
import Info4 from './info/info4';

class Info extends Component {

   constructor(props) {
    super(props);

    this.currentIndex = 1;

  }

  componentDidMount() {

  }

  leftHandler() {
    console.log("left click");
    var temp = this.currentIndex;
    this.changeScreen(--temp);
  }

  rightHandler() {
    console.log("right click");
    var temp = this.currentIndex;
    this.changeScreen(++temp);
  }

  changeScreen(index) {

    const numberOfScreens = 4;

    if(index < 1)
        this.currentIndex = numberOfScreens;
    else if(index > numberOfScreens)
        this.currentIndex = 1;
    else
        this.currentIndex = index;
    this.props.history.push("/info/" + this.currentIndex);
  }

  render() {

    return (
      <Router>
       <div className="info-common">
           <img className="game-title info-game"/>
           <Switch>
                 <Route path="/info/1" component={ Info1 }/>
                <Route path="/info/2" component={ Info2 }/>
                <Route path="/info/3" component={ Info3 }/>
                <Route path="/info/4" component={ Info4 }/>
            </Switch>
            <Link to="/rings"><button className="back-info-btn">назад</button></Link>
            <button onClick={ this.leftHandler.bind(this) } className="left-info-btn"></button>
            <button onClick={ this.rightHandler.bind(this)} className="right-info-btn"></button>
       </div>
      </Router>
    );
  }

}

Info.propTypes = {
  history: React.PropTypes.shape({
    push: React.PropTypes.func.isRequired,
    }).isRequired,
  location: React.PropTypes.isRequired,
};

export default withRouter(Info);
</code>```

EDIT:
While I accepted given answer, I didn't test it, in my project I used this solution:

```<code>app.js

import {
  BrowserRouter as Router,
  Route,
  Link
} from 'react-router-dom';

...

render() {

    return (
      <div id='game-container' width="1236" height="634">
        <Router>
        <div>
          <Route path="/info" component={ Info }/>
        </div>
        </Router>
      </div>
    );
  }
</code>```

Then in Info itself:

```<code>Info.js

class Info extends Component {

   constructor(props) {
   super(props);

   this.currentIndex = 1;

  }

  leftHandler() {
    console.log("left click");
    var temp = this.currentIndex;
    this.changeScreen(--temp);
  }

  rightHandler() {
    console.log("right click");
    var temp = this.currentIndex;
    this.changeScreen(++temp);
  }

  changeScreen(index) {

    const numberOfScreens = 4;

    if(index < 1)
        this.currentIndex = numberOfScreens;
    else if(index > numberOfScreens)
        this.currentIndex = 1;
    else
        this.currentIndex = index;
    this.props.history.push("/info/" + this.currentIndex);
  }

  render() {

    return (
       <div className="info-common">
           <img className="game-title info-game" src={ this.drawGame() }/>
            <Switch>
                <Route path={`${this.props.match.path}/1`} component={ Info1 }/>
                <Route path={`${this.props.match.path}/2`} component={ Info2 }/>
                <Route path={`${this.props.match.path}/3`} component={ Info3 }/>
                <Route path={`${this.props.match.path}/4`} component={ Info4 }/>
            </Switch>
            <Link to="/rings"><button className="back-info-btn">назад</button></Link>
            <button onClick={ this.leftHandler.bind(this) } className="left-info-btn"></button>
            <button onClick={ this.rightHandler.bind(this)} className="right-info-btn"></button>
       </div>
    );
  }

}

Info.propTypes = {
  history: React.PropTypes.shape({
    push: React.PropTypes.func.isRequired,
    }).isRequired,
  location: React.PropTypes.object.isRequired,
};

export default withRouter(Info);
</code>```

答:
If you wrap a component in withRouter, you can only use it inside a <Router>, just like <Route>s etc.

To get your example working, you need to make <Info> a child of <Router>, since it uses withRouter. First, remove the <Router> from the render method, and just render the
 as the top-level component:

render() {
  return (

      <Switch>
        <Route path="/info/1" component={ Info1 }/>
        <Route path="/info/2" component={ Info2 }/>
        <Route path="/info/3" component={ Info3 }/>
        <Route path="/info/4" component={ Info4 }/>
      </Switch>
      <Link to="/rings">
        <button className="back-info-btn">назад</button>
      </Link>
      <button onClick={ this.leftHandler.bind(this) } className="left-info-btn"></button>
      <button onClick={ this.rightHandler.bind(this)} className="right-info-btn"></button>

  )
}
```

<p>Then, wherever you render <code><Info /></code>, render <code><Router><Info /></Router></code> instead. Or, add an extra component that renders the two, and use that component instead of <code><Info /></code>.</p>

<pre class="lang-js prettyprint-override"><code>// Option 1: render <Router> wherever you use <Info>
import Info from './info';
...
ReactDOM.render(<Router><Info /></Router>);

// Option 2: add another component that wraps <Info> in a Router,
// either as the new export of the module, or as a new module
const App = () => (
  <Router>
    <Info />
  </Router>
);
export default App;
</code>```

Body:
I have a screen with buttons, common background and common title and changing nested components. Inside this screen I want to change nested components with a click of a button. Nested components must change each other in a circle with left and right button. So far I did a lots of attempts to achieve this ( I try to do it with withRouter), I give you code only of one of my attempts, but all of them didn't work. I don't get any errors, I see route in browser is changing but screen doesn't, I see only the first nested component. There is questions about this on SOF, but they related to older version of react-router.
Here my code, if you need more information feel free to ask in comments.

import React, { Component } from 'react';

import { Link,
         BrowserRouter as Router,
         Route,
         Switch,
         withRouter } from 'react-router-dom';

import Info1 from './info/info1';
import Info2 from './info/info2';
import Info3 from './info/info3';
import Info4 from './info/info4';

class Info extends Component {

   constructor(props) {
    super(props);

    this.currentIndex = 1;

  }

  componentDidMount() {

  }

  leftHandler() {
    console.log("left click");
    var temp = this.currentIndex;
    this.changeScreen(--temp);
  }

  rightHandler() {
    console.log("right click");
    var temp = this.currentIndex;
    this.changeScreen(++temp);
  }

  changeScreen(index) {

    const numberOfScreens = 4;

    if(index < 1)
        this.currentIndex = numberOfScreens;
    else if(index > numberOfScreens)
        this.currentIndex = 1;
    else
        this.currentIndex = index;
    this.props.history.push("/info/" + this.currentIndex);
  }

  render() {

    return (
      <Router>

           <Switch>
                 <Route path="/info/1" component={ Info1 }/>
                <Route path="/info/2" component={ Info2 }/>
                <Route path="/info/3" component={ Info3 }/>
                <Route path="/info/4" component={ Info4 }/>
            </Switch>
            <Link to="/rings"><button className="back-info-btn">назад</button></Link>
            <button onClick={ this.leftHandler.bind(this) } className="left-info-btn"></button>
            <button onClick={ this.rightHandler.bind(this)} className="right-info-btn"></button>

      </Router>
    );
  }

}

Info.propTypes = {
  history: React.PropTypes.shape({
    push: React.PropTypes.func.isRequired,
    }).isRequired,
  location: React.PropTypes.isRequired,
};

export default withRouter(Info);

EDIT:
While I accepted given answer, I didn't test it, in my project I used this solution:

app.js

import {
  BrowserRouter as Router,
  Route,
  Link
} from 'react-router-dom';

...

render() {

    return (

        <Router>

          <Route path="/info" component={ Info }/>

        </Router>

    );
  }

Then in Info itself:

Info.js

class Info extends Component {

   constructor(props) {
   super(props);

   this.currentIndex = 1;

  }

  leftHandler() {
    console.log("left click");
    var temp = this.currentIndex;
    this.changeScreen(--temp);
  }

  rightHandler() {
    console.log("right click");
    var temp = this.currentIndex;
    this.changeScreen(++temp);
  }

  changeScreen(index) {

    const numberOfScreens = 4;

    if(index < 1)
        this.currentIndex = numberOfScreens;
    else if(index > numberOfScreens)
        this.currentIndex = 1;
    else
        this.currentIndex = index;
    this.props.history.push("/info/" + this.currentIndex);
  }

  render() {

    return (

            <Switch>
                <Route path={`${this.props.match.path}/1`} component={ Info1 }/>
                <Route path={`${this.props.match.path}/2`} component={ Info2 }/>
                <Route path={`${this.props.match.path}/3`} component={ Info3 }/>
                <Route path={`${this.props.match.path}/4`} component={ Info4 }/>
            </Switch>
            <Link to="/rings"><button className="back-info-btn">назад</button></Link>
            <button onClick={ this.leftHandler.bind(this) } className="left-info-btn"></button>
            <button onClick={ this.rightHandler.bind(this)} className="right-info-btn"></button>

    );
  }

}

Info.propTypes = {
  history: React.PropTypes.shape({
    push: React.PropTypes.func.isRequired,
    }).isRequired,
  location: React.PropTypes.object.isRequired,
};

export default withRouter(Info);

Body:
If you wrap a component in withRouter, you can only use it inside a <Router>, just like <Route>s etc.

To get your example working, you need to make <Info> a child of <Router>, since it uses withRouter. First, remove the <Router> from the render method, and just render the <div> as the top-level component:

render() {
  return (
    <div className="info-common">
      <img className="game-title info-game"/>
      <Switch>
        <Route path="/info/1" component={ Info1 }/>
        <Route path="/info/2" component={ Info2 }/>
        <Route path="/info/3" component={ Info3 }/>
        <Route path="/info/4" component={ Info4 }/>
      </Switch>
      <Link to="/rings">
        <button className="back-info-btn">назад</button>
      </Link>
      <button onClick={ this.leftHandler.bind(this) } className="left-info-btn"></button>
      <button onClick={ this.rightHandler.bind(this)} className="right-info-btn"></button>
    </div>
  )
}

Then, wherever you render <Info />, render <Router><Info /></Router> instead. Or, add an extra component that renders the two, and use that component instead of <Info />.

// Option 1: render <Router> wherever you use <Info>
import Info from './info';
...
ReactDOM.render(<Router><Info /></Router>);

// Option 2: add another component that wraps <Info> in a Router,
// either as the new export of the module, or as a new module
const App = () => (
  <Router>
    <Info />
  </Router>
);
export default App;


来源: stackexchange

问:
std::variant store multiple string types and tell them apart
In C++17, I'm implementing a toy vm. I'm using a std::variant() as the elements of the VM's stack. I need to push strings onto the stack which represent different kinds of operands, namely:

a variable name

an identifier

a quoted string

All 3 types of operands can be of type std::string_view. The variant is defined like so:

```<code>std::variant<bool, int, double, std::string_view>;
</code>```

In order to discriminate about the actual type of string view, is the correct way to do something like this?

```<code>enum StringKind { Symbol, String, Var };
using Stringy = std::tuple<StringKind, std::string_view>; // SV can be symbol, var, string
std::variant<bool, int, double, Stringy>;
</code>```

Or is it possible to encode the string kind right at the variant. One of the benefits of doing it at the variant level is that the type can be had by calling std::variant::index(). Otherwise, I have to check for .index() == 3, std::get<3>(var), and then inspect the type to see if its string, symbol, or var.

答:
One alternative is to create a templated class to "tag" the various enum types. This avoids the need to have a "using" statement for each enum value so you repeat yourself less.

```<code>enum class StringKind { Symbol, String, Var };
template <StringKind T> struct TaggedString { std::string_view value; };
using StackType = std::variant<bool,
                               int,
                               double,
                               TaggedString<StringKind::Symbol>,
                               TaggedString<StringKind::String>,
                               TaggedString<StringKind::Var>>;
</code>```

Also, you mentioned using std::variant::index() to get the type contained in the variant. Another way to do this is to use std::visit() in the following way to be a bit more type safe:

```<code>#include <iostream>
#include <string_view>
#include <variant>

template<typename T> struct always_false : std::false_type { };
enum class StringKind { Symbol, String, Var };
template <StringKind T> struct TaggedString { std::string_view value; };
using StackType = std::variant<bool,
                               int,
                               double,
                               TaggedString<StringKind::Symbol>,
                               TaggedString<StringKind::String>,
                               TaggedString<StringKind::Var>>;

std::ostream& operator<<(std::ostream& stream, const StackType& st) {
    std::visit([&stream](auto&& var) {
        using T = std::decay_t<decltype(var)>;
        if constexpr (std::is_same_v<T, bool>) {
            stream << "Bool(" << var << ")";
        } else if constexpr (std::is_same_v<T, int>) {
            stream << "Int(" << var << ")";
        } else if constexpr (std::is_same_v<T, double>) {
            stream << "Double(" << var << ")";
        } else if constexpr (std::is_same_v<T, TaggedString<StringKind::Symbol>>) {
            stream << "Symbol(" << var.value << ")";
        } else if constexpr (std::is_same_v<T, TaggedString<StringKind::String>>) {
            stream << "String(" << var.value << ")";
        } else if constexpr (std::is_same_v<T, TaggedString<StringKind::Var>>) {
            stream << "Var(" << var.value << ")";
        } else {
            static_assert(always_false<T>::value, "non-exhaustive visitor!");
        }
    }, st);
    return stream;
}

int main(int, char**) {
    StackType t_bool   = true;
    StackType t_int    = 3;
    StackType t_double = 3.0;
    StackType t_symbol = TaggedString<StringKind::Symbol>{"Foo"};
    StackType t_string = TaggedString<StringKind::String>{"Bar"};
    StackType t_var    = TaggedString<StringKind::Var>{"Baz"};
    std::cout << t_bool   << std::endl
              << t_int    << std::endl
              << t_double << std::endl
              << t_symbol << std::endl
              << t_string << std::endl
              << t_var    << std::endl;
}
</code>```

This program outputs:

```<code>Bool(1)
Int(3)
Double(3)
Symbol(Foo)
String(Bar)
Var(Baz)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In C++17, I'm implementing a toy vm. I'm using a std::variant() as the elements of the VM's stack. I need to push strings onto the stack which represent different kinds of operands, namely:

a variable name

an identifier

a quoted string

All 3 types of operands can be of type std::string_view. The variant is defined like so:

std::variant<bool, int, double, std::string_view>;

In order to discriminate about the actual type of string view, is the correct way to do something like this?

enum StringKind { Symbol, String, Var };
using Stringy = std::tuple<StringKind, std::string_view>; // SV can be symbol, var, string
std::variant<bool, int, double, Stringy>;

Or is it possible to encode the string kind right at the variant. One of the benefits of doing it at the variant level is that the type can be had by calling std::variant::index(). Otherwise, I have to check for .index() == 3, std::get<3>(var), and then inspect the type to see if its string, symbol, or var.

Body:
One alternative is to create a templated class to "tag" the various enum types. This avoids the need to have a "using" statement for each enum value so you repeat yourself less.

enum class StringKind { Symbol, String, Var };
template <StringKind T> struct TaggedString { std::string_view value; };
using StackType = std::variant<bool,
                               int,
                               double,
                               TaggedString<StringKind::Symbol>,
                               TaggedString<StringKind::String>,
                               TaggedString<StringKind::Var>>;

Also, you mentioned using std::variant::index() to get the type contained in the variant. Another way to do this is to use std::visit() in the following way to be a bit more type safe:

#include <iostream>
#include <string_view>
#include <variant>

template<typename T> struct always_false : std::false_type { };
enum class StringKind { Symbol, String, Var };
template <StringKind T> struct TaggedString { std::string_view value; };
using StackType = std::variant<bool,
                               int,
                               double,
                               TaggedString<StringKind::Symbol>,
                               TaggedString<StringKind::String>,
                               TaggedString<StringKind::Var>>;

std::ostream& operator<<(std::ostream& stream, const StackType& st) {
    std::visit([&stream](auto&& var) {
        using T = std::decay_t<decltype(var)>;
        if constexpr (std::is_same_v<T, bool>) {
            stream << "Bool(" << var << ")";
        } else if constexpr (std::is_same_v<T, int>) {
            stream << "Int(" << var << ")";
        } else if constexpr (std::is_same_v<T, double>) {
            stream << "Double(" << var << ")";
        } else if constexpr (std::is_same_v<T, TaggedString<StringKind::Symbol>>) {
            stream << "Symbol(" << var.value << ")";
        } else if constexpr (std::is_same_v<T, TaggedString<StringKind::String>>) {
            stream << "String(" << var.value << ")";
        } else if constexpr (std::is_same_v<T, TaggedString<StringKind::Var>>) {
            stream << "Var(" << var.value << ")";
        } else {
            static_assert(always_false<T>::value, "non-exhaustive visitor!");
        }
    }, st);
    return stream;
}

int main(int, char**) {
    StackType t_bool   = true;
    StackType t_int    = 3;
    StackType t_double = 3.0;
    StackType t_symbol = TaggedString<StringKind::Symbol>{"Foo"};
    StackType t_string = TaggedString<StringKind::String>{"Bar"};
    StackType t_var    = TaggedString<StringKind::Var>{"Baz"};
    std::cout << t_bool   << std::endl
              << t_int    << std::endl
              << t_double << std::endl
              << t_symbol << std::endl
              << t_string << std::endl
              << t_var    << std::endl;
}

This program outputs:

Bool(1)
Int(3)
Double(3)
Symbol(Foo)
String(Bar)
Var(Baz)


问:
Page Load Wait and Keys codes
Can anyone tell me how to type text and press enter key in browser address bar in selenium webdriver? I am using C# bindings.

and

Please explain how can I make webdriver to wait untill the new webpage fully loaded in browser.

答:
Selenium cannot input the  URL in browser address bar, if you want to open a website, please use below code to open the page:</p>

```<code>driver=webdriver.Chrome()
driver.get("http://www.google.com")
</code>```

Title: Page Load Wait and Keys codes

Body:
Selenium cannot input the  URL in browser address bar, if you want to open a website, please use below code to open the page:

driver=webdriver.Chrome()
driver.get("http://www.google.com")


问:
Azure App service Role environment Failed to Initialize
there are multiple warnings in event viewer

```<code>  w3wp Role environment . INITIALIZING

  w3wp Role environment .INITIALED RETURNED. HResult=-2147024891

  w3wp Role environment . FAILED TO INITIALIZE. hr: -2147024891
</code>```

followed this and removed all references to WindowsAzure.Configuration and checked Remove All additional files during publishing but I still see these warnings in logs

答:
I suggest you could check the Web.Config for references to Microsoft.WindowsAzure.Diagnostics” or “Microsoft.WindowsAzure.ServiceRuntime.

Since these are designed for could services and not for the app services, so you will face these error.

Body:
there are multiple warnings in event viewer

  w3wp Role environment . INITIALIZING

  w3wp Role environment .INITIALED RETURNED. HResult=-2147024891

  w3wp Role environment . FAILED TO INITIALIZE. hr: -2147024891

followed this and removed all references to WindowsAzure.Configuration and checked Remove All additional files during publishing but I still see these warnings in logs


问:
Matlab: confusion in generating binary numbers with a specific probability distribution
I want to obtain an array of binary numbers of length say N=10 where the probability of 0 = 0.6 and probability of 1's is 0.4. But, during validating if actually the probability is correct, I am getting incorrect probability values. So, symbols is an array of 0/1 integers generated. Then I am checking if the probability is correct or not using p_1 = sum(symbols==1)/length(symbols) .Where am I going wrong?

```<code>    N =10;
    p_0 = 0.6;% probability of zeros
  *for n = 1:N
         xr=rand;
         if xr<p_0
             symbols(n)=1;
         else
             symbols(n)=0;
         end
end

        p_1 = sum(symbols==1)/length(symbols)
        p_0 = 1-p_1*
</code>```

答:
If you want to test if the probability is correct, generate an array with a million values. Out of 10 random values, it is impossible to know that the underlying probabilities are.

Note that you can do what you are doing without a loop:

```<code>symbols = rand(N,1) > p_0;
</code>```

(This generates a logical array, +symbols would be a numeric array.)

Body:
I want to obtain an array of binary numbers of length say N=10 where the probability of 0 = 0.6 and probability of 1's is 0.4. But, during validating if actually the probability is correct, I am getting incorrect probability values. So, symbols is an array of 0/1 integers generated. Then I am checking if the probability is correct or not using p_1 = sum(symbols==1)/length(symbols) .Where am I going wrong?

    N =10;
    p_0 = 0.6;% probability of zeros
  *for n = 1:N
         xr=rand;
         if xr<p_0
             symbols(n)=1;
         else
             symbols(n)=0;
         end
end

        p_1 = sum(symbols==1)/length(symbols)
        p_0 = 1-p_1*

Body:
If you want to test if the probability is correct, generate an array with a million values. Out of 10 random values, it is impossible to know that the underlying probabilities are.

Note that you can do what you are doing without a loop:

symbols = rand(N,1) > p_0;

(This generates a logical array, +symbols would be a numeric array.)


问:
How do I call a visual basic 6.0 method in c#?
I would like to call a method which is written in visual basic 6.0 from c# (visual studio 2008). Is it possible?  How would I do it?</p>

答: Yes.  It is possible.  You call it just like you call a method which has been written in Visual Basic.  You need a reference to the assembly and then you just call it with the right namespace.</p>

ContentLicense: CC BY-SA 2.5


问:
What is the best way to check if a variable is a list?
I found this 3 ways to check it, but I don't know which of them is the best:

```<code>x = ['Bla', 'Bla', 'Bla', 'etc']

if isinstance(a, list): print('Perfect!')
if type(a) is list:     print('Incredible!')
if type(a) == type([]): print('Awesome!')
</code>```

Which of these is better?

Also, Can I use these ways to check whether an x is a string, tuple, dictionary, int, float, etc? If this is possible, in the first two methods do I have to convert a list to a tuple, string, dictionary, int, float, etc (no?), but in the third? I have to use (), {}, '', and what more for int and float?

答:
Do you need to know if it's a list, or just if it's iterable (if you can use it in a for loop, for example)? Generally the "Pythonic way" is to just go ahead and do it in a try-except, because many things can be iterable: strings, lists, sets, deques, custom types, etc. (All it takes is an __iter__ or __getitem__ method)

If you REALLY need to know what type it is, isinstance() is typically the way to go since it will also cover subclasses.

As far as using type() == something is concerned, int, float, list, etc are all types: type(1) == int is True.

My typical approach, where I might have a string, a list (or tuple, etc.) of strings, or an int or other object which can be converted to a string, would be this (for Python 2 - Py3 no longer has basestring so you'll need to check for str and/or bytes), assuming foo is your variable:

```<code>if isinstance(foo, basestring):
    foo = (foo,) # turn it into an iterable (tuple)
    # or, doStuff(foo) followed by a return or break
try:
    for x in foo:
        doStuff(str(x)) # do something with each element
except TypeError: # TypeError: 'some' object is not iterable
    doStuff(str(foo))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I found this 3 ways to check it, but I don't know which of them is the best:

x = ['Bla', 'Bla', 'Bla', 'etc']

if isinstance(a, list): print('Perfect!')
if type(a) is list:     print('Incredible!')
if type(a) == type([]): print('Awesome!')

Which of these is better?

Also, Can I use these ways to check whether an x is a string, tuple, dictionary, int, float, etc? If this is possible, in the first two methods do I have to convert a list to a tuple, string, dictionary, int, float, etc (no?), but in the third? I have to use (), {}, '', and what more for int and float?

Body:
Do you need to know if it's a list, or just if it's iterable (if you can use it in a for loop, for example)? Generally the "Pythonic way" is to just go ahead and do it in a try-except, because many things can be iterable: strings, lists, sets, deques, custom types, etc. (All it takes is an __iter__ or __getitem__ method)

If you REALLY need to know what type it is, isinstance() is typically the way to go since it will also cover subclasses.

As far as using type() == something is concerned, int, float, list, etc are all types: type(1) == int is True.

My typical approach, where I might have a string, a list (or tuple, etc.) of strings, or an int or other object which can be converted to a string, would be this (for Python 2 - Py3 no longer has basestring so you'll need to check for str and/or bytes), assuming foo is your variable:

if isinstance(foo, basestring):
    foo = (foo,) # turn it into an iterable (tuple)
    # or, doStuff(foo) followed by a return or break
try:
    for x in foo:
        doStuff(str(x)) # do something with each element
except TypeError: # TypeError: 'some' object is not iterable
    doStuff(str(foo))


问:
How do I change sublime text default PHP comment format to blade laravel's comment format?
The normal comment syntax in Sublime for PHP is ```// comment goes here``` or ```/* comment goes here */```

However, in blade templating, the format is ```{{-- comment goes here --}}```

The default shortcut key in sublime text is CTRL + / and CTRL + SHIFT + / respectively.

I was wondering how I would wire blade's commenting format to sublime's default shortcut commenting key.

Any help would be appreciated!

PS: I am using the Laravel Blade Highlighter package for sublime text 3 on Ubuntu Linux.

答: Press Ctrl + Shift + P and search for "laravel blade" and Set Sintax: Laravel Blade.</p>

Body:
The normal comment syntax in Sublime for PHP is
// comment goes here
 or
/* comment goes here */

However, in blade templating, the format is
{{-- comment goes here --}}

The default shortcut key in sublime text is CTRL + / and CTRL + SHIFT + / respectively.

I was wondering how I would wire blade's commenting format to sublime's default shortcut commenting key.

Any help would be appreciated!

PS: I am using the Laravel Blade Highlighter package for sublime text 3 on Ubuntu Linux.


问:
How to vertically align text with icon font?
I have a very basic HTML which mix plain text and icon fonts.
The problem is that icons are not exactly rendered at the same height than the text:

   Accueil
   Créations
  Qui-suis je

```

Any suggestion to fix it?

答:
Adding to the spans

```<code>vertical-align:baseline;
</code>```

Didn't work for me but

```<code>vertical-align:baseline;
vertical-align:-webkit-baseline-middle;
</code>```

did work (tested on Chrome)

Body:
I have a very basic HTML which mix plain text and icon fonts.
The problem is that icons are not exactly rendered at the same height than the text:

   Accueil
   Créations
  Qui-suis je

Any suggestion to fix it?

Body:
Adding to the spans

vertical-align:baseline;

Didn't work for me but

vertical-align:baseline;
vertical-align:-webkit-baseline-middle;

did work (tested on Chrome)


问:
ASP.net MVC razor checkbox for select and insert of role-permission
I am really lost on this as to how I am going to present and submit the data

I have the following database table

role table

```<code>role_id (pk)
role_name
</code>```

permission table

```<code>permission_id (pk)
permission
</code>```

role_permission table:

```<code>role_permission_id (pk)
role_id (fk from role table)
perm_id (fk from permission table)
edit_perm (bit)
view_perm (bit)
</code>```

And based on the table, I have created the below view.

```<code>@using (Html.BeginForm("Update", "RolePermission", FormMethod.Post))
{
<div>
    <table border="1">
        <tr>
            <th colspan="2">RoleName</th>

            @if (Model.ListOfPermission.Count > 0)
            {
                foreach (var permitem in Model.ListOfPermission)
                {
                    <th>@permitem.permission</th>
                }
            }
        </tr>
        @if (Model.ListOfRoles.Count > 0)
        {
            foreach (var roleitem in Model.ListOfRoles)
            {
                <tr>
                    <th rowspan="2">@roleitem.role_name</th>
                    <td>Edit</td>
                    @if (Model.ListOfPermission.Count > 0)
                    {
                        foreach (var permitem in Model.ListOfPermission)
                        {
                            <td>@Html.CheckBox("EditCheckBox")</td>
                        }
                    }
                </tr>
                <tr>
                    <td>View</td>
                    @if (Model.ListOfPermission.Count > 0)
                    {
                        foreach (var permitem in Model.ListOfPermission)
                        {
                            <td>@Html.CheckBox("ViewCheckBox")</td>
                        }
                    }
                </tr>
            }
        }
    </table>
    <div>
        <button id="SaveBtn" type="submit">Save</button>
    </div>
</div>
}
</code>```

and my model so far as below:

```<code>public class RolePermissionModel
{
    public List <tblRole> ListOfRoles { get; set; }
    public List <tblPermission> ListOfPermission { get; set; }
}
</code>```

The above view gives the table format as the picture attached.

Sorry, I don't have enough reputation

My goal is to have check box checked depending on the role-permission table. above. For instance, if role-permission table has:

```<code>role_id: 1 -> (IT Admin role_id)
perm_id: 1 -> (Create User Permission)
edit_perm: 0
view_perm: 1
</code>```

I need check checked on view sub-row of IT Admin row and Create User permission column.

Also, upon user clicking the checkbox and submit, I need to do insert.

The trouble here is, how do I pass the data from controller to view and how do I pass the view to controller to achieve that?

I am guessing I have to send the checkbox value along with column/row matching value to the controller on insert, but I have no idea how to achieve it. (Do I use jquery to get values of cell column value and row value?)

As for showing the checked value, I have no idea.

Your help will greatly be appreciated.

答:
Here is the result for those who may need.

Edit: Edited when there is record initially.

Model:

```<code>public class RolePermissionModel
{
    public List<tblRole> ListOfRoles { get; set; }
    public List<tblPermission> ListOfPermission { get; set; }
    public List<tblRole_Permission> RolePermStatus { get; set; }
    public List<ColumnEditCheckBoxList> RowEditCheckBox { get; set; }
    public List<ColumnViewCheckBoxList> RowViewCheckBox { get; set; }
}

public class ColumnEditCheckBoxList
{
    public List<EditCheckBoxElement> ColEditCheckBox { get; set; }
}

public class ColumnViewCheckBoxList
{
    public List<ViewCheckBoxElement> ColViewCheckBox { get; set; }
}

public class EditCheckBoxElement
{
    public bool IsEditChecked { get; set; }
}

public class ViewCheckBoxElement
{
    public bool IsViewChecked { get; set; }
}
</code>```

View:

```<code>@model RoadTex_MVC_Project.Models.RolePermission_Model.RolePermissionModel
@{
    ViewBag.Title = "RolePermission";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>ViewBag.Title</h2>
@using (Html.BeginForm("RolePermission", "RolePermission", FormMethod.Post))
{
    <div>
        <table border="1">
            <tr>
                <th colspan="2">RoleName</th>
                @if (Model.ListOfPermission.Count > 0)
                {
                    for (int i = 0; i< Model.ListOfPermission.Count; i++)
                    {
                        <th>@Model.ListOfPermission[i].permission</th>
                    }
                }
            </tr>
            @if (Model.ListOfRoles.Count > 0)
            {
                for (int i = 0; i < Model.ListOfRoles.Count; i++)
                {
                    <tr>
                        <th rowspan="2">@Model.ListOfRoles[i].role_name</th>
                        <th>Edit</th>
                        @if (Model.ListOfPermission.Count > 0)
                        {
                            for (int j=0; j < Model.ListOfPermission.Count; j++)
                            {
                                <td rowspan="2">
                                    @Html.HiddenFor(e => e.ListOfRoles[i].role_id)
                                    @Html.HiddenFor(e => e.ListOfPermission[j].perm_id)
                                    @Html.CheckBoxFor(e => e.RowEditCheckBox[i].ColEditCheckBox[j].IsEditChecked)
                                    <br />
                                    @Html.CheckBoxFor(e => e.RowViewCheckBox[i].ColViewCheckBox[j].IsViewChecked)
                                </td>
                            }
                        }
                    </tr>
                    <tr>
                        <th>View</th>
                    </tr>
                }
            }
        </table>
        <div>
            <button id="SaveBtn" type="submit">Save</button>
        </div>
    </div>
}
</code>```

Controller:

```<code>public class RolePermissionController : Controller
{
    private static RoadTex_MVC_Model_Local DB;

    [NonAction]
    private RoadTex_MVC_Model_Local Connect()
    {
        DB = new RoadTex_MVC_Model_Local();
        return DB;
    }

    [NonAction]
    private void PopulateModel(RolePermissionModel Model)
    {
        using (Connect())
        {
            Model.ListOfRoles = DB.tblRoles.ToList();
            Model.ListOfPermission = DB.tblPermissions.ToList();
            Model.RolePermStatus = DB.tblRole_Permission.ToList();
        }
    }

    [NonAction]
    private void UpdateCheckBox(RolePermissionModel Model)
    {
        using (Connect())
        {
            for (int i = 0; i < Model.ListOfRoles.Count; i++)
            {
                for (int j = 0; j < Model.ListOfPermission.Count; j++)
                {
                    tblRole_Permission RolePermission = new tblRole_Permission
                    {
                        role_id = Model.ListOfRoles[i].role_id,
                        perm_id = Model.ListOfPermission[j].perm_id,
                        edit_perm = Model.RowEditCheckBox[i].ColEditCheckBox[j].IsEditChecked,
                        view_perm = Model.RowViewCheckBox[i].ColViewCheckBox[j].IsViewChecked
                    };
                    DB.tblRole_Permission.AddOrUpdate(e => new { e.role_id, e.perm_id }, RolePermission);
                }
            }
            DB.SaveChanges();
        }
    }
    [NonAction]
    private void GenerateCheckBox(RolePermissionModel Model)
    {
        using (Connect())
        {
            for (int i = 0; i < Model.ListOfRoles.Count; i++)
            {
                for (int j = 0; j < Model.ListOfPermission.Count; j++)
                {
                    var temp_role = Model.ListOfRoles[i].role_id;
                    var temp_perm = Model.ListOfPermission[j].perm_id;
                    tblRole_Permission RolePermission = new tblRole_Permission
                    {
                        role_id = temp_role,
                        perm_id = temp_perm,
                        edit_perm = false,
                        view_perm = false
                    };
                    if (!DB.tblRole_Permission.Where(e => e.role_id == temp_role
                    && e.perm_id == temp_perm).Any())
                    {
                        DB.tblRole_Permission.Add(RolePermission);
                    }
                }
            }
            DB.SaveChanges();
            Model.RolePermStatus = DB.tblRole_Permission.ToList();
        }
    }

    [NonAction]
    private void ShowCheckBox(RolePermissionModel Model)
    {
        Model.RowEditCheckBox = new List<ColumnEditCheckBoxList>();
        Model.RowViewCheckBox = new List<ColumnViewCheckBoxList>();
        int k = 0;
        for (int i = 0; i < Model.ListOfRoles.Count; i++)
        {
            ColumnEditCheckBoxList ColEditList = new ColumnEditCheckBoxList()
            {
                ColEditCheckBox = new List<EditCheckBoxElement>()
            };
            ColumnViewCheckBoxList ColViewList = new ColumnViewCheckBoxList()
            {
                ColViewCheckBox = new List<ViewCheckBoxElement>()
            };
            for (int j = 0; j < Model.ListOfPermission.Count; j++)
            {
                EditCheckBoxElement EditEl = new EditCheckBoxElement();
                ViewCheckBoxElement ViewEl = new ViewCheckBoxElement();
                EditEl.IsEditChecked = Model.RolePermStatus[k].edit_perm;
                ViewEl.IsViewChecked = Model.RolePermStatus[k].view_perm;
                k++;
                ColEditList.ColEditCheckBox.Add(EditEl);
                ColViewList.ColViewCheckBox.Add(ViewEl);
            }
            Model.RowEditCheckBox.Add(ColEditList);
            Model.RowViewCheckBox.Add(ColViewList);
        }
    }

    [HttpGet]
    public ActionResult RolePermission()
    {
        //if (Session["UserName"] == null)
        //{
        //    return RedirectToAction("Login", "Home");
        //}
        RolePermissionModel Model = new RolePermissionModel();
        PopulateModel(Model);
        GenerateCheckBox(Model);
        ShowCheckBox(Model);
        return View("RolePermission", Model);
    }

    [HttpPost]
    public ActionResult RolePermission(RolePermissionModel Model)
    {
        UpdateCheckBox(Model);
        return RedirectToAction("RolePermission");
    }
}
</code>```

Performance is really bad because controller is looping through number of times in order to achieve desired result.

Using sql stored procedure (possibly using pivot) and putting into webgrid will be much simpler and better for the performance.

Body:
I am really lost on this as to how I am going to present and submit the data

I have the following database table

role table

role_id (pk)
role_name

permission table

permission_id (pk)
permission

role_permission table:

role_permission_id (pk)
role_id (fk from role table)
perm_id (fk from permission table)
edit_perm (bit)
view_perm (bit)

And based on the table, I have created the below view.

@using (Html.BeginForm("Update", "RolePermission", FormMethod.Post))
{

            RoleName

            @if (Model.ListOfPermission.Count > 0)
            {
                foreach (var permitem in Model.ListOfPermission)
                {
                    @permitem.permission
                }
            }

        @if (Model.ListOfRoles.Count > 0)
        {
            foreach (var roleitem in Model.ListOfRoles)
            {

                    @roleitem.role_name
                    Edit
                    @if (Model.ListOfPermission.Count > 0)
                    {
                        foreach (var permitem in Model.ListOfPermission)
                        {
                            @Html.CheckBox("EditCheckBox")
                        }
                    }

                    View
                    @if (Model.ListOfPermission.Count > 0)
                    {
                        foreach (var permitem in Model.ListOfPermission)
                        {
                            @Html.CheckBox("ViewCheckBox")
                        }
                    }

            }
        }

        <button id="SaveBtn" type="submit">Save</button>

}

and my model so far as below:

public class RolePermissionModel
{
    public List <tblRole> ListOfRoles { get; set; }
    public List <tblPermission> ListOfPermission { get; set; }
}

The above view gives the table format as the picture attached.

Sorry, I don't have enough reputation

My goal is to have check box checked depending on the role-permission table. above. For instance, if role-permission table has:

role_id: 1 -> (IT Admin role_id)
perm_id: 1 -> (Create User Permission)
edit_perm: 0
view_perm: 1

I need check checked on view sub-row of IT Admin row and Create User permission column.

Also, upon user clicking the checkbox and submit, I need to do insert.

The trouble here is, how do I pass the data from controller to view and how do I pass the view to controller to achieve that?

I am guessing I have to send the checkbox value along with column/row matching value to the controller on insert, but I have no idea how to achieve it. (Do I use jquery to get values of cell column value and row value?)

As for showing the checked value, I have no idea.

Your help will greatly be appreciated.

Body:
Here is the result for those who may need.

Edit: Edited when there is record initially.

Model:

public class RolePermissionModel
{
    public List<tblRole> ListOfRoles { get; set; }
    public List<tblPermission> ListOfPermission { get; set; }
    public List<tblRole_Permission> RolePermStatus { get; set; }
    public List<ColumnEditCheckBoxList> RowEditCheckBox { get; set; }
    public List<ColumnViewCheckBoxList> RowViewCheckBox { get; set; }
}

public class ColumnEditCheckBoxList
{
    public List<EditCheckBoxElement> ColEditCheckBox { get; set; }
}

public class ColumnViewCheckBoxList
{
    public List<ViewCheckBoxElement> ColViewCheckBox { get; set; }
}

public class EditCheckBoxElement
{
    public bool IsEditChecked { get; set; }
}

public class ViewCheckBoxElement
{
    public bool IsViewChecked { get; set; }
}

View:

@model RoadTex_MVC_Project.Models.RolePermission_Model.RolePermissionModel
@{
    ViewBag.Title = "RolePermission";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>ViewBag.Title</h2>
@using (Html.BeginForm("RolePermission", "RolePermission", FormMethod.Post))
{
    <div>
        <table border="1">
            <tr>
                <th colspan="2">RoleName</th>
                @if (Model.ListOfPermission.Count > 0)
                {
                    for (int i = 0; i< Model.ListOfPermission.Count; i++)
                    {
                        <th>@Model.ListOfPermission[i].permission</th>
                    }
                }
            </tr>
            @if (Model.ListOfRoles.Count > 0)
            {
                for (int i = 0; i < Model.ListOfRoles.Count; i++)
                {
                    <tr>
                        <th rowspan="2">@Model.ListOfRoles[i].role_name</th>
                        <th>Edit</th>
                        @if (Model.ListOfPermission.Count > 0)
                        {
                            for (int j=0; j < Model.ListOfPermission.Count; j++)
                            {
                                <td rowspan="2">
                                    @Html.HiddenFor(e => e.ListOfRoles[i].role_id)
                                    @Html.HiddenFor(e => e.ListOfPermission[j].perm_id)
                                    @Html.CheckBoxFor(e => e.RowEditCheckBox[i].ColEditCheckBox[j].IsEditChecked)
                                    <br />
                                    @Html.CheckBoxFor(e => e.RowViewCheckBox[i].ColViewCheckBox[j].IsViewChecked)
                                </td>
                            }
                        }
                    </tr>
                    <tr>
                        <th>View</th>
                    </tr>
                }
            }
        </table>
        <div>
            <button id="SaveBtn" type="submit">Save</button>
        </div>
    </div>
}

Controller:

public class RolePermissionController : Controller
{
    private static RoadTex_MVC_Model_Local DB;

    [NonAction]
    private RoadTex_MVC_Model_Local Connect()
    {
        DB = new RoadTex_MVC_Model_Local();
        return DB;
    }

    [NonAction]
    private void PopulateModel(RolePermissionModel Model)
    {
        using (Connect())
        {
            Model.ListOfRoles = DB.tblRoles.ToList();
            Model.ListOfPermission = DB.tblPermissions.ToList();
            Model.RolePermStatus = DB.tblRole_Permission.ToList();
        }
    }

    [NonAction]
    private void UpdateCheckBox(RolePermissionModel Model)
    {
        using (Connect())
        {
            for (int i = 0; i < Model.ListOfRoles.Count; i++)
            {
                for (int j = 0; j < Model.ListOfPermission.Count; j++)
                {
                    tblRole_Permission RolePermission = new tblRole_Permission
                    {
                        role_id = Model.ListOfRoles[i].role_id,
                        perm_id = Model.ListOfPermission[j].perm_id,
                        edit_perm = Model.RowEditCheckBox[i].ColEditCheckBox[j].IsEditChecked,
                        view_perm = Model.RowViewCheckBox[i].ColViewCheckBox[j].IsViewChecked
                    };
                    DB.tblRole_Permission.AddOrUpdate(e => new { e.role_id, e.perm_id }, RolePermission);
                }
            }
            DB.SaveChanges();
        }
    }
    [NonAction]
    private void GenerateCheckBox(RolePermissionModel Model)
    {
        using (Connect())
        {
            for (int i = 0; i < Model.ListOfRoles.Count; i++)
            {
                for (int j = 0; j < Model.ListOfPermission.Count; j++)
                {
                    var temp_role = Model.ListOfRoles[i].role_id;
                    var temp_perm = Model.ListOfPermission[j].perm_id;
                    tblRole_Permission RolePermission = new tblRole_Permission
                    {
                        role_id = temp_role,
                        perm_id = temp_perm,
                        edit_perm = false,
                        view_perm = false
                    };
                    if (!DB.tblRole_Permission.Where(e => e.role_id == temp_role
                    && e.perm_id == temp_perm).Any())
                    {
                        DB.tblRole_Permission.Add(RolePermission);
                    }
                }
            }
            DB.SaveChanges();
            Model.RolePermStatus = DB.tblRole_Permission.ToList();
        }
    }

    [NonAction]
    private void ShowCheckBox(RolePermissionModel Model)
    {
        Model.RowEditCheckBox = new List<ColumnEditCheckBoxList>();
        Model.RowViewCheckBox = new List<ColumnViewCheckBoxList>();
        int k = 0;
        for (int i = 0; i < Model.ListOfRoles.Count; i++)
        {
            ColumnEditCheckBoxList ColEditList = new ColumnEditCheckBoxList()
            {
                ColEditCheckBox = new List<EditCheckBoxElement>()
            };
            ColumnViewCheckBoxList ColViewList = new ColumnViewCheckBoxList()
            {
                ColViewCheckBox = new List<ViewCheckBoxElement>()
            };
            for (int j = 0; j < Model.ListOfPermission.Count; j++)
            {
                EditCheckBoxElement EditEl = new EditCheckBoxElement();
                ViewCheckBoxElement ViewEl = new ViewCheckBoxElement();
                EditEl.IsEditChecked = Model.RolePermStatus[k].edit_perm;
                ViewEl.IsViewChecked = Model.RolePermStatus[k].view_perm;
                k++;
                ColEditList.ColEditCheckBox.Add(EditEl);
                ColViewList.ColViewCheckBox.Add(ViewEl);
            }
            Model.RowEditCheckBox.Add(ColEditList);
            Model.RowViewCheckBox.Add(ColViewList);
        }
    }

    [HttpGet]
    public ActionResult RolePermission()
    {
        //if (Session["UserName"] == null)
        //{
        //    return RedirectToAction("Login", "Home");
        //}
        RolePermissionModel Model = new RolePermissionModel();
        PopulateModel(Model);
        GenerateCheckBox(Model);
        ShowCheckBox(Model);
        return View("RolePermission", Model);
    }

    [HttpPost]
    public ActionResult RolePermission(RolePermissionModel Model)
    {
        UpdateCheckBox(Model);
        return RedirectToAction("RolePermission");
    }
}

Performance is really bad because controller is looping through number of times in order to achieve desired result.

Using sql stored procedure (possibly using pivot) and putting into webgrid will be much simpler and better for the performance.


问:
Inserting the first cell into a collection view causes an assertion failure
If I try to insert an item into a UICollectionView when there are 0 sections and 0 items, I get an assertion failure.

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid
  number of sections. The number of sections contained in the collection
  view after the update (1) must be equal to the number of sections
  contained in the collection view before the update (0), plus or minus
  the number of sections inserted or deleted (0 inserted, 0 deleted).'

A classic. The problem is, I'm modifying my data source and then inserting the item directly afterwards. The showFirstCell property is checked in all of the necessary data source methods and it isn't modified anywhere else.

```<code>self.showFirstCell = true
self.collectionView.insertItemsAtIndexPaths([NSIndexPath(forItem: 0, inSection: 0)])
</code>```

Wrapping this in performBatchUpdates changes nothing.

I would like for this item to be added in an animated fashion. I don't think I should have to first check if there are items already in place, but doing so and calling reloadData instead does work, but it's not perfect.

答:
If you want to insert item from your CollectionView, you need to
  insert that item from your data source which is in your array. In this example I inserted the item to myArray
  then I inserted it also to myCollectionView. It's working because
  the total number of items from your array (data source) is equal to
  the number of items in the collectionView.

```<code>myArray.insert(valuetoinsert, atIndex: 0)
let path:NSIndexPath = NSIndexPath.init(row: 0, section: 0)
myCollectionView.insertItems(at: [path as IndexPath])
</code>```

Body:
If I try to insert an item into a UICollectionView when there are 0 sections and 0 items, I get an assertion failure.

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid
  number of sections. The number of sections contained in the collection
  view after the update (1) must be equal to the number of sections
  contained in the collection view before the update (0), plus or minus
  the number of sections inserted or deleted (0 inserted, 0 deleted).'

A classic. The problem is, I'm modifying my data source and then inserting the item directly afterwards. The showFirstCell property is checked in all of the necessary data source methods and it isn't modified anywhere else.

self.showFirstCell = true
self.collectionView.insertItemsAtIndexPaths([NSIndexPath(forItem: 0, inSection: 0)])

Wrapping this in performBatchUpdates changes nothing.

I would like for this item to be added in an animated fashion. I don't think I should have to first check if there are items already in place, but doing so and calling reloadData instead does work, but it's not perfect.

Body:
If you want to insert item from your CollectionView, you need to
  insert that item from your data source which is in your array. In this example I inserted the item to myArray
  then I inserted it also to myCollectionView. It's working because
  the total number of items from your array (data source) is equal to
  the number of items in the collectionView.

myArray.insert(valuetoinsert, atIndex: 0)
let path:NSIndexPath = NSIndexPath.init(row: 0, section: 0)
myCollectionView.insertItems(at: [path as IndexPath])


问:
Is adding an Enum value a breaking change for GraphQL?
According to the GraphQL Best Practices, a GraphQL service should follow the "common practice of always avoiding breaking changes and serving a versionless API."

Is adding a value to an Enum considered a breaking change that should be avoided if following the Best Practices?

To illustrate this, let's say that the schema has this enum:

```<code>enum Episode {
  NEWHOPE
  EMPIRE
  JEDI
}
</code>```

Is it bad practice to evolve the enum to be this sometime in the future:

```<code>enum Episode {
  NEWHOPE
  EMPIRE
  JEDI
  FORCEAWAKENS
  ROGUEONE
}
</code>```

答:
Specifically, breaking changes are changes to schema structure that would cause already-written queries to fail. I couldn't find an exhaustive list online, but here are few example breaking changes:

Removing a field from an Object type (queries which used that field would become invalid)

Adding a required argument to a field (queries which used the field without that argument would become invalid)

Changing the return type of a field when the new type is not a supertype of the old type (eg, changing from Int to String, clients which used that field may have type errors from the new response).

It's possible that a new enum value could break a client (if it didn't have code to handle the new case, it may have a runtime error), but I think that's a client design issue, but not a breaking change to the schema!

Body:
According to the GraphQL Best Practices, a GraphQL service should follow the "common practice of always avoiding breaking changes and serving a versionless API."

Is adding a value to an Enum considered a breaking change that should be avoided if following the Best Practices?

To illustrate this, let's say that the schema has this enum:

enum Episode {
  NEWHOPE
  EMPIRE
  JEDI
}

Is it bad practice to evolve the enum to be this sometime in the future:

enum Episode {
  NEWHOPE
  EMPIRE
  JEDI
  FORCEAWAKENS
  ROGUEONE
}


问:
Getting every possible permutation in a format python
I'm trying to program a way to generate all possible combinations in this format:

```<code>01-01-01-A
</code>```

Now I've already looked in the itertools.permutations and combinations libs and read examples of how they worked. Though my problem is different than the other questions I've read

the first range can go from 0-38 and the next 2 ranges can go from 0-9 and the letter can go from A-C. I'm currently stuck on how I can use itertools to generate all possible combinations using this format.

What I am currently thinking is having 1 list with 4 lists inside with each of those numbers:

```<code>first_value = []
second_value = []
third_value = []
fourth_value = ["A", "B", "C"]
final_value = []
for num in range(0, 39):
    first_value.append(num)
for num in range(0, 10):
    second_value.append(num)
    third_value.append(num)
final_value.append(first_value)
final_value.append(second_value)
final_value.append(third_value)
final_value.append(fourth_value)
for value in itertools.permutations(final_value):
    print(value)
</code>```

I'm not really sure how I can program this.

答:
You want itertools.product.</p>

```<code>import itertools

map(lambda t: "-".join(t),
    itertools.product(
        map(str, range(0,39)),
        map(str, range(0,10)),
        map(str, range(0,10)),
        ['A', 'B', 'C'])
    )
</code>```

Body:
I'm trying to program a way to generate all possible combinations in this format:

01-01-01-A

Now I've already looked in the itertools.permutations and combinations libs and read examples of how they worked. Though my problem is different than the other questions I've read

the first range can go from 0-38 and the next 2 ranges can go from 0-9 and the letter can go from A-C. I'm currently stuck on how I can use itertools to generate all possible combinations using this format.

What I am currently thinking is having 1 list with 4 lists inside with each of those numbers:

first_value = []
second_value = []
third_value = []
fourth_value = ["A", "B", "C"]
final_value = []
for num in range(0, 39):
    first_value.append(num)
for num in range(0, 10):
    second_value.append(num)
    third_value.append(num)
final_value.append(first_value)
final_value.append(second_value)
final_value.append(third_value)
final_value.append(fourth_value)
for value in itertools.permutations(final_value):
    print(value)

I'm not really sure how I can program this.

Body:
You want itertools.product.

import itertools

map(lambda t: "-".join(t),
    itertools.product(
        map(str, range(0,39)),
        map(str, range(0,10)),
        map(str, range(0,10)),
        ['A', 'B', 'C'])
    )


问:
Select sum and group by SQLITE
I have a sqlite table with 4 fields (id, name, role, points) i want the sum of field points WHERE role = 'something' AND name = 'something'

My query does not work correctly:

```<code>select id,name,role, points (select sum(points)
from salvataggi_punti_giocatori where role = 'por')
as total from salvataggi_punti_giocatori
</code>```

答:
You have to group the columns first in order to perform aggregate functions</p>

```<code>SELECT  sum(points)
  FROM  salvataggi_punti_giocatori
  WHERE role = 'value'
  AND   name = 'value'
  GROUP BY role, name
</code>```

Title: Select sum and group by SQLITE

Body:
I have a sqlite table with 4 fields (id, name, role, points) i want the sum of field points WHERE role = 'something' AND name = 'something'

My query does not work correctly:

select id,name,role, points (select sum(points)
from salvataggi_punti_giocatori where role = 'por')
as total from salvataggi_punti_giocatori

Body:
You have to group the columns first in order to perform aggregate functions

SELECT  sum(points)
  FROM  salvataggi_punti_giocatori
  WHERE role = 'value'
  AND   name = 'value'
  GROUP BY role, name


问:
MySQL Not Starting on Mac Even Though it is Installed Using Brew
In Apple Preferences I can see the MySQL icon. when I click on it it says it cannot be started.

On the terminal I can see that MySQL is already installed using brew:

```<code>mysql --version
mysql  Ver 14.14 Distrib 5.7.17, for osx10.11 (x86_64) using  EditLine wrapper
</code>```

Any ideas why I cannot start mysql server?

when I try to jump into the mysql prompt from Mac terminal I get the following:

```<code>sudo mysql -u root
Password:
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
</code>```

UPDATE:

```<code>mysql
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
Jason-MacBook-Pro:fe$ mysql -uroot
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
</code>```

答:
Try running the command which mysql on command prompt, it will o/p like something. /usr/local/mysql/bin/mysql. then confirm that no existing mysql process is running by using ps aux | grep mysql command. then if no process if running, start mysql from command line with below command :-

```<code>/usr/local/mysql/bin/mysqld
</code>```

After that again confirm with command ps aux | grep mysql and mac preference setting, mysql should be up and running.

Let me know if it doesn't work.

Body:
In Apple Preferences I can see the MySQL icon. when I click on it it says it cannot be started.

On the terminal I can see that MySQL is already installed using brew:

mysql --version
mysql  Ver 14.14 Distrib 5.7.17, for osx10.11 (x86_64) using  EditLine wrapper

Any ideas why I cannot start mysql server?

when I try to jump into the mysql prompt from Mac terminal I get the following:

sudo mysql -u root
Password:
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

UPDATE:

mysql
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
Jason-MacBook-Pro:fe$ mysql -uroot
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

Body:
Try running the command which mysql on command prompt, it will o/p like something. /usr/local/mysql/bin/mysql. then confirm that no existing mysql process is running by using ps aux | grep mysql command. then if no process if running, start mysql from command line with below command :-

/usr/local/mysql/bin/mysqld

After that again confirm with command ps aux | grep mysql and mac preference setting, mysql should be up and running.

Let me know if it doesn't work.


问:
why can't I convert a field in sql server from not null to null
I have a db table that previously was not null (so every record had a value). I now want to make it nullable so its optional but it seems like SQL won't let you do this without deleting and recreating the table.

Why would it have this restriction if no data will be affected as I am going to a more lenient model (not a stricter one)?

答:
You can:</p>

```<code>create table test (id int not null)
insert test values (1), (2), (3), (4), (5)
insert test values (null) -- fails
alter table test alter column id int null
insert test values (null) -- succeeds
select * from test
</code>```

Body:
You can:

create table test (id int not null)
insert test values (1), (2), (3), (4), (5)
insert test values (null) -- fails
alter table test alter column id int null
insert test values (null) -- succeeds
select * from test


问:
Generate all possible 2 character combinations of a potential 8 character string?
I have a to generate all possible combinations of a tuple of tuples

```<code>( (base1 , position1) , (base2 , position2) )
</code>```

The bases = ["U", "C", "A", "G"] and the positions = [0,1,2,3,4,5,6,7,8].

Requirements

no repeats

the bases can be the same but the positions must be
different

the order must be kept.

For example:

( (A,1), (B,2) ) == ( (B,2) , (A,1) ) and
( (A,1), (B,1) ) should be discarded.

Sample output:

[ ( (U,0) , (U,1) ), ( (U,0) , (U,2) ), ( (U,0) , (U,3) ) ...]

Should have a length of 448

Example:

For a string length 2:

```<code>((U,0),(U,1))
((U,0),(C,1))
((U,0),(A,1))
((U,0),(G,1))

((C,0),(U,1))
((C,0),(C,1))
((C,0),(A,1))
((C,0),(G,1))

((A,0),(U,1))
((A,0),(C,1))
((A,0),(A,1))
((A,0),(G,1))

((G,0),(U,1))
((G,0),(C,1))
((G,0),(A,1))
((G,0),(G,1))
</code>```

would be all the combinations... I think

I have this so far

```<code>all_possible = []
nucleotides = ["U","C","A","G"]

for i in range(len(nucleotides)):
    for j in range(8):
        all_possible.append(((nucleotides[i],j),(nucleotides[i],j)))
</code>```

答:
It sounds like you want the Cartesian product of (every possible 2-base word)  X (every 2-combination drawn from range(8)).

You can get this in general by

```<code>from itertools import product, combinations

def build(num_chars, length):
    bases = ["U", "C", "A", "G"]
    for letters in product(bases, repeat=num_chars):
        for positions in combinations(range(length), num_chars):
            yield list(zip(letters, positions))
</code>```

which gives us

```<code>In [4]: output = list(build(2, 8))

In [5]: len(output)
Out[5]: 448

In [6]: output[:4]
Out[6]:
[[('U', 0), ('U', 1)],
 [('U', 0), ('U', 2)],
 [('U', 0), ('U', 3)],
 [('U', 0), ('U', 4)]]

In [7]: output[-4:]
Out[7]:
[[('G', 4), ('G', 7)],
 [('G', 5), ('G', 6)],
 [('G', 5), ('G', 7)],
 [('G', 6), ('G', 7)]]
</code>```

Body:
I have a to generate all possible combinations of a tuple of tuples

( (base1 , position1) , (base2 , position2) )

The bases = ["U", "C", "A", "G"] and the positions = [0,1,2,3,4,5,6,7,8].

Requirements

no repeats

the bases can be the same but the positions must be
different

the order must be kept.

For example:

( (A,1), (B,2) ) == ( (B,2) , (A,1) ) and
( (A,1), (B,1) ) should be discarded.

Sample output:

[ ( (U,0) , (U,1) ), ( (U,0) , (U,2) ), ( (U,0) , (U,3) ) ...]

Should have a length of 448

Example:

For a string length 2:

((U,0),(U,1))
((U,0),(C,1))
((U,0),(A,1))
((U,0),(G,1))

((C,0),(U,1))
((C,0),(C,1))
((C,0),(A,1))
((C,0),(G,1))

((A,0),(U,1))
((A,0),(C,1))
((A,0),(A,1))
((A,0),(G,1))

((G,0),(U,1))
((G,0),(C,1))
((G,0),(A,1))
((G,0),(G,1))

would be all the combinations... I think

I have this so far

all_possible = []
nucleotides = ["U","C","A","G"]

for i in range(len(nucleotides)):
    for j in range(8):
        all_possible.append(((nucleotides[i],j),(nucleotides[i],j)))

Body:
It sounds like you want the Cartesian product of (every possible 2-base word)  X (every 2-combination drawn from range(8)).

You can get this in general by

from itertools import product, combinations

def build(num_chars, length):
    bases = ["U", "C", "A", "G"]
    for letters in product(bases, repeat=num_chars):
        for positions in combinations(range(length), num_chars):
            yield list(zip(letters, positions))

which gives us

In [4]: output = list(build(2, 8))

In [5]: len(output)
Out[5]: 448

In [6]: output[:4]
Out[6]:
[[('U', 0), ('U', 1)],
 [('U', 0), ('U', 2)],
 [('U', 0), ('U', 3)],
 [('U', 0), ('U', 4)]]

In [7]: output[-4:]
Out[7]:
[[('G', 4), ('G', 7)],
 [('G', 5), ('G', 6)],
 [('G', 5), ('G', 7)],
 [('G', 6), ('G', 7)]]


问:
Asp.net Web Api stop using ARRAffinity cookie
My API uses bearer token for authentication and the controller use Authorize attribute.

Whenever I query the API using postman. It for some reason sends a ARRAffinity cookie with every request along with the bearer token.

However, when I call the same API endpoint with fiddler without he cookie. It fails with a 401 Randomly. YES Randomly some requests would get 200 success and some would fail with 401.

However, when I pass the ARRAffinity cookie via fidler. It works without any failure.

Is there a way to stop Web Api or azure from generating the ARRAffinity cookie. I just want to use bearer  and not the cookie.

答:
Is there a way to stop Web Api or azure from generating the ARRAffinity cookie.

We can easily turn ARR Affinity off in the azure portal. detail steps are as blow:

Step 1:  Navigate to your Web Api in the Azure portal.

Step 2:  Select Application settings in the Settings blade.

Step 3:  Off ARR Affinity.

Step 4:  Select Save.

For more information please refer to document


问:
UIPageViewController shows an animation in the wrong direction when deleting the last photo
I'm using UIPageViewController with transition style swipe, to implement a photo gallery. As the user swipes through photos, she can delete an individual photo, in which case the gallery goes to the next photo, along with an animation. This works as expected.

If the last photo is deleted, we go to the photo before the deleted one. This also works as expected, but the animation is wrong — it looks as if we're going to the next photo.

My code is:

```<code>let photo = (viewControllers!.first as! SinglePhotoController).photo
var nextPhoto = Photo.after(photo: photo)
if nextPhoto == nil {
  nextPhoto = Photo.before(photo: photo)
  print("You deleted the last photo, so showing previous photo")
}
photo.delete {
  let nextController = self.makeController(photo: nextPhoto!)
  self.setViewControllers([nextController], direction: .forward, animated: true)
}
</code>```

photo.delete() is a method that deletes the photo and invokes the callback on the main thread.

How do I invoke setViewControllers() with a different animation?

This is on iOS 10.

答:
Just use direction: .reverse when deleting the last photo.

The effect of this is transient — once the animation triggered by setViewControllers() completes, it no longer has an effect. In other words, the direction of navigation remains unchanged: if you have A, B, and C, and you delete C, you'll end up with A and B as intended, not B and A.

Body:
I'm using UIPageViewController with transition style swipe, to implement a photo gallery. As the user swipes through photos, she can delete an individual photo, in which case the gallery goes to the next photo, along with an animation. This works as expected.

If the last photo is deleted, we go to the photo before the deleted one. This also works as expected, but the animation is wrong — it looks as if we're going to the next photo.

My code is:

let photo = (viewControllers!.first as! SinglePhotoController).photo
var nextPhoto = Photo.after(photo: photo)
if nextPhoto == nil {
  nextPhoto = Photo.before(photo: photo)
  print("You deleted the last photo, so showing previous photo")
}
photo.delete {
  let nextController = self.makeController(photo: nextPhoto!)
  self.setViewControllers([nextController], direction: .forward, animated: true)
}

photo.delete() is a method that deletes the photo and invokes the callback on the main thread.

How do I invoke setViewControllers() with a different animation?

This is on iOS 10.


问:
Changing Light Intensity Unity Multiplayer
I am currently facing an issue when trying to change the intensity of my light in multiplayer.

The light intensities changes fine for the person who starts the game, the host. However the people who connect to the host, their light intensity does not change.

I am trying to change the light intensity using the [SyncVar] however the player who connects to the host is not seeing the light intensity change at all. Here's my code:

```<code> using UnityEngine;
 using System.Collections;
 using UnityEngine.Networking;

 public class dayNightCycle : NetworkBehaviour { //changes day and night based on the wavelevel SpawnManager_waveLevel.cs script

     Light light;
     float fadeTime = 1f;
     [SyncVar(hook = "OnLightAmountChange")]
     float lightAmout = 0f;
     SpawnManager_waveLevel level;

     public override void OnStartLocalPlayer()
     {
         light = GetComponentInChildren<Light>();
         level = GetComponent<SpawnManager_waveLevel>();
         light.intensity = lightAmout;
     }

     // Update is called once per frame
     void Update () {

         changeLight();
     }

     void changeLight()
     {
         if (isLocalPlayer)
         {
             if (level.waveCounter == 1)
             {
                 lightAmout = 0.03f;
                 light.intensity = Mathf.Lerp(light.intensity, lightAmout, fadeTime * Time.deltaTime);
             }
             else
             {
                 lightAmout = 1f;
                 light.intensity = Mathf.Lerp(light.intensity, lightAmout, fadeTime * Time.deltaTime);
             }
         }
     }

     void OnLightAmountChange(float amount)
     {
         lightAmout = amount;
         changeLight();
     }
 }
</code>```

My issue is that the light intensity is only changing for one player, the host. I want the light intensity to change for all player who connect to the game. Any suggestions are welcome.

答:
I was able to fix this issue by completely removing the light intensity change logic from this class. This class now looks like the following:

```<code>using UnityEngine;
using System.Collections;
using UnityEngine.Networking;

public class dayNightCycle : NetworkBehaviour { //changes day and night based on the wavelevel SpawnManager_waveLevel.cs script

    [SerializeField]
    public Light light;

    [SerializeField]
    SpawnManager_waveLevel level;

    [SyncVar(hook = "OnLightAmountChange")]
    public float lightAmout = 0f;

    public override void OnStartLocalPlayer()
    {
        OnLightAmountChange(lightAmout);
    }

    void OnLightAmountChange(float amount)
    {
        light.intensity = amount;
    }
}
</code>```

I've gone ahead and put the condition to change the light intensity into my SpawnManager_waveLevel and now it works fine. I hope this will help whoever was facing the same issue as me.

oh and also a big change in that class was in the method OnLightAmountChange(), I no longer set lightAmout = amount; I now set the following as you can see light.intensity = amount; The actual intensity.

Body:
I am currently facing an issue when trying to change the intensity of my light in multiplayer.

The light intensities changes fine for the person who starts the game, the host. However the people who connect to the host, their light intensity does not change.

I am trying to change the light intensity using the [SyncVar] however the player who connects to the host is not seeing the light intensity change at all. Here's my code:

 using UnityEngine;
 using System.Collections;
 using UnityEngine.Networking;

 public class dayNightCycle : NetworkBehaviour { //changes day and night based on the wavelevel SpawnManager_waveLevel.cs script

     Light light;
     float fadeTime = 1f;
     [SyncVar(hook = "OnLightAmountChange")]
     float lightAmout = 0f;
     SpawnManager_waveLevel level;

     public override void OnStartLocalPlayer()
     {
         light = GetComponentInChildren<Light>();
         level = GetComponent<SpawnManager_waveLevel>();
         light.intensity = lightAmout;
     }

     // Update is called once per frame
     void Update () {

         changeLight();
     }

     void changeLight()
     {
         if (isLocalPlayer)
         {
             if (level.waveCounter == 1)
             {
                 lightAmout = 0.03f;
                 light.intensity = Mathf.Lerp(light.intensity, lightAmout, fadeTime * Time.deltaTime);
             }
             else
             {
                 lightAmout = 1f;
                 light.intensity = Mathf.Lerp(light.intensity, lightAmout, fadeTime * Time.deltaTime);
             }
         }
     }

     void OnLightAmountChange(float amount)
     {
         lightAmout = amount;
         changeLight();
     }
 }

My issue is that the light intensity is only changing for one player, the host. I want the light intensity to change for all player who connect to the game. Any suggestions are welcome.

Body:
I was able to fix this issue by completely removing the light intensity change logic from this class. This class now looks like the following:

using UnityEngine;
using System.Collections;
using UnityEngine.Networking;

public class dayNightCycle : NetworkBehaviour { //changes day and night based on the wavelevel SpawnManager_waveLevel.cs script

    [SerializeField]
    public Light light;

    [SerializeField]
    SpawnManager_waveLevel level;

    [SyncVar(hook = "OnLightAmountChange")]
    public float lightAmout = 0f;

    public override void OnStartLocalPlayer()
    {
        OnLightAmountChange(lightAmout);
    }

    void OnLightAmountChange(float amount)
    {
        light.intensity = amount;
    }
}

I've gone ahead and put the condition to change the light intensity into my SpawnManager_waveLevel and now it works fine. I hope this will help whoever was facing the same issue as me.

oh and also a big change in that class was in the method OnLightAmountChange(), I no longer set lightAmout = amount; I now set the following as you can see light.intensity = amount; The actual intensity.


问:
paypal checkout.js check error transaction
I'm working with the checkOut button (https://developer.paypal.com/demo/checkout/#/pattern/confirm) and I'm having some trubles.
I have a question about the process of checking if a credit card is valid or if the account has enough founds for the payment. Take this code for an example:

```<code>  return actions.payment.execute().then(function(data) {

                    console.log(data);

                });
</code>```

The question is that if I could know if 'data' has the information about the execution of the payment. If not, where I can find the information?

答:
If that then function is called, then the payment was successful.

```<code>return actions.payment.execute().then(function(data) {
    console.log('payment was successful!');
}).catch(function(err) {
    console.log('payment failed!');
});
</code>```

Body:
I'm working with the checkOut button (https://developer.paypal.com/demo/checkout/#/pattern/confirm) and I'm having some trubles.
I have a question about the process of checking if a credit card is valid or if the account has enough founds for the payment. Take this code for an example:

  return actions.payment.execute().then(function(data) {

                    console.log(data);

                });

The question is that if I could know if 'data' has the information about the execution of the payment. If not, where I can find the information?

Body:
If that then function is called, then the payment was successful.

return actions.payment.execute().then(function(data) {
    console.log('payment was successful!');
}).catch(function(err) {
    console.log('payment failed!');
});


问:
Array does not connect with the tableView(numberOfRowsInSection) method
I have an array which I will store all data that I get from http request and display them on tableView but it seems that tableView(numberOfRowsInSection) does not recognize the change in the array because the count remains as 0.

```<code>class OrdersViewController: UIViewController {
    @IBOutlet weak var tableView: UITableView!

    var arr = [[String: AnyObject]]()
    var selectedIndex = -1

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        let baseUrl = "my url"
        let consumer_key = "consumer_key"
        let consumer_secret = "consumer_key"
        let url = "\(baseUrl)?consumer_key=\(consumer_key)&consumer_secret=\(consumer_secret)&status=processing"

        let headers2 = ["Accept": "application/json"]
        Alamofire.request(url, headers: headers2)
            .responseJSON { response in
                    self.arr.append(data from request)
                }
        }

        let url2 = "\(baseUrl)?consumer_key=\(consumer_key)&consumer_secret=\(consumer_secret)&status=pending"
        Alamofire.request(url2, headers: headers2)
            .responseJSON { response in
                    self.arr.append(data from request)
                    print("arr", self.arr)
                }
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        print("after request", self.arr)
        return self.arr.count
    }
}
// and some other code...
</code>```

I do get data from the http request successfully and it gets updated in my Alamofire call but "after request" keeps printing empty array. What's going on here?

答: I would recommend you to move your request and response logic in one function and then call that function from viewDidAppear instead of viewDidLoad and just after the call reload your tableview using reloadData()

Body:
I have an array which I will store all data that I get from http request and display them on tableView but it seems that tableView(numberOfRowsInSection) does not recognize the change in the array because the count remains as 0.

class OrdersViewController: UIViewController {
    @IBOutlet weak var tableView: UITableView!

    var arr = [[String: AnyObject]]()
    var selectedIndex = -1

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        let baseUrl = "my url"
        let consumer_key = "consumer_key"
        let consumer_secret = "consumer_key"
        let url = "\(baseUrl)?consumer_key=\(consumer_key)&consumer_secret=\(consumer_secret)&status=processing"

        let headers2 = ["Accept": "application/json"]
        Alamofire.request(url, headers: headers2)
            .responseJSON { response in
                    self.arr.append(data from request)
                }
        }

        let url2 = "\(baseUrl)?consumer_key=\(consumer_key)&consumer_secret=\(consumer_secret)&status=pending"
        Alamofire.request(url2, headers: headers2)
            .responseJSON { response in
                    self.arr.append(data from request)
                    print("arr", self.arr)
                }
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        print("after request", self.arr)
        return self.arr.count
    }
}
// and some other code...

I do get data from the http request successfully and it gets updated in my Alamofire call but "after request" keeps printing empty array. What's going on here?


问:
Using Build Variables in C code with Eclipse 4.4.2
I have a project that I created previously using Eclipse 3.5.2.  In it, I was able to set a Build Variable in the project properties.  In this case, let's say I set SW_VERSION to be 4403.  Now this is intended to be a hex number, so in the Build Settings, I added a Symbol "VERSION=0x${SW_VERSION}" entry.  Then in my code, I was able to use VERSION as a regular number, like so:

```<code>unsigned int vers = VERSION;
</code>```

There was no problems, and vers got the value 0x4403.

Now I'm using Eclipse version 4.4.2 and I'm updating my project with some new features.  But first I'm just trying to re-compile my old project with the new toolchain, and while I don't get any messages on the Console, I get 3 warnings in the Problems tab:

Symbol 'SW_VERSION' could not be resolved
Symbol '$' could not be resolved
Statement has no effect 'VERSION'
```

I haven't tried running the completed project yet, but this concerns me and I have to assume that it won't actually work like it used to.  Is there some different way to do this in the newer Eclipse or is this feature just gone?

As a side note, there is a reason why I did it that way.  I also have the value of SW_VERSION appended to the end of my artifact name.  That part still works at least.

答:
You say:

Makes the thing kind of pointless if it can't actually analyze what the code actually is. I did this and it works, but it makes the pop-up macro expansion show this fake value rather than the real thing.

But I bet in Eclipse 3.5.2, the pop-up macro expansion wouldn't even come up for VERSION.

In other words, the indexer was never resolving VERSION correctly. The only thing that changed, I believe around Eclipse 3.7, is that indexer errors started to be surfaced in the UI, which I why you would have started seeing errors like Symbol '$' could not be resolved.

Now, regarding solving your problem: is the build output parser (Project Properties -> C/C++ General -> Preprocessor Include Paths, Macros etc. -> Providers tab -> <Your Toolchain> Build Output Parser) enabled?

It should be able to pick up the correct value of VERSION for the indexer, by parsing the output of the build, including the compiler invocations (which presumably contain the expanded value of ${SW_VERSION}, otherwise compilation wouldn't work).

I don't have much experience with generated makefile projects (I write my own makefiles), but I think the build output parser should work for them too.

Body:
I have a project that I created previously using Eclipse 3.5.2.  In it, I was able to set a Build Variable in the project properties.  In this case, let's say I set SW_VERSION to be 4403.  Now this is intended to be a hex number, so in the Build Settings, I added a Symbol "VERSION=0x${SW_VERSION}" entry.  Then in my code, I was able to use VERSION as a regular number, like so:

unsigned int vers = VERSION;

There was no problems, and vers got the value 0x4403.

Now I'm using Eclipse version 4.4.2 and I'm updating my project with some new features.  But first I'm just trying to re-compile my old project with the new toolchain, and while I don't get any messages on the Console, I get 3 warnings in the Problems tab:

Symbol 'SW_VERSION' could not be resolved
Symbol '$' could not be resolved
Statement has no effect 'VERSION'

I haven't tried running the completed project yet, but this concerns me and I have to assume that it won't actually work like it used to.  Is there some different way to do this in the newer Eclipse or is this feature just gone?

As a side note, there is a reason why I did it that way.  I also have the value of SW_VERSION appended to the end of my artifact name.  That part still works at least.


问:
why this error Exception in thread "main" java.lang.IllegalArgumentException: adding a window to a container
I am trying to make a simple GUI with a button but getting this error.</p>

```<code>import javax.swing.*;

public class GUIClass extends JFrame {

    public static void main (String[] args){
        // TODO Auto-generated method stub
        JFrame fm = new JFrame();
        JFrame btn = new JFrame("Click ME");
        btn.setBounds(50, 40, 120, 30);
        fm.add(btn);
        fm.setLayout(null);
        fm.setVisible(true);
        fm.setSize(400, 300);
    }
}
</code>```

答:
```<code> JFrame btn = new JFrame("Click ME");
</code>```

Change it to;

```<code>JButton btn = new JButton("Click ME");
</code>```

Also don't forget to import javax.swing.JButton;

Also check this out:
https://docs.oracle.com/javase/7/docs/api/javax/swing/JButton.html

Body:
I am trying to make a simple GUI with a button but getting this error.

import javax.swing.*;

public class GUIClass extends JFrame {

    public static void main (String[] args){
        // TODO Auto-generated method stub
        JFrame fm = new JFrame();
        JFrame btn = new JFrame("Click ME");
        btn.setBounds(50, 40, 120, 30);
        fm.add(btn);
        fm.setLayout(null);
        fm.setVisible(true);
        fm.setSize(400, 300);
    }
}

Body:
 JFrame btn = new JFrame("Click ME");

Change it to;

JButton btn = new JButton("Click ME");

Also don't forget to import javax.swing.JButton;

Also check this out:
https://docs.oracle.com/javase/7/docs/api/javax/swing/JButton.html


问:
Should i put nickname avatar into user access token?
Should I put user's nickname and avatar into user's access token like jwt? what's the best practice?</p>

答:
sub Subject - This holds the identifier for the token (defaults to
user id)

iat Issued At - When the token was issued (unix timestamp)

exp Expiry - The token expiry date (unix timestamp)

nbf Not Before - The earliest point in time that the token can be
used (unix timestamp)

iss Issuer - The issuer of the token (defaults to the request url)

jti JWT Id - A unique identifier for the token (md5 of    the sub and
iat claims)

Just put the user's uniquely identifies into the subject claim.


问:
How to return bool and double simultaneously?
In C, I have a function that calculates the product of a and b. If a < b it returns false otherwise returns true. How can I return the product when the function is defined as boolean?</p>

```<code>bool multiplication(int a, int b)
{
    int c = a*b;
    if (a < b)
        return false;
    else
        return true;
}
</code>```

答:
You can define a new parameter as output.

define a struct included bool and int data.
Initiate the struct, then return it.

Body:
In C, I have a function that calculates the product of a and b. If a < b it returns false otherwise returns true. How can I return the product when the function is defined as boolean?

bool multiplication(int a, int b)
{
    int c = a*b;
    if (a < b)
        return false;
    else
        return true;
}


问:
Is there a more concise way to combine many comparisons in Ruby?
I currently have this if statement:

```<code>if Time.now.day == 1 and Time.now.hour == 0 and Time.now.minute == 0 and Time.now.second == 0
</code>```

Is there a more concise way to do this?

答:
You can compare it to a time you created:

```<code>if Time.now == Time.at(0)
</code>```

or

```<code>if Time.now == Time.utc(2000,"jan",1,20,15,1)
</code>```

Body:
I currently have this if statement:

if Time.now.day == 1 and Time.now.hour == 0 and Time.now.minute == 0 and Time.now.second == 0

Is there a more concise way to do this?

Body:
You can compare it to a time you created:

if Time.now == Time.at(0)

or

if Time.now == Time.utc(2000,"jan",1,20,15,1)