问:
Redux loses state when navigating to another page using react-router 'history.push'
(as you can see my reputation is not very high :) and I understand that if you don't like my question it is going to be my last one, therefore I am going to write it as good as I can :)

The problem I am facing is a similar to:

Redux loses state when navigating to another page

However, the answer to the above question was to use 'history.push', which is what I am doing, and I am still having a problem.

I am using:

"react": "^16.0.0"

"react-redux": "^5.0.6"

"react-router": "^4.2.0"

"react-router-dom": "^4.2.2"

"redux": "^3.7.2"

"redux-promise":"^0.5.3"

"axios": "^0.17.1"

I am doing the following:

In a react component, "SearchText", getting a text string and calling an action creator

In the action creator, using the text string to send an HTTP request to goodreads.com

In my reducer, using the action payload to set the redux state

Using another component, "BookResults" (in another route), to display this state

The component "SearchText" has a link to the "BookResults" page.
So, once "SearchText" fires the action creator, if (when I see on the console that a result is received and the state is set with a list of books) I click on the link that routes to "BookResults", I see the list of books.

If, however, "SearchText" uses (when firing the action creator) a callback that performs history.push of the new page, and this callback is called by 'axios(xxx).then', the state is not set properly, although I see in the console that the HTTP request was successful.

I am sure you can see what I am doing wrong (and I hope it is not very stupid)... Please tell me.

Here is the code:

index.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import { createStore, applyMiddleware } from 'redux';
import ReduxPromise from 'redux-promise';
import SearchText from './components/search_text';
import BookResults from './components/book_results';
import reducers from './reducers';

const createStoreWithMiddleware = applyMiddleware(ReduxPromise)(createStore);

ReactDOM.render(
  <Provider store={createStoreWithMiddleware(reducers)}>
    <BrowserRouter>
    <div>
      <BrowserRouter>
        <Switch>
          <Route path="/book_results" component={BookResults} />
          <Route path="/" component={SearchText} />
        </Switch>
      </BrowserRouter>
    </div>

    </BrowserRouter>
  </Provider>
  , document.querySelector('#root'));
</code>```

SearchText component

```<code>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Link } from 'react-router-dom';
import { searchForBooks } from '../actions';

class SearchText extends Component {
    constructor(props) {
        super(props);
        this.state = {
            searchText: ''
        };
        this.handleFormSubmit = this.handleFormSubmit.bind(this);
        this.handleSearchTextChange = this.handleSearchTextChange.bind(this);
    }

    handleSearchTextChange(e) {
        this.setState({ searchText: e.target.value });
    }

    handleFormSubmit(e) {
        e.preventDefault();

        const formPayload = {
            searchText: this.state.searchText
        };

        console.log("In SearchBooks/handleFormSubmit. Submitting. state: ", this.state);
    this.props.searchForBooks(formPayload, () => {
            this.props.history.push(`/book_results`);
        });
    }

    render() {
        return (
            <form className="container" onSubmit={this.handleFormSubmit}>
                <h3>Search Form</h3>

                <div className="form-group">
                    <label className="form-label">{'Search Text:'}</label>
                    <input
                        className='form-input'
                        type='text'
                        name='searchText'
                        value={this.state.searchText}
                        onChange={this.handleSearchTextChange}
                        onBlur={this.handleSearchTextBlur}
                        placeholder='' />
                </div>
                <br />
                <input
                    type="submit"
                    className="btn btn-primary float-right"
                    value="Submit"/>
                <br /><br />
                <Link to={`/book_results`}>⇐ Book Results</Link>
            </form>
        );
    }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({ searchForBooks: searchForBooks }, dispatch);
}

export default connect(null, mapDispatchToProps)(SearchText);
</code>```

BookResults component

```<code>import React from 'react';
import { connect } from 'react-redux';
import _ from 'lodash';
import Book from './book';

class BookResults extends React.Component {

  render() {

    let books;
    const booksArray = _.values(this.props.bookResults);
    console.log("***In BookResults. booksArray: ", booksArray);

    if (booksArray.length === 0) {
      books = "No books to display";
    } else {
      books = booksArray.map( (book) => {
        return (
          <Book book={book} key={book.id} />
        );
      });
    }

    return (
      <div>
        <h2>Search Results</h2>
        <br />
        <ul>
          {books}
        </ul>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    bookResults: state.bookResults,
    cats: state.cats
  };
}

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

Book component

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

const Book = (props) => (
  <li>
    {props.book.title}
  </li>
);

export default Book;
</code>```

actions/index.js

As you can see below, the following line is commented out:

```<code>//  .then(() => callback());
</code>```

If I include it, I have the problem.

```<code>import axios from 'axios';
export const SEARCH_FOR_BOOKS = 'search_for_books';

const GOODREADS = "https://www.goodreads.com/search/index.xml";
const KEY = "xxx";

export function searchForBooks(values, callback) {
  let result;
  console.log("In actions/searchForBooks. values: ", values);
  if (!values.searchText || values.searchText === "") {
    console.error("*** ERROR *** In actions/searchForBooks." +
    "values.searchText: ", values.searchText);
  } else {
    const searchUrl = `${GOODREADS}?key=${KEY}&q=${values.searchText}`;
    console.log("In actions/searchForBooks. url: " + searchUrl);

    result = axios.get(searchUrl);
    //  .then(() => callback());
  }

  return {
    type: SEARCH_FOR_BOOKS,
    payload: result
  };
}
</code>```

reducers/index.js

```<code>import { combineReducers } from 'redux';
import bookResultsReducer from './reducer_book_results';

const rootReducer = combineReducers({
  bookResults: bookResultsReducer
});

export default rootReducer;
</code>```

The reducer

```<code>import { parseString } from  'xml2js';
import _ from 'lodash';
import { SEARCH_FOR_BOOKS } from '../actions/index';

const bookResults = {};

export default function bookResultsReducer(state = bookResults, action) {
  switch (action.type) {
    case SEARCH_FOR_BOOKS:
      console.log("In bookResultsReducer. payload: ", action.payload);
      if (action.error) {  // error from goodreads search books
        console.error("*** APP ERROR *** In bookResultsReducer. action.error: ", action.error);
      } else if (!action.payload || !action.payload.data) {
        console.error("*** APP ERROR *** In bookResultsReducer." +
        " action.payload or action.payload.data is undefined", action.payload);
      } else {
        parseString(action.payload.data, function(err, result) {
          if (err) {
            console.error("*** APP ERROR *** In bookResultsReducer. Error from parseString: ", err);
          } else {
            state = Object.assign({}, getBooks(result));
          }
        });
      }
      console.log("In bookResultsReducer. new state: ", state);
      return state;
      break;

    default:
      return state;
  }
}

function getBooks(data) {

  const bookResults =  data.GoodreadsResponse.search[0].results[0].work;
  if (!bookResults || bookResults.length === 0) {
    return {};
  } else {
    const results = bookResults.map( (book, index) => {
      const bookInfo = book.best_book[0];
      return (
        { id: index + 1,
          title: bookInfo.title[0] }
      );
    });
    return _.mapKeys(results, 'id');
  }
}
</code>```

答:
Someone sent me the solution by mail.

The error was in the actions/index.js file.

Instead of:

```<code>import axios from 'axios';
export const SEARCH_FOR_BOOKS = 'search_for_books';

const GOODREADS = "https://www.goodreads.com/search/index.xml";
const KEY = "xxx";

export function searchForBooks(values, callback) {
  let result;
  console.log("In actions/searchForBooks. values: ", values);
  if (!values.searchText || values.searchText === "") {
    console.error("*** ERROR *** In actions/searchForBooks." +
    "values.searchText: ", values.searchText);
  } else {
    const searchUrl = `${GOODREADS}?key=${KEY}&q=${values.searchText}`;
    console.log("In actions/searchForBooks. url: " + searchUrl);

    result = axios.get(searchUrl)
      .then(() => callback());
  }

  return {
    type: SEARCH_FOR_BOOKS,
    payload: result
  };
}
</code>```

I should have written:

```<code>import axios from 'axios';
export const SEARCH_FOR_BOOKS = 'search_for_books';

const GOODREADS = "https://www.goodreads.com/search/index.xml";
const KEY = "xxx";

export function searchForBooks(values, callback) {
  let result;
  console.log("In actions/searchForBooks. values: ", values);
  if (!values.searchText || values.searchText === "") {
    console.error("*** ERROR *** In actions/searchForBooks." +
    "values.searchText: ", values.searchText);
  } else {
    const searchUrl = `${GOODREADS}?key=${KEY}&q=${values.searchText}`;
    console.log("In actions/searchForBooks. url: " + searchUrl);

    result = axios.get(searchUrl)
      .then((res) => {
        callback();
        return res;
      });
  }

  return {
    type: SEARCH_FOR_BOOKS,
    payload: result
  };
}
</code>```

Explanation:

The issue is that the returned value from axios.get is passed to the .then clause, and whatever is returned from the .then clause is set to be the value of result.
My error was that I didn't return anything from the .then clause, and therefore the value of result was undefined, and not the returned promise.

Body:
(as you can see my reputation is not very high :) and I understand that if you don't like my question it is going to be my last one, therefore I am going to write it as good as I can :)

The problem I am facing is a similar to:

Redux loses state when navigating to another page

However, the answer to the above question was to use 'history.push', which is what I am doing, and I am still having a problem.

I am using:

"react": "^16.0.0"

"react-redux": "^5.0.6"

"react-router": "^4.2.0"

"react-router-dom": "^4.2.2"

"redux": "^3.7.2"

"redux-promise":"^0.5.3"

"axios": "^0.17.1"

I am doing the following:

In a react component, "SearchText", getting a text string and calling an action creator

In the action creator, using the text string to send an HTTP request to goodreads.com

In my reducer, using the action payload to set the redux state

Using another component, "BookResults" (in another route), to display this state

The component "SearchText" has a link to the "BookResults" page.
So, once "SearchText" fires the action creator, if (when I see on the console that a result is received and the state is set with a list of books) I click on the link that routes to "BookResults", I see the list of books.

If, however, "SearchText" uses (when firing the action creator) a callback that performs history.push of the new page, and this callback is called by 'axios(xxx).then', the state is not set properly, although I see in the console that the HTTP request was successful.

I am sure you can see what I am doing wrong (and I hope it is not very stupid)... Please tell me.

Here is the code:

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import { createStore, applyMiddleware } from 'redux';
import ReduxPromise from 'redux-promise';
import SearchText from './components/search_text';
import BookResults from './components/book_results';
import reducers from './reducers';

const createStoreWithMiddleware = applyMiddleware(ReduxPromise)(createStore);

ReactDOM.render(
  <Provider store={createStoreWithMiddleware(reducers)}>
    <BrowserRouter>

      <BrowserRouter>
        <Switch>
          <Route path="/book_results" component={BookResults} />
          <Route path="/" component={SearchText} />
        </Switch>
      </BrowserRouter>

    </BrowserRouter>
  </Provider>
  , document.querySelector('#root'));

SearchText component

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Link } from 'react-router-dom';
import { searchForBooks } from '../actions';

class SearchText extends Component {
    constructor(props) {
        super(props);
        this.state = {
            searchText: ''
        };
        this.handleFormSubmit = this.handleFormSubmit.bind(this);
        this.handleSearchTextChange = this.handleSearchTextChange.bind(this);
    }

    handleSearchTextChange(e) {
        this.setState({ searchText: e.target.value });
    }

    handleFormSubmit(e) {
        e.preventDefault();

        const formPayload = {
            searchText: this.state.searchText
        };

        console.log("In SearchBooks/handleFormSubmit. Submitting. state: ", this.state);
    this.props.searchForBooks(formPayload, () => {
            this.props.history.push(`/book_results`);
        });
    }

    render() {
        return (
            <form className="container" onSubmit={this.handleFormSubmit}>

Search Form

                    {'Search Text:'}
                    <input
                        className='form-input'
                        type='text'
                        name='searchText'
                        value={this.state.searchText}
                        onChange={this.handleSearchTextChange}
                        onBlur={this.handleSearchTextBlur}
                        placeholder='' />

                <input
                    type="submit"
                    className="btn btn-primary float-right"
                    value="Submit"/>

                <Link to={`/book_results`}>⇐ Book Results</Link>
            </form>
        );
    }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({ searchForBooks: searchForBooks }, dispatch);
}

export default connect(null, mapDispatchToProps)(SearchText);

BookResults component

import React from 'react';
import { connect } from 'react-redux';
import _ from 'lodash';
import Book from './book';

class BookResults extends React.Component {

  render() {

    let books;
    const booksArray = _.values(this.props.bookResults);
    console.log("***In BookResults. booksArray: ", booksArray);

    if (booksArray.length === 0) {
      books = "No books to display";
    } else {
      books = booksArray.map( (book) => {
        return (
          <Book book={book} key={book.id} />
        );
      });
    }

    return (

Search Results

          {books}

    );
  }
}

function mapStateToProps(state) {
  return {
    bookResults: state.bookResults,
    cats: state.cats
  };
}

export default connect(mapStateToProps)(BookResults);

Book component

import React from 'react';

const Book = (props) => (

    {props.book.title}

);

export default Book;

actions/index.js

As you can see below, the following line is commented out:

//  .then(() => callback());

If I include it, I have the problem.

import axios from 'axios';
export const SEARCH_FOR_BOOKS = 'search_for_books';

const GOODREADS = "https://www.goodreads.com/search/index.xml";
const KEY = "xxx";

export function searchForBooks(values, callback) {
  let result;
  console.log("In actions/searchForBooks. values: ", values);
  if (!values.searchText || values.searchText === "") {
    console.error("*** ERROR *** In actions/searchForBooks." +
    "values.searchText: ", values.searchText);
  } else {
    const searchUrl = `${GOODREADS}?key=${KEY}&q=${values.searchText}`;
    console.log("In actions/searchForBooks. url: " + searchUrl);

    result = axios.get(searchUrl);
    //  .then(() => callback());
  }

  return {
    type: SEARCH_FOR_BOOKS,
    payload: result
  };
}

reducers/index.js

import { combineReducers } from 'redux';
import bookResultsReducer from './reducer_book_results';

const rootReducer = combineReducers({
  bookResults: bookResultsReducer
});

export default rootReducer;

The reducer

import { parseString } from  'xml2js';
import _ from 'lodash';
import { SEARCH_FOR_BOOKS } from '../actions/index';

const bookResults = {};

export default function bookResultsReducer(state = bookResults, action) {
  switch (action.type) {
    case SEARCH_FOR_BOOKS:
      console.log("In bookResultsReducer. payload: ", action.payload);
      if (action.error) {  // error from goodreads search books
        console.error("*** APP ERROR *** In bookResultsReducer. action.error: ", action.error);
      } else if (!action.payload || !action.payload.data) {
        console.error("*** APP ERROR *** In bookResultsReducer." +
        " action.payload or action.payload.data is undefined", action.payload);
      } else {
        parseString(action.payload.data, function(err, result) {
          if (err) {
            console.error("*** APP ERROR *** In bookResultsReducer. Error from parseString: ", err);
          } else {
            state = Object.assign({}, getBooks(result));
          }
        });
      }
      console.log("In bookResultsReducer. new state: ", state);
      return state;
      break;

    default:
      return state;
  }
}

function getBooks(data) {

  const bookResults =  data.GoodreadsResponse.search[0].results[0].work;
  if (!bookResults || bookResults.length === 0) {
    return {};
  } else {
    const results = bookResults.map( (book, index) => {
      const bookInfo = book.best_book[0];
      return (
        { id: index + 1,
          title: bookInfo.title[0] }
      );
    });
    return _.mapKeys(results, 'id');
  }
}

Body:
Someone sent me the solution by mail.

The error was in the actions/index.js file.

Instead of:

import axios from 'axios';
export const SEARCH_FOR_BOOKS = 'search_for_books';

const GOODREADS = "https://www.goodreads.com/search/index.xml";
const KEY = "xxx";

export function searchForBooks(values, callback) {
  let result;
  console.log("In actions/searchForBooks. values: ", values);
  if (!values.searchText || values.searchText === "") {
    console.error("*** ERROR *** In actions/searchForBooks." +
    "values.searchText: ", values.searchText);
  } else {
    const searchUrl = `${GOODREADS}?key=${KEY}&q=${values.searchText}`;
    console.log("In actions/searchForBooks. url: " + searchUrl);

    result = axios.get(searchUrl)
      .then(() => callback());
  }

  return {
    type: SEARCH_FOR_BOOKS,
    payload: result
  };
}

I should have written:

import axios from 'axios';
export const SEARCH_FOR_BOOKS = 'search_for_books';

const GOODREADS = "https://www.goodreads.com/search/index.xml";
const KEY = "xxx";

export function searchForBooks(values, callback) {
  let result;
  console.log("In actions/searchForBooks. values: ", values);
  if (!values.searchText || values.searchText === "") {
    console.error("*** ERROR *** In actions/searchForBooks." +
    "values.searchText: ", values.searchText);
  } else {
    const searchUrl = `${GOODREADS}?key=${KEY}&q=${values.searchText}`;
    console.log("In actions/searchForBooks. url: " + searchUrl);

    result = axios.get(searchUrl)
      .then((res) => {
        callback();
        return res;
      });
  }

  return {
    type: SEARCH_FOR_BOOKS,
    payload: result
  };
}

Explanation:

The issue is that the returned value from axios.get is passed to the .then clause, and whatever is returned from the .then clause is set to be the value of result.
My error was that I didn't return anything from the .then clause, and therefore the value of result was undefined, and not the returned promise.


来源: stackexchange

问:
How to exclude generated files from gradle javadoc task?
I am generating some code in my gradle build through a 3rd party plugin.
The generated codes javadoc is malformed.

So i tried to exclude that path from gradles javadoc task but it does not work.
I looked through similar questions but none offers a helpful answer.

```<code>$> ./gradlew --version
------------------------------------------------------------
Gradle 4.3
------------------------------------------------------------

Build time:   2017-10-30 15:43:29 UTC
Revision:     c684c202534c4138b51033b52d871939b8d38d72

Groovy:       2.4.12
Ant:          Apache Ant(TM) version 1.9.6 compiled on June 29 2015
JVM:          1.8.0_121 (Oracle Corporation 25.121-b13)
OS:           Windows 7 6.1 amd64
</code>```

This is my build.gradle

```<code>sourceSets {
  main {
    compileClasspath += java.srcDir("${buildDir}/generated/src/main/com4j")
    runtimeClasspath += java.srcDir("${buildDir}/generated/src/main/com4j")
  }
  test {
    compileClasspath += java.srcDir("${buildDir}/generated/src/main/com4j")
    runtimeClasspath += java.srcDir("${buildDir}/generated/src/main/com4j")
  }
}

javadoc {
  exclude "**/generated/**"
  source = sourceSets.main.allJava
}
</code>```

Has no effect.

```<code>$> ./gradlew javadoc
:javadocC:\cygwin64\home\username\sourcecode\COMJurer\build\generated\src\main\com4j\com\app\com4j\api\ClassFactory.java:15: warning: no @return
  public static com.app.com4j.api.IAPI createAPI() {
                                                     ^
C:\cygwin64\home\username\sourcecode\COMJurer\build\generated\src\main\com4j\com\app\com4j\api\IAPI.java:99: error: malformed HTML
   * @param xmlReturn Mandatory Holder<java.lang.String> parameter.
                                  ^
 C:\cygwin64\home\username\sourcecode\COMJurer\build\generated\src\main\com4j\com\app\com4j\api\IAPI.java:99: error: bad use of '>'
   * @param xmlReturn Mandatory Holder<java.lang.String> parameter.
                                                   ^

2 errors
1 warning
:javadoc FAILED
</code>```

gradles documentation is lacking any specifics: https://docs.gradle.org/current/dsl/org.gradle.api.tasks.javadoc.Javadoc.html

答:
The problem is that your pattern refers to the path of the source directory.

Javadoc patterns are matched against the package of the classes.

So you need instead to use a pattern that refers to the package(s) you need to exclude, something like:

```<code>exclude 'com/app/com4j/api/**'
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am generating some code in my gradle build through a 3rd party plugin.
The generated codes javadoc is malformed.

So i tried to exclude that path from gradles javadoc task but it does not work.
I looked through similar questions but none offers a helpful answer.

$> ./gradlew --version
------------------------------------------------------------
Gradle 4.3
------------------------------------------------------------

Build time:   2017-10-30 15:43:29 UTC
Revision:     c684c202534c4138b51033b52d871939b8d38d72

Groovy:       2.4.12
Ant:          Apache Ant(TM) version 1.9.6 compiled on June 29 2015
JVM:          1.8.0_121 (Oracle Corporation 25.121-b13)
OS:           Windows 7 6.1 amd64

This is my build.gradle

sourceSets {
  main {
    compileClasspath += java.srcDir("${buildDir}/generated/src/main/com4j")
    runtimeClasspath += java.srcDir("${buildDir}/generated/src/main/com4j")
  }
  test {
    compileClasspath += java.srcDir("${buildDir}/generated/src/main/com4j")
    runtimeClasspath += java.srcDir("${buildDir}/generated/src/main/com4j")
  }
}

javadoc {
  exclude "**/generated/**"
  source = sourceSets.main.allJava
}

Has no effect.

$> ./gradlew javadoc
:javadocC:\cygwin64\home\username\sourcecode\COMJurer\build\generated\src\main\com4j\com\app\com4j\api\ClassFactory.java:15: warning: no @return
  public static com.app.com4j.api.IAPI createAPI() {
                                                     ^
C:\cygwin64\home\username\sourcecode\COMJurer\build\generated\src\main\com4j\com\app\com4j\api\IAPI.java:99: error: malformed HTML
   * @param xmlReturn Mandatory Holder<java.lang.String> parameter.
                                  ^
 C:\cygwin64\home\username\sourcecode\COMJurer\build\generated\src\main\com4j\com\app\com4j\api\IAPI.java:99: error: bad use of '>'
   * @param xmlReturn Mandatory Holder<java.lang.String> parameter.
                                                   ^

2 errors
1 warning
:javadoc FAILED

gradles documentation is lacking any specifics: https://docs.gradle.org/current/dsl/org.gradle.api.tasks.javadoc.Javadoc.html

Body:
The problem is that your pattern refers to the path of the source directory.

Javadoc patterns are matched against the package of the classes.

So you need instead to use a pattern that refers to the package(s) you need to exclude, something like:

exclude 'com/app/com4j/api/**'


问:
visual studio attach to process not working
I am trying to debug my production website using the code on my local system.
I am using VS2010, and tried all sorts of things still didn't work.
I tried using VS Development Server, and tried using IIS still didn't work.
When I attach the process debugger starts but break points were not hitting.
I tried attaching process to W3wp process, and tried attaching it to IE also.
Still its not hitting break points. Any idea whats causing this.
Thanks</p>

答:
Try clearing the settings of Visual Studio
Tools->Import and Export Settings Wizard->Reset all settings->No…->next and set it

One more option, which worked for me is to open the VS in Safe Mode. It will 100% work:
Open Windows Explorer, and navigate to  \Common7\IDE;
Devenv /SafeMode: Launches the IDE in safe mode loading minimal windows.


问:
how can get other Country Time in swift?
i'm beginner swift developer and i want to get user FIPS country codes like "EN" then apps Hour change to that country Time.

```<code>let CountryTime = String(NSDate.date(*/"EN"*/)) // -> return England Time
</code>```

how can do it ?

Please advice. Thank you.

答:
Following TimeZone.init Returns a time zone initialized with a given identifier.If identifier is an unknown identifier, then returns nil.

```<code>let timezone = TimeZone.init(identifier: "America/Los_Angeles")
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
dateFormatter.timeZone = timezone
print(dateFormatter.string(from: Date()))
</code>```

Also to check the timeZone identifier list you can use this to get list.

```<code>print("Time zone list %@",TimeZone.knownTimeZoneIdentifiers)
</code>```

Body:
i'm beginner swift developer and i want to get user FIPS country codes like "EN" then apps Hour change to that country Time.

let CountryTime = String(NSDate.date(*/"EN"*/)) // -> return England Time

how can do it ?

Please advice. Thank you.

Body:
Following TimeZone.init Returns a time zone initialized with a given identifier.If identifier is an unknown identifier, then returns nil.

let timezone = TimeZone.init(identifier: "America/Los_Angeles")
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
dateFormatter.timeZone = timezone
print(dateFormatter.string(from: Date()))

Also to check the timeZone identifier list you can use this to get list.

print("Time zone list %@",TimeZone.knownTimeZoneIdentifiers)


问:
Changing status code from 502 to 503 in fallback route
I'm using nginx as proxy server for my project. In case my app is offline for maintenance I'd like to show a fallback page. This works fine so far. The only problem is, that the server response with a 502 error code - which makes sense. How do I change it to a 503 route in my fallback though?</p>
```<code>server {
    listen 80;
    error_page 500 502 503 504 @fallback;

   location / {
     proxy_pass http://0.0.0.0:3000;
   }

   location @fallback {
       // I need this to answer with a status of 503 instead of a 502
       root /srv/my-project/static;
       try_files /fallback.html;
   }

}
</code>```

答:
Thanks @shalbafzadeh for that answer, that solved it for me.

In my very particular situation the solution looks like this:

```<code>server {
    listen 80;
    error_page 502 =503 @fallback; <-- THIS

   location / {
     proxy_pass http://0.0.0.0:3000;
   }

   location @fallback {
       root /srv/my-project/static;
       try_files /fallback.html;
   }

}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm using nginx as proxy server for my project. In case my app is offline for maintenance I'd like to show a fallback page. This works fine so far. The only problem is, that the server response with a 502 error code - which makes sense. How do I change it to a 503 route in my fallback though?

server {
    listen 80;
    error_page 500 502 503 504 @fallback;

   location / {
     proxy_pass http://0.0.0.0:3000;
   }

   location @fallback {
       // I need this to answer with a status of 503 instead of a 502
       root /srv/my-project/static;
       try_files /fallback.html;
   }

}

Body:
Thanks @shalbafzadeh for that answer, that solved it for me.

In my very particular situation the solution looks like this:

server {
    listen 80;
    error_page 502 =503 @fallback; <-- THIS

   location / {
     proxy_pass http://0.0.0.0:3000;
   }

   location @fallback {
       root /srv/my-project/static;
       try_files /fallback.html;
   }

}


问:
Sum of specific elements of a list based on indexes from another list in python

I am trying to find the durations of all the notes with the same name in a music piece (from .xml), in python. I have 3 lists:

```<code>scales = ['A', 'B', 'C'] #scales names
notesAll = ['B', 'A', 'C', 'A', 'C', 'C']  #note names of the piece
durationsAll = [1, 1.5, 1.5, 1, 1, 2]  #duration of each note from notesAll list
</code>```

I want to sum all the durations from durationsAll list for all the notes with the same name. For example for all the 'A's from notesAll list, which equals to scales[0], I want something like: durationsAll[1] + durationsAll[3]= 1.5 + 1 = 2.5. I need a better solution than my attempt:

```<code>for sc in scales:
  for ntPosition, nt in enumerate(notesAll):
    dtOfEach = 0
    for dtPosition, dt in enumerate(durationsAll):
      if sc == nt:
        dtPosotion = ntPosition  #I guess here is the problem
        dtOfEach = dtOfEach + dt
</code>```

The result I want would be: dtOfEach: 2.5  1  4.5

答:
It can be done with a list comprehension, exploiting the idea that booleans behave like integers

```<code>In [3]: S = ['A', 'B', 'C'] #scales names
   ...: N = ['B', 'A', 'C', 'A', 'C', 'C']  #note names of the piece
   ...: D = [1, 1.5, 1.5, 1, 1, 2]  #duration of each note from notesAll list
In [4]: [sum(match*d for match, d in zip((n==s for n in N), D)) for s in S]
Out[4]: [2.5, 1.0, 4.5]
</code>```

If you need a dictionary

```<code>In [5]: {s:sum(match*d for match, d in zip((n==s for n in N), D)) for s in S}
Out[5]: {'A': 2.5, 'B': 1.0, 'C': 4.5}
</code>```

or, avoiding one loop and w/o importing collections

```<code>In [6]: r = {}
In [7]: for n, d  in zip(N, D): r[n] = r.get(n, 0) + d
In [8]: r
Out[8]: {'A': 2.5, 'B': 1, 'C': 4.5}
</code>```

where we access the data in the dictionary not  by indexing but using the dictionary .get(key, default) method that makes it possible to initialize correctly our values.

Body:
I am trying to find the durations of all the notes with the same name in a music piece (from .xml), in python. I have 3 lists:

scales = ['A', 'B', 'C'] #scales names
notesAll = ['B', 'A', 'C', 'A', 'C', 'C']  #note names of the piece
durationsAll = [1, 1.5, 1.5, 1, 1, 2]  #duration of each note from notesAll list

I want to sum all the durations from durationsAll list for all the notes with the same name. For example for all the 'A's from notesAll list, which equals to scales[0], I want something like: durationsAll[1] + durationsAll[3]= 1.5 + 1 = 2.5. I need a better solution than my attempt:

for sc in scales:
  for ntPosition, nt in enumerate(notesAll):
    dtOfEach = 0
    for dtPosition, dt in enumerate(durationsAll):
      if sc == nt:
        dtPosotion = ntPosition  #I guess here is the problem
        dtOfEach = dtOfEach + dt

The result I want would be: dtOfEach: 2.5  1  4.5

Body:
It can be done with a list comprehension, exploiting the idea that booleans behave like integers

In [3]: S = ['A', 'B', 'C'] #scales names
   ...: N = ['B', 'A', 'C', 'A', 'C', 'C']  #note names of the piece
   ...: D = [1, 1.5, 1.5, 1, 1, 2]  #duration of each note from notesAll list
In [4]: [sum(match*d for match, d in zip((n==s for n in N), D)) for s in S]
Out[4]: [2.5, 1.0, 4.5]

If you need a dictionary

In [5]: {s:sum(match*d for match, d in zip((n==s for n in N), D)) for s in S}
Out[5]: {'A': 2.5, 'B': 1.0, 'C': 4.5}

or, avoiding one loop and w/o importing collections

In [6]: r = {}
In [7]: for n, d  in zip(N, D): r[n] = r.get(n, 0) + d
In [8]: r
Out[8]: {'A': 2.5, 'B': 1, 'C': 4.5}

where we access the data in the dictionary not  by indexing but using the dictionary .get(key, default) method that makes it possible to initialize correctly our values.


问:
Placing an imageview at the center of the layout regardless of screen size?
I am new to Android and so this is me experimenting with my layouts. I want to place an imageview at the center of the layout screen and it should be at the center regardless of device size or resolutions. Additionally, the imageview should automatically scale up in size depending on the device sizes. How should I go about it ?

This is what I tried so far.

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.inducesmile.androidcameraapi2.AndroidCameraApi">
    <TextureView
        android:id="@+id/texture"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/btn_takepicture"
        android:layout_alignParentTop="true"/>
    <Button
        android:id="@+id/btn_takepicture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="16dp"
        android:layout_marginTop="16dp"
        android:text="take_picture" />

    <ImageView
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:id="@+id/imageView"
        android:layout_alignParentTop="true"
        android:layout_alignEnd="@+id/btn_takepicture"
        android:layout_marginTop="140dp"
        android:src="@drawable/rectangle" />
</RelativeLayout>
</code>```

答:
Try this code.

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.inducesmile.androidcameraapi2.AndroidCameraApi">
    <TextureView
        android:id="@+id/texture"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/btn_takepicture"
        android:layout_alignParentTop="true"/>
    <Button
        android:id="@+id/btn_takepicture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="16dp"
        android:layout_marginTop="16dp"
        android:text="take_picture" />

    <ImageView
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:id="@+id/imageView"
        android:layout_alignParentTop="true"
     android:layout_centerHorizontal="true"
        android:layout_alignEnd="@+id/btn_takepicture"
        android:layout_marginTop="140dp"
        android:src="@drawable/rectangle" />
</RelativeLayout>
</code>```

I've added this line in your imageView android:layout_centerHorizontal="true"

Body:
I am new to Android and so this is me experimenting with my layouts. I want to place an imageview at the center of the layout screen and it should be at the center regardless of device size or resolutions. Additionally, the imageview should automatically scale up in size depending on the device sizes. How should I go about it ?

This is what I tried so far.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.inducesmile.androidcameraapi2.AndroidCameraApi">
    <TextureView
        android:id="@+id/texture"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/btn_takepicture"
        android:layout_alignParentTop="true"/>
    <Button
        android:id="@+id/btn_takepicture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="16dp"
        android:layout_marginTop="16dp"
        android:text="take_picture" />

    <ImageView
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:id="@+id/imageView"
        android:layout_alignParentTop="true"
        android:layout_alignEnd="@+id/btn_takepicture"
        android:layout_marginTop="140dp"
        android:src="@drawable/rectangle" />
</RelativeLayout>

Body:
Try this code.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.inducesmile.androidcameraapi2.AndroidCameraApi">
    <TextureView
        android:id="@+id/texture"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/btn_takepicture"
        android:layout_alignParentTop="true"/>
    <Button
        android:id="@+id/btn_takepicture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="16dp"
        android:layout_marginTop="16dp"
        android:text="take_picture" />

    <ImageView
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:id="@+id/imageView"
        android:layout_alignParentTop="true"
     android:layout_centerHorizontal="true"
        android:layout_alignEnd="@+id/btn_takepicture"
        android:layout_marginTop="140dp"
        android:src="@drawable/rectangle" />
</RelativeLayout>

I've added this line in your imageView android:layout_centerHorizontal="true"


问:
iPhone Remote Audio Unit callback
I am looking at Audio Unit Development Fundamentals. Assuming

```<code>   UInt32 sessionCategory = kAudioSessionCategory_PlayAndRecord;
   status = AudioSessionSetProperty(
            kAudioSessionProperty_AudioCategory,
            sizeof(sessionCategory),
            &sessionCategory);
</code>```

with sample rate 44,1000 and allocate the buffer large enough to hold 1 second recording

How often the recording callback method will be called?

Once per second?

What's the algorithm to decide to call the callback method?

Thanks in advance for your help

答:
Assuming that you haven't set the kAudioUnitProperty_MaximumFramesPerSlice property on the Audio Unit in question, a render cycle will execute (thus calling your callback) once every FRAMES_PER_SLICE / SAMPLE_RATE seconds.  At 44.1kHz, and with the default maximum frames per slice of 1024, this works out to 1024 / 44100, or ~0.023 seconds / ~23 milliseconds.  That's just over 43 times per second.

I'm not sure about your third question.  Are you asking how the Audio Unit determines internally whether or not to call (one of) its callback(s)?

ContentLicense: CC BY-SA 2.5

Title: iPhone Remote Audio Unit callback

Body:
I am looking at Audio Unit Development Fundamentals. Assuming

   UInt32 sessionCategory = kAudioSessionCategory_PlayAndRecord;
   status = AudioSessionSetProperty(
            kAudioSessionProperty_AudioCategory,
            sizeof(sessionCategory),
            &sessionCategory);

with sample rate 44,1000 and allocate the buffer large enough to hold 1 second recording

How often the recording callback method will be called?

Once per second?

What's the algorithm to decide to call the callback method?

Thanks in advance for your help


问:
Hosting react app on aws S3
I am trying to host my static application on aws s3 bucket. I have put my build folder files in bucket. It looks like this

But when I go to .s3-website..amazonaws.com index.jade gets downloaded instead of webapp getting opened.

I followed this tutorial https://www.fullstackreact.com/articles/deploying-a-react-app-to-s3/

How can I get my web app work?

Update:

When I changed content type of index.jade to text/html, the browser shows html text like this

Here is how I edit metadata key in aws console

now there is no download. But still web page is not getting served.

答:
You need to enable static site hosting on your S3 bucket. To enable website hosting for an Amazon S3 bucket

Sign in to the AWS Management Console and open the Amazon S3 console at https://console.aws.amazon.com/s3/.

In the list, choose the bucket that you want to use for your hosted website.

Choose the Properties tab.

Choose Static website hosting, and then choose Use this bucket to host a website.

You are prompted to provide the index document and any optional error documents and redirection rules that are needed.

Make sure to keep your bucket ACL as public. Also you need to parse your jade files to html.

Title: Hosting react app on aws S3


问:
Need help accessing the assets folder in Code Igniter 3
I am working with Code Igniter 3. I kept all the assets file in the root folder like I normally do. However, I needed to move all the files inside a different folder, let me explain:

BEFORE

user.php was in : %root%\application\views\

admin-panel.php was in : %root%\application\views\

And the assets in: %root%\assets

NOW

user.php file is inside a folder: %root%\application\views\usr\

admin-panel.php was in : %root%\application\views\adm

And the assets is in: %root%\assets

I know I can access the asset files from adm or the usr folders by simply changing assets/anything.extension to ../assets/anything.extension

Or by copy-pasting the assets folder in both the directories (which I don't want to do)

However, I have already finished the designs and it will be very time consuming to do that so I would like to know if there's any other way to let the files in adm or usr access the files inside assets by maybe using route.php or .htaccess something?

答:
you need to add base path and assets path in config file.

i am providing some configuration. Follow these steps

Go-To application\config\config.php

add these code (configure base url and assets path)

```<code>$config['base_url'] = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "https" : "http");
$config['base_url'] .= "://".$_SERVER['HTTP_HOST'];
$config['base_url'] .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);

define('ASSET_PATH',$config['base_url'].'assets/');
</code>```

and finally you can used in link like this

```<code><a href="<?php echo base_url('index.php/yourController/yourFunction'); ?>">Any Link</a>
</code>```

for assets (like img)

```<code><img src="<?php echo base_url(); ?>assets/img/logo.png" alt="">
</code>```

You can get js, css files like this

```<code><link href="<?php echo ASSET_PATH; ?>css/bootstrap.min.css" rel="stylesheet">

<script src="<?php echo ASSET_PATH; ?>js/jquery.min.js"></script>
</code>```

Body:
you need to add base path and assets path in config file.

i am providing some configuration. Follow these steps

Go-To application\config\config.php

add these code (configure base url and assets path)

$config['base_url'] = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "https" : "http");
$config['base_url'] .= "://".$_SERVER['HTTP_HOST'];
$config['base_url'] .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);

define('ASSET_PATH',$config['base_url'].'assets/');

and finally you can used in link like this

<a href="<?php echo base_url('index.php/yourController/yourFunction'); ?>">Any Link</a>

for assets (like img)

<img src="<?php echo base_url(); ?>assets/img/logo.png" alt="">

You can get js, css files like this

<link href="<?php echo ASSET_PATH; ?>css/bootstrap.min.css" rel="stylesheet">

<script src="<?php echo ASSET_PATH; ?>js/jquery.min.js"></script>


问:
Redirect users to location on google map with coordinates
I've coordinates on a mobile web application. I'm trying to allow the user to click a button so the app will redirect the user to Google Maps with the coordinates.

Can I simply pass in the coordinates as a query string to the google maps url?

答:
You can pass parameters in URL with ?q=X,Y

https://www.google.co.uk/maps/dir//51.917168,-0.227051/@51.917168,-0.2292397,17z


问:
CSS3 specifications on w3.org
http://www.w3.org/TR/css3-roadmap/

Hasn't CSS3 been out since a while now? Why is most of the specification not complete?

Is there a complete reference anywhere on the web (or in a book)?

答: CSS 2.1 was finalized only a couple of years ago. As Hogan said, this could take 10 years. CSS3 was introduced just a few years ago itself. Standards are based on implementation, not invention. </p>

Title: CSS3 specifications on w3.org


问:
Change URL of the twitter 'share button'
I want to add a URL to a Twitter "share button" which points to a section of the target page.

I am using this code:

```<code><div>
<a class="twitter-share-button" href="https://twitter.com/intent/tweet?text=The process...random text. mezet.xyz/dl18/manifesto/#section" data-size="large">
Tweet</a>
</div>
</code>```

答:
Hope it is what you where looking for. If you want to post a tweet with an url to take you to a certain section of the page linking an id , for twiiter you cant use # in the url, manipulating the # tag use the following.

Add : %23 as an # tag

    Tweet

```

Run code snippt, right click on "Tweet" and open link in new tab. You will see the URL with the # tag added.

Body:
I want to add a URL to a Twitter "share button" which points to a section of the target page.

I am using this code:

Tweet

Body:
Hope it is what you where looking for. If you want to post a tweet with an url to take you to a certain section of the page linking an id , for twiiter you cant use # in the url, manipulating the # tag use the following.

Add : %23 as an # tag

<div>
    <a class="twitter-share-button" href="https://twitter.com/intent/tweet?text=The process...of this is just total dummy text to test if i can manupilate the url. http://mezet.xyz/dl18/manifesto/%23priorities-section " data-size="large">Tweet</a>
</div>

Run code snippt, right click on "Tweet" and open link in new tab. You will see the URL with the # tag added.


问:
Is contextlib.closing() thread safe - Python
I read about with statement in Python & understood that with statement will make sure to close resources on completion of job.

I m performing some DB operation & managing connection using with statement. But, I am not sure about thread safety.

```<code>with contextlib.closing(sqlite3.connect(self.dbName)) as connection:
    # Do Something
</code>```

I also read about threading using with like

```<code>lock = threading.Lock()
with lock:
    #Do Something
</code>```

I want to know whether context.closing() is able to handle multithreading or do I have to call threading.Lock() & do locking in addition to context.closing() like

```<code>lock = threading.Lock()
with lock:
    with contextlib.closing(sqlite3.connect(self.dbName)) as connection:
        # Do Something
</code>```

答:
contextlib.closing has nothing to do with threads and thread locks apart from both being able to utilize the with ... syntax. It's essentially a convenience shorthand for:

```<code>try:
    connection = sqlite3.connect(self.dbName)
    # code within the `with` block
    connection.close()
except:
    connection.close()
</code>```

So if you want whatever you're executing within a contextlib.closing, hmm, context to have an exclusive thread access, you'll have to use a threading.Lock (or threading.RLock) to ensure it.

Keep in mind that the order or nesting matters as:

```<code>with lock:
    with contextlib.closing(sqlite3.connect(self.dbName)) as connection:
        # Do Something
</code>```

Ensures that only a single thread can obtain a connection at a time and Do Something, while:

```<code>with contextlib.closing(sqlite3.connect(self.dbName)) as connection:
    with lock:
        # Do Something
</code>```

Means that any thread can get a connection, but only a single thread can Do Something at one time.

P.S. To avoid nesting hell, you can stack your with statements together as:

```<code>with lock, contextlib.closing(sqlite3.connect(self.dbName)) as connection:
    # Do Somehing
</code>```

The first statement takes the precedent just as if you were nesting them.

Body:
I read about with statement in Python & understood that with statement will make sure to close resources on completion of job.

I m performing some DB operation & managing connection using with statement. But, I am not sure about thread safety.

with contextlib.closing(sqlite3.connect(self.dbName)) as connection:
    # Do Something

I also read about threading using with like

lock = threading.Lock()
with lock:
    #Do Something

I want to know whether context.closing() is able to handle multithreading or do I have to call threading.Lock() & do locking in addition to context.closing() like

lock = threading.Lock()
with lock:
    with contextlib.closing(sqlite3.connect(self.dbName)) as connection:
        # Do Something

Body:
contextlib.closing has nothing to do with threads and thread locks apart from both being able to utilize the with ... syntax. It's essentially a convenience shorthand for:

try:
    connection = sqlite3.connect(self.dbName)
    # code within the `with` block
    connection.close()
except:
    connection.close()

So if you want whatever you're executing within a contextlib.closing, hmm, context to have an exclusive thread access, you'll have to use a threading.Lock (or threading.RLock) to ensure it.

Keep in mind that the order or nesting matters as:

with lock:
    with contextlib.closing(sqlite3.connect(self.dbName)) as connection:
        # Do Something

Ensures that only a single thread can obtain a connection at a time and Do Something, while:

with contextlib.closing(sqlite3.connect(self.dbName)) as connection:
    with lock:
        # Do Something

Means that any thread can get a connection, but only a single thread can Do Something at one time.

P.S. To avoid nesting hell, you can stack your with statements together as:

with lock, contextlib.closing(sqlite3.connect(self.dbName)) as connection:
    # Do Somehing

The first statement takes the precedent just as if you were nesting them.


问:
CMake - OpenCV - cannot find -lDisplayImage
I'm trying to build a project on C++ with opencv using Cmake. But there is an error that I couldn't able to solve. I have searched a lot but found nothing.

Note:

I am beginner to OpenCV. So I don't even know why this library required. Just doing same insructions with a website.

Error is /usr/bin/ld: cannot find -lDisplayImage.

My code:

```<code>#include <opencv2/opencv.hpp>

using namespace cv;

int main()
{
    // read image
    Mat img = imread("foo.jpg", CV_LOAD_IMAGE_UNCHANGED);

    // show it in the window
    imshow("Window Name",img);

    waitKey();
}
</code>```

My CMakeLists.txt:

```<code>cmake_minimum_required(VERSION 3.8)
project(image_processing)

find_package( OpenCV REQUIRED )

set(CMAKE_CXX_STANDARD 11)

set(SOURCE_FILES main.cpp)
add_executable(image_processing ${SOURCE_FILES})
target_link_libraries( image_processing DisplayImage ${OpenCV_LIBS} )
</code>```

My compile output:

```<code>[ 50%] Linking CXX executable image_processing
/usr/bin/ld: cannot find -lDisplayImage
collect2: error: ld returned 1 exit status
CMakeFiles/image_processing.dir/build.make:137: recipe for target 'image_processing' failed
make[3]: *** [image_processing] Error 1
CMakeFiles/Makefile2:67: recipe for target 'CMakeFiles/image_processing.dir/all' failed
make[2]: *** [CMakeFiles/image_processing.dir/all] Error 2
CMakeFiles/Makefile2:79: recipe for target 'CMakeFiles/image_processing.dir/rule' failed
make[1]: *** [CMakeFiles/image_processing.dir/rule] Error 2
Makefile:118: recipe for target 'image_processing' failed
make: *** [image_processing] Error 2
</code>```

Output of ld -ldisplayimage --verbose command:

```<code>attempt to open //usr/local/lib/x86_64-linux-gnu/libdisplayimage.so failed
attempt to open //usr/local/lib/x86_64-linux-gnu/libdisplayimage.a failed
attempt to open //lib/x86_64-linux-gnu/libdisplayimage.so failed
attempt to open //lib/x86_64-linux-gnu/libdisplayimage.a failed
attempt to open //usr/lib/x86_64-linux-gnu/libdisplayimage.so failed
attempt to open //usr/lib/x86_64-linux-gnu/libdisplayimage.a failed
attempt to open //usr/local/lib64/libdisplayimage.so failed
attempt to open //usr/local/lib64/libdisplayimage.a failed
attempt to open //lib64/libdisplayimage.so failed
attempt to open //lib64/libdisplayimage.a failed
attempt to open //usr/lib64/libdisplayimage.so failed
attempt to open //usr/lib64/libdisplayimage.a failed
attempt to open //usr/local/lib/libdisplayimage.so failed
attempt to open //usr/local/lib/libdisplayimage.a failed
attempt to open //lib/libdisplayimage.so failed
attempt to open //lib/libdisplayimage.a failed
attempt to open //usr/lib/libdisplayimage.so failed
attempt to open //usr/lib/libdisplayimage.a failed
attempt to open //usr/x86_64-linux-gnu/lib64/libdisplayimage.so failed
attempt to open //usr/x86_64-linux-gnu/lib64/libdisplayimage.a failed
attempt to open //usr/x86_64-linux-gnu/lib/libdisplayimage.so failed
attempt to open //usr/x86_64-linux-gnu/lib/libdisplayimage.a failed
ld: cannot find -ldisplayimage
</code>```

I tried to find that library but I couldn't able to find. I checked all of my lib folders.

My opencv installed on /opt/opencv/ and built on /opt/opencv/release/.

Thanks for any help. I don't know anything about how to solve it.

答:
This happens when you copy and paste from examples without understanding them well. The problem is in the CMakeLists.txt

you have

```<code>cmake_minimum_required(VERSION 3.8)
project(image_processing)

find_package( OpenCV REQUIRED )

set(CMAKE_CXX_STANDARD 11)

set(SOURCE_FILES main.cpp)
add_executable(image_processing ${SOURCE_FILES})
target_link_libraries( image_processing DisplayImage ${OpenCV_LIBS} )
</code>```

I will go line by line here. First it checks that you have a minimum cmake version (to make sure some of the functions afterwards are valid), then is the name of the project obviously, it can be whatever you want. Then you find OpenCV library and this sets several variables (includes, libs, etc). Then you set c++11 standard and your source files, in this case it is just 1 for THIS executable (you can put as many as you need to, the same with .h if needed).

Finally the important part, add_executable which you pass 2 arguments, the name of the executable (it can be whatever) and the sourcefiles... you can even write the source file manually instead of setting them into a variable first. After that you say which libraries are going to be linked to your executable... here is where you have the error!! You have to put as first argument the same name of the executable you declare before, followed by the libraries used. When you did find_package(OpenCV REQUIRED) it set the libraries name in $(OpenCV_LIBS) variable. If you need another library you can put the name manually and it will link it while compiling it. In this case you have the name DisplayImage, and it thinks it is a library name and tries to link it, this means -lDisplayImage while compiling.

This means that you remove this and it should compile :)

```<code>target_link_libraries( image_processing  ${OpenCV_LIBS} )
</code>```

Also, after finding the OpenCV package I would recommend you to do

```<code>include_directories( ${OpenCV_INCLUDE_DIRS} )
</code>```

This will make sure the include folder is added to the compilation. Equivalent in gcc to the -Ifolder/path option. If you have to include more folders from different libraries project, you can use this command.

I hope this helps you.

Body:
I'm trying to build a project on C++ with opencv using Cmake. But there is an error that I couldn't able to solve. I have searched a lot but found nothing.

Note:

I am beginner to OpenCV. So I don't even know why this library required. Just doing same insructions with a website.

Error is /usr/bin/ld: cannot find -lDisplayImage.

My code:

#include <opencv2/opencv.hpp>

using namespace cv;

int main()
{
    // read image
    Mat img = imread("foo.jpg", CV_LOAD_IMAGE_UNCHANGED);

    // show it in the window
    imshow("Window Name",img);

    waitKey();
}

My CMakeLists.txt:

cmake_minimum_required(VERSION 3.8)
project(image_processing)

find_package( OpenCV REQUIRED )

set(CMAKE_CXX_STANDARD 11)

set(SOURCE_FILES main.cpp)
add_executable(image_processing ${SOURCE_FILES})
target_link_libraries( image_processing DisplayImage ${OpenCV_LIBS} )

My compile output:

[ 50%] Linking CXX executable image_processing
/usr/bin/ld: cannot find -lDisplayImage
collect2: error: ld returned 1 exit status
CMakeFiles/image_processing.dir/build.make:137: recipe for target 'image_processing' failed
make[3]: *** [image_processing] Error 1
CMakeFiles/Makefile2:67: recipe for target 'CMakeFiles/image_processing.dir/all' failed
make[2]: *** [CMakeFiles/image_processing.dir/all] Error 2
CMakeFiles/Makefile2:79: recipe for target 'CMakeFiles/image_processing.dir/rule' failed
make[1]: *** [CMakeFiles/image_processing.dir/rule] Error 2
Makefile:118: recipe for target 'image_processing' failed
make: *** [image_processing] Error 2

Output of ld -ldisplayimage --verbose command:

attempt to open //usr/local/lib/x86_64-linux-gnu/libdisplayimage.so failed
attempt to open //usr/local/lib/x86_64-linux-gnu/libdisplayimage.a failed
attempt to open //lib/x86_64-linux-gnu/libdisplayimage.so failed
attempt to open //lib/x86_64-linux-gnu/libdisplayimage.a failed
attempt to open //usr/lib/x86_64-linux-gnu/libdisplayimage.so failed
attempt to open //usr/lib/x86_64-linux-gnu/libdisplayimage.a failed
attempt to open //usr/local/lib64/libdisplayimage.so failed
attempt to open //usr/local/lib64/libdisplayimage.a failed
attempt to open //lib64/libdisplayimage.so failed
attempt to open //lib64/libdisplayimage.a failed
attempt to open //usr/lib64/libdisplayimage.so failed
attempt to open //usr/lib64/libdisplayimage.a failed
attempt to open //usr/local/lib/libdisplayimage.so failed
attempt to open //usr/local/lib/libdisplayimage.a failed
attempt to open //lib/libdisplayimage.so failed
attempt to open //lib/libdisplayimage.a failed
attempt to open //usr/lib/libdisplayimage.so failed
attempt to open //usr/lib/libdisplayimage.a failed
attempt to open //usr/x86_64-linux-gnu/lib64/libdisplayimage.so failed
attempt to open //usr/x86_64-linux-gnu/lib64/libdisplayimage.a failed
attempt to open //usr/x86_64-linux-gnu/lib/libdisplayimage.so failed
attempt to open //usr/x86_64-linux-gnu/lib/libdisplayimage.a failed
ld: cannot find -ldisplayimage

I tried to find that library but I couldn't able to find. I checked all of my lib folders.

My opencv installed on /opt/opencv/ and built on /opt/opencv/release/.

Thanks for any help. I don't know anything about how to solve it.

Body:
This happens when you copy and paste from examples without understanding them well. The problem is in the CMakeLists.txt

you have

cmake_minimum_required(VERSION 3.8)
project(image_processing)

find_package( OpenCV REQUIRED )

set(CMAKE_CXX_STANDARD 11)

set(SOURCE_FILES main.cpp)
add_executable(image_processing ${SOURCE_FILES})
target_link_libraries( image_processing DisplayImage ${OpenCV_LIBS} )

I will go line by line here. First it checks that you have a minimum cmake version (to make sure some of the functions afterwards are valid), then is the name of the project obviously, it can be whatever you want. Then you find OpenCV library and this sets several variables (includes, libs, etc). Then you set c++11 standard and your source files, in this case it is just 1 for THIS executable (you can put as many as you need to, the same with .h if needed).

Finally the important part, add_executable which you pass 2 arguments, the name of the executable (it can be whatever) and the sourcefiles... you can even write the source file manually instead of setting them into a variable first. After that you say which libraries are going to be linked to your executable... here is where you have the error!! You have to put as first argument the same name of the executable you declare before, followed by the libraries used. When you did find_package(OpenCV REQUIRED) it set the libraries name in $(OpenCV_LIBS) variable. If you need another library you can put the name manually and it will link it while compiling it. In this case you have the name DisplayImage, and it thinks it is a library name and tries to link it, this means -lDisplayImage while compiling.

This means that you remove this and it should compile :)

target_link_libraries( image_processing  ${OpenCV_LIBS} )

Also, after finding the OpenCV package I would recommend you to do

include_directories( ${OpenCV_INCLUDE_DIRS} )

This will make sure the include folder is added to the compilation. Equivalent in gcc to the -Ifolder/path option. If you have to include more folders from different libraries project, you can use this command.

I hope this helps you.


问:
Why does Traefik not proxy new services in a Docker Swarm?
I try to setup traefik with a Docker Swarm. I have to VMs - one manger-node and one worker-node.
In addition I have created a external network with:

```<code>docker network create --driver=overlay proxy-net
</code>```

I start traefik as a service within my manager-node with the following docker-compose.yml file:

```<code>version: '3'

services:
  traefik:
     image: traefik:v1.4.4
     volumes:
       - /var/run/docker.sock:/var/run/docker.sock
       - $PWD/management/traefik/traefik.toml:/etc/traefik/traefik.toml
     ports:
       - 80:80
       - 8100:8080
     deploy:
       placement:
         constraints:
           - node.role == manager

networks:
   default:
    external:
      name:  proxy-net
</code>```

My traefik.toml file looks like this:

```<code>Debug : "DEBUG"
defaultEntryPoints = ["http"]
[entryPoints]
    [entryPoints.http]
    address = ":80"

[web]
address = ":8080"

[docker]
watch = true
swarmmode = true
domain = "mydomain.com"
exposedbydefault = true
</code>```

When I now start a new service (e.g. emilevauge/whoami) with:

```<code>docker service create \
    --name whoami1 \
    --publish mode=host,target=80,published=8002 \
    --network proxy-net \
    --label traefik.docker.network=proxy-net \
    --label traefik.frontend.rule=Host:whoami.mydomain.com \
    --label traefik.port=8002 \
    emilevauge/whoami
</code>```

The service is seen by the traefik web frontend. So at first every thing looks fine. I can access the service directly on my worker node on port 8002.
But traefik does not seem to be able to proxy this service. When I browse my endpoint URL (whomai.mydomain.com) I get the answer:

```<code>Bad Gateway
</code>```

The traefik logfile (logLevel=DEBUG) shown messages like this:

```<code>proxy_traefik.1.zl50yv6got5f@tocidoc001 time="2017-12-03T20:09:28Z" level=debug msg="Filtering container without port and no traefik.port label swarmpit_app.1 : strconv.Atoi: parsing "": invalid syntax"
proxy_traefik.1.zl50yv6got5f@tocidoc001 time="2017-12-03T20:09:28Z" level=debug msg="Filtering container without port and no traefik.port label proxy_traefik.1 : strconv.Atoi: parsing "": invalid syntax"
proxy_traefik.1.zl50yv6got5f@tocidoc001 time="2017-12-03T20:09:28Z" level=debug msg="Filtering container without port and no traefik.port label swarmpit_db.1 : strconv.Atoi: parsing "": invalid syntax"
proxy_traefik.1.zl50yv6got5f@tocidoc001 time="2017-12-03T20:09:28Z" level=debug msg="Validation of load balancer method for backend backend-whoami1-whoami1-whoami1 failed: invalid load-balancing method ''. Using default method wrr."
proxy_traefik.1.zl50yv6got5f@tocidoc001 time="2017-12-03T20:09:28Z" level=debug msg="Configuration received from provider docker: {"backends":{"backend-whoami1-whoami1-whoami1":{"servers":{"service-0":{"url":"http://10.0.1.5:8002","weight":0}},"loadBalancer":{"method":"wrr"}}},"frontends":{"frontend-whoami1-whoami1-whoami1":{"entryPoints":["http"],"backend":"backend-whoami1-whoami1-whoami1","routes":{"service-whoami1":{"rule":"Host:whoami.mydomain.com"}},"passHostHeader":true,"priority":0,"basicAuth":[],"headers":{}}}}"
</code>```

I played around several hours with different configurations. I also read the very concise documentation about traefik and docker-swarm. But I don't get any idea what I'm doing wrong.

Can any body help me with some tips how to better understand the problem?

答:
I finally I solved this issue. It was actually not a Traefik problem.
The problem was, that both VMs from my provider have  the same private IPv4 address.
To register and join the docker-swarm  it is important to provide the public IPv4 addresses with the option --advertise-addr

To register the swarm I have to run:

```<code>docker swarm init --advertise-addr [manager-ip-address]
</code>```

to join the swarm by a worker-node also the public IPv4 address need to be set explicitly:

```<code>docker swarm join \
 --token SWMTKN-1-xxxxxxxxxxxxxxxxxxxx-xxxxxxxx \
 --advertise-addr [worker-ip-address]\
 [manager-ip-address]:2377
</code>```

Body:
I try to setup traefik with a Docker Swarm. I have to VMs - one manger-node and one worker-node.
In addition I have created a external network with:

docker network create --driver=overlay proxy-net

I start traefik as a service within my manager-node with the following docker-compose.yml file:

version: '3'

services:
  traefik:
     image: traefik:v1.4.4
     volumes:
       - /var/run/docker.sock:/var/run/docker.sock
       - $PWD/management/traefik/traefik.toml:/etc/traefik/traefik.toml
     ports:
       - 80:80
       - 8100:8080
     deploy:
       placement:
         constraints:
           - node.role == manager

networks:
   default:
    external:
      name:  proxy-net

My traefik.toml file looks like this:

Debug : "DEBUG"
defaultEntryPoints = ["http"]
[entryPoints]
    [entryPoints.http]
    address = ":80"

[web]
address = ":8080"

[docker]
watch = true
swarmmode = true
domain = "mydomain.com"
exposedbydefault = true

When I now start a new service (e.g. emilevauge/whoami) with:

docker service create \
    --name whoami1 \
    --publish mode=host,target=80,published=8002 \
    --network proxy-net \
    --label traefik.docker.network=proxy-net \
    --label traefik.frontend.rule=Host:whoami.mydomain.com \
    --label traefik.port=8002 \
    emilevauge/whoami

The service is seen by the traefik web frontend. So at first every thing looks fine. I can access the service directly on my worker node on port 8002.
But traefik does not seem to be able to proxy this service. When I browse my endpoint URL (whomai.mydomain.com) I get the answer:

Bad Gateway

The traefik logfile (logLevel=DEBUG) shown messages like this:

proxy_traefik.1.zl50yv6got5f@tocidoc001 time="2017-12-03T20:09:28Z" level=debug msg="Filtering container without port and no traefik.port label swarmpit_app.1 : strconv.Atoi: parsing "": invalid syntax"
proxy_traefik.1.zl50yv6got5f@tocidoc001 time="2017-12-03T20:09:28Z" level=debug msg="Filtering container without port and no traefik.port label proxy_traefik.1 : strconv.Atoi: parsing "": invalid syntax"
proxy_traefik.1.zl50yv6got5f@tocidoc001 time="2017-12-03T20:09:28Z" level=debug msg="Filtering container without port and no traefik.port label swarmpit_db.1 : strconv.Atoi: parsing "": invalid syntax"
proxy_traefik.1.zl50yv6got5f@tocidoc001 time="2017-12-03T20:09:28Z" level=debug msg="Validation of load balancer method for backend backend-whoami1-whoami1-whoami1 failed: invalid load-balancing method ''. Using default method wrr."
proxy_traefik.1.zl50yv6got5f@tocidoc001 time="2017-12-03T20:09:28Z" level=debug msg="Configuration received from provider docker: {"backends":{"backend-whoami1-whoami1-whoami1":{"servers":{"service-0":{"url":"http://10.0.1.5:8002","weight":0}},"loadBalancer":{"method":"wrr"}}},"frontends":{"frontend-whoami1-whoami1-whoami1":{"entryPoints":["http"],"backend":"backend-whoami1-whoami1-whoami1","routes":{"service-whoami1":{"rule":"Host:whoami.mydomain.com"}},"passHostHeader":true,"priority":0,"basicAuth":[],"headers":{}}}}"

I played around several hours with different configurations. I also read the very concise documentation about traefik and docker-swarm. But I don't get any idea what I'm doing wrong.

Can any body help me with some tips how to better understand the problem?

Body:
I finally I solved this issue. It was actually not a Traefik problem.
The problem was, that both VMs from my provider have  the same private IPv4 address.
To register and join the docker-swarm  it is important to provide the public IPv4 addresses with the option --advertise-addr

To register the swarm I have to run:

docker swarm init --advertise-addr [manager-ip-address]

to join the swarm by a worker-node also the public IPv4 address need to be set explicitly:

docker swarm join \
 --token SWMTKN-1-xxxxxxxxxxxxxxxxxxxx-xxxxxxxx \
 --advertise-addr [worker-ip-address]\
 [manager-ip-address]:2377


问:
Using pimcore in Docker environment
We are currently rolling out Pimcore 5 in our Docker Kubernetes environment but we didn't find an appropriate answer for the following question yet:

Which folders need to be persistent?

The documentation points out that the folders /var and /web/var are used to safe logs and assets (from the admin interface). Are there any other folders that need to be persistent to keep the environment stable even after a container restart / rebuild?

Are there any problems with updates or downsides if we run a setup like this:

Git Repository for our Code Base

PHP-fpm Docker image that holds the code base (plus nginx and redis container)

Consistent Database

We would also like to share our results when we managed to come up with a good solution.

Thank you very much!
I know this question is kind of specific :)

答:
Yes, /var and /web/var need to be on a persistent and shared filesystem.

Further hints regarding this setup are in the documentation:

https://pimcore.com/docs/master/Development_Documentation/Installation_and_Upgrade/System_Setup_and_Hosting/Cluster_Setup.html

https://pimcore.com/docs/4.6.x/Development_Documentation/Installation_and_Upgrade/System_Setup_and_Hosting/Amazon_AWS_Setup/index.html

Title: Using pimcore in Docker environment


问:
JavaScript grouping array with age group and find largest date
I am trying to implement something like for each age group, I wanted to find the largest date, and then compare with today's date, get the date differences and store into another separate array. Here is some sample input:

```<code>//removed
</code>```

I sorted the array into ascending order:

```<code>frequentarr.sort(function(a, b) {
    da = new Date(a.date);
    db = new Date(b.date);
    if (da == db) {
        return 0;
    }
    return da > db ? 1 : -1;
});
console.log(frequentarr);
</code>```

My age group array:

```<code>var ageGroup = ['>=80', '70-79', '60-69', '50-59', '40-49', '30-39', '20-29', '10-19', '0-9'];
</code>```

I not sure how to actually group the account according to age group, and then for each age group, find the largest date. After that, compare with today's date to find the date differences.

Any ideas? Thanks!

答:
I'd first sort the frequentarray by the date, then simply group it using reduce. I'm using a Map, so you can simply get the latest date within a age group using

```<code>m.get(<ageGroup>)[0];
</code>```

let frequentarr = [{accountID: "-Ks8mWcr2x08gEbSCSuJ", age: 67, gender: "female", brand: "Akira", date: "2017/01/09"},
    {accountID: "-Ks8mWh4j7fv7XaQyygJ", age: 11, gender: "female", brand: "Akira", date: "2017/01/14"},
    {accountID: "-Ks8mWh4j7fv7XaQyygJ", age: 11, gender: "female", brand: "Akira", date: "2017/01/14"},
    {accountID: "-Ks8mWayOns5WnK0xu3e", age: 62, gender: "male", brand: "Akira", date: "2017/01/15"},
    {accountID: "-Ks8mWYnb4fu1AT9vR8X", age: 40, gender: "male", brand: "Akira", date: "2017/01/21"},
    {accountID: "-Ks8mWf0deAAVlOSb2qS", age: 21, gender: "male", brand: "Akira", date: "2017/02/08"},
    {accountID: "-Ks8mWbH4YQhXg9DZvjG", age: 12, gender: "male", brand: "Akira", date: "2017/02/18"},
    {accountID: "-Ks8mWZpiUOt8aXyEY22", age: 56, gender: "female", brand: "Akira", date: "2017/02/29"},
    {accountID: "-Ks8mW_HvNJ3RKCz6QZk", age: 24, gender: "male", brand: "Akira", date: "2017/03/03"},
    {accountID: "-Ks8mWgBmSBh6LrsLMU4", age: 22, gender: "male", brand: "Akira", date: "2017/03/17"},
    {accountID: "-Ks8mWgceHTuJsBObl_C", age: 66, gender: "female", brand: "Akira", date: "2017/03/25"},
    {accountID: "-Ks8mWYhd7WuUGJMUTzx", age: 62, gender: "female", brand: "Akira", date: "2017/04/03"},
    {accountID: "-Ks8mWhQ-TsvAbvS0Sk2", age: 59, gender: "male", brand: "Akira", date: "2017/05/18"},
    {accountID: "-Ks8mWY4PQ3stDWTlriB", age: 39, gender: "male", brand: "Akira", date: "2017/06/14"},
    {accountID: "-Ks8mWYMZw8YTs6P-UCk", age: 19, gender: "male", brand: "Akira", date: "2017/07/03"},
    {accountID: "-Ks8mWcm1zYkSQN2fD9c", age: 31, gender: "male", brand: "Akira", date: "2017/07/10"},
    {accountID: "-Ks8mWalbiAq35e10lZy", age: 24, gender: "male", brand: "Akira", date: "2017/07/14"},
    {accountID: "-Ks8mWjmbuBtmzzJ2IPu", age: 36, gender: "female", brand: "Akira", date: "2017/07/24"},
    {accountID: "-Ks8mWjmbuBtmzzJ2IPu", age: 36, gender: "female", brand: "Akira", date: "2017/07/24"},
    {accountID: "-Ks8mWbNJ53rNuspHlQe", age: 73, gender: "male", brand: "Akira", date: "2017/08/17"},
    {accountID: "-Ks8mWcvM1-w0GAl-eHs", age: 63, gender: "male", brand: "Akira", date: "2017/10/01"},
    {accountID: "-Ks8mWhvTEp83PziAxpp", age: 16, gender: "male", brand: "Akira", date: "2017/10/14"},
    {accountID: "-Ks8mWdGfSrC-5n8ywNs", age: 70, gender: "female", brand: "Akira", date: "2017/10/18"},
    {accountID: "-Ks8mWdf0LfFKWH8-YBF", age: 29, gender: "male", brand: "Akira", date: "2017/12/03"},
    {accountID: "-Ks8mWhtA-3ExwVUWZC_", age: 15, gender: "female", brand: "Akira", date: "2017/12/07"},
    {accountID: "-Ks8mWX4R6inD83AO4rZ", age: 47, gender: "female", brand: "Akira", date: "2017/12/19"},
    {accountID: "-Ks8mWh4j7fv7XaQyygJ", age: 11, gender: "female", brand: "Akira", date: "2017/12/25"},
    {accountID: "-Ks8mWadHFzJ1VGmN60k", age: 26, gender: "male", brand: "Akira", date: "2017/12/28"}];

let ageGroups = ['80-1000', '70-79', '60-69', '50-59', '40-49', '30-39', '20-29', '10-19', '0-9'];

function getAgeRange(age) {
    return ageGroups.find(e => {
        let s = e.split('-');
        return age >= s[0] && age <= s[1];
    })
}

let m = frequentarr.sort((a,b) => new Date(b.date) - new Date(a.date)).reduce((a,b) => {
    let r = getAgeRange(b.age);
    return a.set(r, a.has(r) ? a.get(r).concat(b) : [b])
}, new Map);

console.log(m);```

Body:
I am trying to implement something like for each age group, I wanted to find the largest date, and then compare with today's date, get the date differences and store into another separate array. Here is some sample input:

//removed

I sorted the array into ascending order:

frequentarr.sort(function(a, b) {
    da = new Date(a.date);
    db = new Date(b.date);
    if (da == db) {
        return 0;
    }
    return da > db ? 1 : -1;
});
console.log(frequentarr);

My age group array:

var ageGroup = ['>=80', '70-79', '60-69', '50-59', '40-49', '30-39', '20-29', '10-19', '0-9'];

I not sure how to actually group the account according to age group, and then for each age group, find the largest date. After that, compare with today's date to find the date differences.

Any ideas? Thanks!

Body:
I'd first sort the frequentarray by the date, then simply group it using reduce. I'm using a Map, so you can simply get the latest date within a age group using

m.get(<ageGroup>)[0];

let frequentarr = [{accountID: "-Ks8mWcr2x08gEbSCSuJ", age: 67, gender: "female", brand: "Akira", date: "2017/01/09"},
    {accountID: "-Ks8mWh4j7fv7XaQyygJ", age: 11, gender: "female", brand: "Akira", date: "2017/01/14"},
    {accountID: "-Ks8mWh4j7fv7XaQyygJ", age: 11, gender: "female", brand: "Akira", date: "2017/01/14"},
    {accountID: "-Ks8mWayOns5WnK0xu3e", age: 62, gender: "male", brand: "Akira", date: "2017/01/15"},
    {accountID: "-Ks8mWYnb4fu1AT9vR8X", age: 40, gender: "male", brand: "Akira", date: "2017/01/21"},
    {accountID: "-Ks8mWf0deAAVlOSb2qS", age: 21, gender: "male", brand: "Akira", date: "2017/02/08"},
    {accountID: "-Ks8mWbH4YQhXg9DZvjG", age: 12, gender: "male", brand: "Akira", date: "2017/02/18"},
    {accountID: "-Ks8mWZpiUOt8aXyEY22", age: 56, gender: "female", brand: "Akira", date: "2017/02/29"},
    {accountID: "-Ks8mW_HvNJ3RKCz6QZk", age: 24, gender: "male", brand: "Akira", date: "2017/03/03"},
    {accountID: "-Ks8mWgBmSBh6LrsLMU4", age: 22, gender: "male", brand: "Akira", date: "2017/03/17"},
    {accountID: "-Ks8mWgceHTuJsBObl_C", age: 66, gender: "female", brand: "Akira", date: "2017/03/25"},
    {accountID: "-Ks8mWYhd7WuUGJMUTzx", age: 62, gender: "female", brand: "Akira", date: "2017/04/03"},
    {accountID: "-Ks8mWhQ-TsvAbvS0Sk2", age: 59, gender: "male", brand: "Akira", date: "2017/05/18"},
    {accountID: "-Ks8mWY4PQ3stDWTlriB", age: 39, gender: "male", brand: "Akira", date: "2017/06/14"},
    {accountID: "-Ks8mWYMZw8YTs6P-UCk", age: 19, gender: "male", brand: "Akira", date: "2017/07/03"},
    {accountID: "-Ks8mWcm1zYkSQN2fD9c", age: 31, gender: "male", brand: "Akira", date: "2017/07/10"},
    {accountID: "-Ks8mWalbiAq35e10lZy", age: 24, gender: "male", brand: "Akira", date: "2017/07/14"},
    {accountID: "-Ks8mWjmbuBtmzzJ2IPu", age: 36, gender: "female", brand: "Akira", date: "2017/07/24"},
    {accountID: "-Ks8mWjmbuBtmzzJ2IPu", age: 36, gender: "female", brand: "Akira", date: "2017/07/24"},
    {accountID: "-Ks8mWbNJ53rNuspHlQe", age: 73, gender: "male", brand: "Akira", date: "2017/08/17"},
    {accountID: "-Ks8mWcvM1-w0GAl-eHs", age: 63, gender: "male", brand: "Akira", date: "2017/10/01"},
    {accountID: "-Ks8mWhvTEp83PziAxpp", age: 16, gender: "male", brand: "Akira", date: "2017/10/14"},
    {accountID: "-Ks8mWdGfSrC-5n8ywNs", age: 70, gender: "female", brand: "Akira", date: "2017/10/18"},
    {accountID: "-Ks8mWdf0LfFKWH8-YBF", age: 29, gender: "male", brand: "Akira", date: "2017/12/03"},
    {accountID: "-Ks8mWhtA-3ExwVUWZC_", age: 15, gender: "female", brand: "Akira", date: "2017/12/07"},
    {accountID: "-Ks8mWX4R6inD83AO4rZ", age: 47, gender: "female", brand: "Akira", date: "2017/12/19"},
    {accountID: "-Ks8mWh4j7fv7XaQyygJ", age: 11, gender: "female", brand: "Akira", date: "2017/12/25"},
    {accountID: "-Ks8mWadHFzJ1VGmN60k", age: 26, gender: "male", brand: "Akira", date: "2017/12/28"}];

let ageGroups = ['80-1000', '70-79', '60-69', '50-59', '40-49', '30-39', '20-29', '10-19', '0-9'];

function getAgeRange(age) {
    return ageGroups.find(e => {
        let s = e.split('-');
        return age >= s[0] && age <= s[1];
    })
}

let m = frequentarr.sort((a,b) => new Date(b.date) - new Date(a.date)).reduce((a,b) => {
    let r = getAgeRange(b.age);
    return a.set(r, a.has(r) ? a.get(r).concat(b) : [b])
}, new Map);

console.log(m);


问:
How to cite full author name using Jabref in latex?
Hi. I am using JabRef for citation and Harvard style. I want cite the full author name in some cases. How do I do this with JabRef?

For example:

Many people defined frogs as animals (John Frank, 2000).

答:
HI

I could solve this problem in this way;
John-Frank,
This brought all the name in front of the publication year.

Cheers!!


问:
How to default set a tab on starting and set the icon color on selection of a tab
I am using a tablayout and a frame layout.

I have five tabs.

I am loading my fragments to this frame layouts.

i want my second tab to defaultly get selected always.

Also when i select a perticular tab, the icon should change the color to red(I am using png icons, which are black , is their any way to change them to red to indicate that it is selected)

```<code>xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.design.widget.TabLayout
    android:id="@+id/simple_tab_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabBackground="@color/colorWhite"
    app:tabIndicatorColor="#f00"
    app:tabSelectedTextColor="#f00"
    app:tabTextColor="#000"
    />

<FrameLayout
    android:id="@+id/fl_home"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</FrameLayout>

</LinearLayout>
</code>```

This is my MainActivity

```<code>     pb.setIcon(R.drawable.p_icon); // pb is my  TabLayout.Tab
    mb.setIcon(R.drawable.view_p_icon);
    gb.setIcon(R.drawable.c_icon);
    ptTab.setIcon(R.drawable.c_icon);

    tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

        @Override
        public void onTabSelected(TabLayout.Tab tab)
        {
            switch (tab.getPosition()) {
                case 0:
                    getSupportFragmentManager().beginTransaction().replace(R.id.fl_home, new UF()).commit();
                    break;
                case 1:
                    //getSupportFragmentManager().beginTransaction().replace(R.id.fl_home, new DF()).commit();
                    showAlertDialog("Logout?");
                    break;
                case 2:
                    //getSupportFragmentManager().beginTransaction().replace(R.id.fl_home, new SF()).commit();
                    showAlertDialog("Logout?");
                    break;
                case 3:
                    //getSupportFragmentManager().beginTransaction().replace(R.id.fl_home, new SF()).commit();
                    showAlertDialog("Logout?");
                    break;
                case 4:
                    getSupportFragmentManager().beginTransaction().replace(R.id.fl_home, new SF()).commit();
                    break;
            }
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });

}
</code>```

答:
Add code for setColorFilter method in onTabSelected() method. It will change color for image .

```<code>tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            int tabPosition = tab.getPosition();

            if (tabPosition == 0) {
                // active tabName
                imageOne.setColorFilter(getResources().getColor(R.color.redColor));
                // other deactive tabName
                imageTwo.setColorFilter(getResources().getColor(R.color.blackcolor));
                imageThree.setColorFilter(getResources().getColor(R.color.blackcolor));
                imageFour.setColorFilter(getResources().getColor(R.color.blackcolor));
            } else if (tabPosition == 1) {
                // active tabName
                imageTwo.setColorFilter(getResources().getColor(R.color.redColor));
                // other deactive tabName
                imageOne.setColorFilter(getResources().getColor(R.color.blackcolor));
                imageThree.setColorFilter(getResources().getColor(R.color.blackcolor));
                imageFour.setColorFilter(getResources().getColor(R.color.blackcolor));
            } else if (tabPosition == 2) {
                // active tabName
                imageThree.setColorFilter(getResources().getColor(R.color.redColor));
                // other deactive tabName
                imageTwo.setColorFilter(getResources().getColor(R.color.blackcolor));
                imageOne.setColorFilter(getResources().getColor(R.color.blackcolor));
                imageFour.setColorFilter(getResources().getColor(R.color.blackcolor));
            } else if (tabPosition == 3) {
                // active tabName
                imageFour.setColorFilter(getResources().getColor(R.color.redColor));
                // other deactive tabName
                imageTwo.setColorFilter(getResources().getColor(R.color.blackcolor));
                imageThree.setColorFilter(getResources().getColor(R.color.blackcolor));
                imageOne.setColorFilter(getResources().getColor(R.color.blackcolor));
            }

        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
            int tabPosition = tab.getPosition();
        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {
            int tabPosition = tab.getPosition();
        }
    });
</code>```

To select tab as default .

If use with viewPager then ,

```<code>tabLayout = (TabLayout) findViewById(R.id.tablayout);
tabLayout.setupWithViewPager(viewpager);
viewpager.setCurrentItem(0);  // set any number of tab which you want to select by default.
</code>```

If use without viewPager then ,

```<code>tabLayout = (TabLayout) findViewById(R.id.tablayout);
TabLayout.Tab tab = tabLayout.getTabAt(someIndex);  // which you want to select.
tab.select();
</code>```

Hope it Helps.

Body:
I am using a tablayout and a frame layout.

I have five tabs.

I am loading my fragments to this frame layouts.

i want my second tab to defaultly get selected always.

Also when i select a perticular tab, the icon should change the color to red(I am using png icons, which are black , is their any way to change them to red to indicate that it is selected)

xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.design.widget.TabLayout
    android:id="@+id/simple_tab_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabBackground="@color/colorWhite"
    app:tabIndicatorColor="#f00"
    app:tabSelectedTextColor="#f00"
    app:tabTextColor="#000"
    />

<FrameLayout
    android:id="@+id/fl_home"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</FrameLayout>

</LinearLayout>

This is my MainActivity

     pb.setIcon(R.drawable.p_icon); // pb is my  TabLayout.Tab
    mb.setIcon(R.drawable.view_p_icon);
    gb.setIcon(R.drawable.c_icon);
    ptTab.setIcon(R.drawable.c_icon);

    tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

        @Override
        public void onTabSelected(TabLayout.Tab tab)
        {
            switch (tab.getPosition()) {
                case 0:
                    getSupportFragmentManager().beginTransaction().replace(R.id.fl_home, new UF()).commit();
                    break;
                case 1:
                    //getSupportFragmentManager().beginTransaction().replace(R.id.fl_home, new DF()).commit();
                    showAlertDialog("Logout?");
                    break;
                case 2:
                    //getSupportFragmentManager().beginTransaction().replace(R.id.fl_home, new SF()).commit();
                    showAlertDialog("Logout?");
                    break;
                case 3:
                    //getSupportFragmentManager().beginTransaction().replace(R.id.fl_home, new SF()).commit();
                    showAlertDialog("Logout?");
                    break;
                case 4:
                    getSupportFragmentManager().beginTransaction().replace(R.id.fl_home, new SF()).commit();
                    break;
            }
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });

}

Body:
Add code for setColorFilter method in onTabSelected() method. It will change color for image .

tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            int tabPosition = tab.getPosition();

            if (tabPosition == 0) {
                // active tabName
                imageOne.setColorFilter(getResources().getColor(R.color.redColor));
                // other deactive tabName
                imageTwo.setColorFilter(getResources().getColor(R.color.blackcolor));
                imageThree.setColorFilter(getResources().getColor(R.color.blackcolor));
                imageFour.setColorFilter(getResources().getColor(R.color.blackcolor));
            } else if (tabPosition == 1) {
                // active tabName
                imageTwo.setColorFilter(getResources().getColor(R.color.redColor));
                // other deactive tabName
                imageOne.setColorFilter(getResources().getColor(R.color.blackcolor));
                imageThree.setColorFilter(getResources().getColor(R.color.blackcolor));
                imageFour.setColorFilter(getResources().getColor(R.color.blackcolor));
            } else if (tabPosition == 2) {
                // active tabName
                imageThree.setColorFilter(getResources().getColor(R.color.redColor));
                // other deactive tabName
                imageTwo.setColorFilter(getResources().getColor(R.color.blackcolor));
                imageOne.setColorFilter(getResources().getColor(R.color.blackcolor));
                imageFour.setColorFilter(getResources().getColor(R.color.blackcolor));
            } else if (tabPosition == 3) {
                // active tabName
                imageFour.setColorFilter(getResources().getColor(R.color.redColor));
                // other deactive tabName
                imageTwo.setColorFilter(getResources().getColor(R.color.blackcolor));
                imageThree.setColorFilter(getResources().getColor(R.color.blackcolor));
                imageOne.setColorFilter(getResources().getColor(R.color.blackcolor));
            }

        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
            int tabPosition = tab.getPosition();
        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {
            int tabPosition = tab.getPosition();
        }
    });

To select tab as default .

If use with viewPager then ,

tabLayout = (TabLayout) findViewById(R.id.tablayout);
tabLayout.setupWithViewPager(viewpager);
viewpager.setCurrentItem(0);  // set any number of tab which you want to select by default.

If use without viewPager then ,

tabLayout = (TabLayout) findViewById(R.id.tablayout);
TabLayout.Tab tab = tabLayout.getTabAt(someIndex);  // which you want to select.
tab.select();

Hope it Helps.


问:
Using Xamarin.Forms with Native pages (Xamarin.iOS, UWP)
I already have a solution which consist of Xamarin.iOS and UWP. We have multiple views (Pages) in both platforms. We are using MvvmCross, so we have a common code (PCL) which consists of Viewmodels, business logic etc. Also, we have separate views (Pages) for both Xamarin.iOS and UWP.

Now I want to add Xamarin.Forms support for native pages of both projects so that we have same views for both Xamarin.iOS and UWP. We need the support of navigation (from Native to Xamarin.Forms & vice versa). I am navigating through MvvmCross navigation service.

For instance,
I have FirstFormView in Xamarin.Forms project.
I have SecondFormView in Native project (can be Xamarin.iOS or UWP).
I have ThirdFormView in Xamarin.Froms project.

I have navigated to FirstFormView (which is staring page of my application)
Now I want to go to SecondFormView (which is in native project).
And from SecondFormView  I need to go to ThirdFormView which is again in Xamarin.Forms

Is it possible to do it MvvmCross? If yes, then what steps should we follow to achieve our desired goal.

Thanks in advance.

Regards,

答:
You already have MvvmCross in your PCL project, just need to add Xamarin Form pages (XAML) for every page in platform specific project (iOS, UWP). And custom renderers for every platform.

For example:

```<code>//in xamarin forms pcl project
namespace XFormProject
{
    public class MyXFormPage : ContentPage project
    {

    }
}

// in ios project
namespace XFormProjecy.iOS
{

    [assembly:ExportRenderer(typeof(XFormProject.MyXFormPage), typeof(XFormProject.iOS.MyXFormPageIOS))]
    public class MyXFormPageIOS : PageRenderer // in iOS
    {
        // your ios native page code goes here.
    }
}
</code>```

Read more about Custom Rederers

Hope this helps :)

Body:
You already have MvvmCross in your PCL project, just need to add Xamarin Form pages (XAML) for every page in platform specific project (iOS, UWP). And custom renderers for every platform.

For example:

//in xamarin forms pcl project
namespace XFormProject
{
    public class MyXFormPage : ContentPage project
    {

    }
}

// in ios project
namespace XFormProjecy.iOS
{

    [assembly:ExportRenderer(typeof(XFormProject.MyXFormPage), typeof(XFormProject.iOS.MyXFormPageIOS))]
    public class MyXFormPageIOS : PageRenderer // in iOS
    {
        // your ios native page code goes here.
    }
}

Read more about Custom Rederers

Hope this helps :)


问:
How to use $ selector in a for loop?? Can't use $("#i")
```<code>    for (i = 0; i < 9; i++) {
    a[i] = val($("#i"));
    alert(a[i]);
    }
</code>```

UPDATE:
This code is wrong, as it selects element with id(#) 'i'. Thus cannot use "#i".

My question was:
How to iterate 'i' in the '$'selector inside for loop??

答:
You can use your variable this way :

```<code> a[i] = val($("#"+i));
</code>```

In your case, you're using 'i' as a string, not a variable.

You must use '+' to concatenate your string and your variable.

Body:
    for (i = 0; i < 9; i++) {
    a[i] = val($("#i"));
    alert(a[i]);
    }

UPDATE:
This code is wrong, as it selects element with id(#) 'i'. Thus cannot use "#i".

My question was:
How to iterate 'i' in the '$'selector inside for loop??

Body:
You can use your variable this way :

 a[i] = val($("#"+i));

In your case, you're using 'i' as a string, not a variable.

You must use '+' to concatenate your string and your variable.


问:
How to add type constraint to functors map function
I'm unable to define a Functor for my abstract class Foo[V : Monoid] that have a type constraint. this is because of the map method of Functor which takes a B parameters which is not a Monoid.

My question is how and where can I add such constraint ?

Here's a sample from what I'm trying to do :

```<code>import cats.Functor
import cats.kernel.Monoid

abstract class Foo[A : Monoid] {
  val a: A
}

object Foo {
  implicit def FooFunctor = new Functor[Foo] {
    override def map[A, B](fa: Foo[A])(f: (A) => B) = new Foo[B] {
      override val a: B = f(fa.a)
    }
  }
}
</code>```

this raise the following exception :

```<code>Error:(12, 59) could not find implicit value for evidence parameter of type cats.kernel.Monoid[B]
    override def map[A, B](fa: Foo[A])(f: (A) => B) = new Foo[B] {
</code>```

My first solution was adding the constraint in the map definition (override def map[A, B : Monoid]) but this is not legal because this will change the definition of the function in Functor and will raise the Exception :

```<code>Error:(12, 18) method map overrides nothing.
</code>```

Can anyone please help me get out of this ? any suggestion would be appreciated.

答:
I think the main problems is that You're trying to mix sub-typing with type-classes. Should be:</p>

```<code>trait Foo[A] extends Monoid[A] with Functor[A] {
  val a: A
}

trait SomeADT
case class SomeValue(a: String) extends SomeADT

object SomeADT {
  //evidence
}
</code>```

Body:
I'm unable to define a Functor for my abstract class Foo[V : Monoid] that have a type constraint. this is because of the map method of Functor which takes a B parameters which is not a Monoid.

My question is how and where can I add such constraint ?

Here's a sample from what I'm trying to do :

import cats.Functor
import cats.kernel.Monoid

abstract class Foo[A : Monoid] {
  val a: A
}

object Foo {
  implicit def FooFunctor = new Functor[Foo] {
    override def map[A, B](fa: Foo[A])(f: (A) => B) = new Foo[B] {
      override val a: B = f(fa.a)
    }
  }
}

this raise the following exception :

Error:(12, 59) could not find implicit value for evidence parameter of type cats.kernel.Monoid[B]
    override def map[A, B](fa: Foo[A])(f: (A) => B) = new Foo[B] {

My first solution was adding the constraint in the map definition (override def map[A, B : Monoid]) but this is not legal because this will change the definition of the function in Functor and will raise the Exception :

Error:(12, 18) method map overrides nothing.

Can anyone please help me get out of this ? any suggestion would be appreciated.

Body:
I think the main problems is that You're trying to mix sub-typing with type-classes. Should be:

trait Foo[A] extends Monoid[A] with Functor[A] {
  val a: A
}

trait SomeADT
case class SomeValue(a: String) extends SomeADT

object SomeADT {
  //evidence
}