问:
How can I get a button in bootstrap 4 to float right without leaving the container it's in?
I am trying to create a container in bootstrap with a button on the bottom floating on the right. Unfortunately, the button is leaving the div. Why is this happening and how can I prevent this? Here is a copy of the HTML

```<code><body>
  <div class="container">
    <p>
      ...
    </p>
    <button type="button" class="btn btn-primary float-right">Primary</button>
  </div>
</body>
</code>```

CSS

```<code>.container {
  border: 1px solid black;
}
</code>```

and a plunker: https://plnkr.co/edit/9DUn1CUj0g6NPhEmqeB9?p=preview

答:
Because the button has applied float-right it will create some out of flow.
Ref : https://www.w3.org/TR/CSS21/visuren.html#x23

Just add

```<code><div style="clear: both;"></div>
</code>```

after the <button>

.container {
  border: 1px solid black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

  <head>
    <link data-require="bootstrap@4.0.0-beta" data-semver="4.0.0-beta" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" />
    <script data-require="bootstrap@4.0.0-beta" data-semver="4.0.0-beta" src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>
    <div class="container">
      <p>
        Measured fer yer chains piracy marooned schooner snow yo-ho-ho parley furl six pounders lanyard. Snow brig Sink me rum American Main reef sails bucko pirate crow's nest Sail ho. American Main coxswain lee heave down tender brig schooner gibbet piracy rum.
      </p>

      <button type="button" class="btn btn-primary float-right">Primary</button>
      <div style="clear: both;"></div>
    </div>
  </body>

</html></code>```

Method 2 :

add overflow: hidden; to container

/* Styles go here */

.container {
  border: 1px solid black;
  overflow: hidden;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

  <head>
    <link data-require="bootstrap@4.0.0-beta" data-semver="4.0.0-beta" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" />
    <script data-require="bootstrap@4.0.0-beta" data-semver="4.0.0-beta" src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>
    <div class="container">
      <p>
        Measured fer yer chains piracy marooned schooner snow yo-ho-ho parley furl six pounders lanyard. Snow brig Sink me rum American Main reef sails bucko pirate crow's nest Sail ho. American Main coxswain lee heave down tender brig schooner gibbet piracy rum.
      </p>
      <button type="button" class="btn btn-primary float-right">Primary</button>
    </div>
  </body>

</html></code>```

Body:
I am trying to create a container in bootstrap with a button on the bottom floating on the right. Unfortunately, the button is leaving the div. Why is this happening and how can I prevent this? Here is a copy of the HTML

      ...

    <button type="button" class="btn btn-primary float-right">Primary</button>

CSS

.container {
  border: 1px solid black;
}

and a plunker: https://plnkr.co/edit/9DUn1CUj0g6NPhEmqeB9?p=preview

Body:
Because the button has applied float-right it will create some out of flow.
Ref : https://www.w3.org/TR/CSS21/visuren.html#x23

Just add

<div style="clear: both;"></div>

after the <button>

.container {
  border: 1px solid black;
}

<!DOCTYPE html>
<html>

  <head>
    <link data-require="bootstrap@4.0.0-beta" data-semver="4.0.0-beta" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" />
    <script data-require="bootstrap@4.0.0-beta" data-semver="4.0.0-beta" src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>
    <div class="container">
      <p>
        Measured fer yer chains piracy marooned schooner snow yo-ho-ho parley furl six pounders lanyard. Snow brig Sink me rum American Main reef sails bucko pirate crow's nest Sail ho. American Main coxswain lee heave down tender brig schooner gibbet piracy rum.
      </p>

      <button type="button" class="btn btn-primary float-right">Primary</button>
      <div style="clear: both;"></div>
    </div>
  </body>

</html>

Method 2 :

add overflow: hidden; to container

/* Styles go here */

.container {
  border: 1px solid black;
  overflow: hidden;
}

<!DOCTYPE html>
<html>

  <head>
    <link data-require="bootstrap@4.0.0-beta" data-semver="4.0.0-beta" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" />
    <script data-require="bootstrap@4.0.0-beta" data-semver="4.0.0-beta" src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>
    <div class="container">
      <p>
        Measured fer yer chains piracy marooned schooner snow yo-ho-ho parley furl six pounders lanyard. Snow brig Sink me rum American Main reef sails bucko pirate crow's nest Sail ho. American Main coxswain lee heave down tender brig schooner gibbet piracy rum.
      </p>
      <button type="button" class="btn btn-primary float-right">Primary</button>
    </div>
  </body>

</html>


来源: stackexchange

问:
Why does "{1: 'a', True: 'b', 1.0: 'c', 1.00: 'd'}" evaluate to "{1: 'd'}"?
When I enter the expression {1: 'a', True: 'b', 1.0: 'c', 1.00: 'd'} into the Python shell, I get back {1: 'd'}. But when I write {1: 'a', True: 'b', 1.0: 'c', 1.00: 'd'} [True], the interpreter returns me 'd'. I don't understand how this dictionary evaluation works.

答: All of the values 1, True, 1.0 and 1.00 are equal (1.0 and 1.00 are the exact same value).  So they are all considered the same key in the dictionary.  You can't have a dict with multiple equal keys.</p>

ContentLicense: CC BY-SA 3.0


答:
Python doesn't support duplicate keys in a dictionary.

In the example, all the keys are same (True==1 evaluates to True).

So Python will discard every key-value except the last one.

Title: Why does "{1: 'a', True: 'b', 1.0: 'c', 1.00: 'd'}" evaluate to "{1: 'd'}"?

Body: When I enter the expression {1: 'a', True: 'b', 1.0: 'c', 1.00: 'd'} into the Python shell, I get back {1: 'd'}. But when I write {1: 'a', True: 'b', 1.0: 'c', 1.00: 'd'} [True], the interpreter returns me 'd'. I don't understand how this dictionary evaluation works.


问:
PHP count of occurrences of characters of a string within another string
Let's say I have two strings.

```<code>$needle = 'AGUXYZ';
$haystack = 'Agriculture ID XYZ-A';
</code>```

I want to count how often characters that are in $needle occur in $haystack. In $haystack, there are the characters 'A' (twice), 'X', 'Y' and 'Z', all of which are in the needle, thus the result is supposed to be 5 (case-sensitive).

Is there any function for that in PHP or do I have to program it myself?

Thanks in advance!

答:
If you are not interested in the character distribution, you could use a Regex

```<code>echo preg_match_all("/[$needle]/", $haystack, $matches);
</code>```

which returns the number of full pattern matches (which might be zero), or FALSE if an error occurred. The solution offered by @thai above should be significantly faster though.

If the character distribution is of any importance, you can use count_chars:

```<code>$needle = 'AGUXYZ';
$haystack = 'Agriculture ID XYZ-A';

$occurences = array_intersect_key(
    count_chars($haystack, 1),
    array_flip(
        array_map('ord', str_split($needle))
    )
);
</code>```

The result would be an array with keys being the ASCII values of the character.

You can then iterate over it with

```<code>foreach($occurences as $char => $amount) {
    printf("There is %d occurences of %s\n", $amount, chr($char));
}
</code>```

You could still pass the $occurences array to array_sum to calculate the total.

ContentLicense: CC BY-SA 2.5

Body:
Let's say I have two strings.

$needle = 'AGUXYZ';
$haystack = 'Agriculture ID XYZ-A';

I want to count how often characters that are in $needle occur in $haystack. In $haystack, there are the characters 'A' (twice), 'X', 'Y' and 'Z', all of which are in the needle, thus the result is supposed to be 5 (case-sensitive).

Is there any function for that in PHP or do I have to program it myself?

Thanks in advance!

Body:
If you are not interested in the character distribution, you could use a Regex

echo preg_match_all("/[$needle]/", $haystack, $matches);

which returns the number of full pattern matches (which might be zero), or FALSE if an error occurred. The solution offered by @thai above should be significantly faster though.

If the character distribution is of any importance, you can use count_chars:

$needle = 'AGUXYZ';
$haystack = 'Agriculture ID XYZ-A';

$occurences = array_intersect_key(
    count_chars($haystack, 1),
    array_flip(
        array_map('ord', str_split($needle))
    )
);

The result would be an array with keys being the ASCII values of the character.

You can then iterate over it with

foreach($occurences as $char => $amount) {
    printf("There is %d occurences of %s\n", $amount, chr($char));
}

You could still pass the $occurences array to array_sum to calculate the total.


答:
Python uses the same equality test that the == operator uses.  All of the keys you're using (1, True, 1.0, and 1.00) compare as equal to each other.  What's happening with your dicts is it's retaining the first key, then updating the value associated with that key for all subsequent keys that compare as equal to it.  It's a bit unintuitive, since the key values are not the same (except for 1.0 and 1.00), but they are "equal".

Similarly, {1: 'd'}[True] evaluates to 'd' because True == 1.


问:
Cyclomatic complexity for some_method is too high
I have following method in controller. When i run lint i get the error
Cyclomatic complexity for some_method is too high

I checked online about it and seems like it is the way i wrote the method. How could i rewrite this method so i dont get the lint error?

```<code>  def customer_order
    if params[:customer_id].present? && !params[:order_id].present?
      render_error :not_found, 'No info found for given customer id' \
      unless @info.customer_id == params[:customer_id]
    elsif params[:order_id].present? && !params[:customer_id].present?
      render_error :not_found, 'No info found for given order id' \
      unless @info.order_id == params[:order_id]
    elsif params[:customer_id].present? && params[:order_id].present?
      render_error :not_found, 'No info found for given customer id and order id’ \
        unless @info.customer_id == params[:customer_id] &&
               @info.order_id == params[:order_id]
    end
  end
</code>```

答:
You could reduce some of the redundancy like so.</p>

```<code>def customer_order
  msg = case [params[:customer_id].present?, params[:order_id].present?]
  when [true, false]
    @info.customer_id == params[:customer_id] ?
      nil : 'No info found for given customer id'
  when [false, true]
    @info.order_id == params[:order_id] ?
      nil : 'No info found for given order id'
  when [true, true]
    @info.customer_id == params[:customer_id] && @info.order_id == params[:order_id] ?
      nil : 'No info found for given customer id and order id’
  else
    nil
  end
  render_error(:not_found, msg) if msg
end
</code>```

Body:
I have following method in controller. When i run lint i get the error
Cyclomatic complexity for some_method is too high

I checked online about it and seems like it is the way i wrote the method. How could i rewrite this method so i dont get the lint error?

  def customer_order
    if params[:customer_id].present? && !params[:order_id].present?
      render_error :not_found, 'No info found for given customer id' \
      unless @info.customer_id == params[:customer_id]
    elsif params[:order_id].present? && !params[:customer_id].present?
      render_error :not_found, 'No info found for given order id' \
      unless @info.order_id == params[:order_id]
    elsif params[:customer_id].present? && params[:order_id].present?
      render_error :not_found, 'No info found for given customer id and order id’ \
        unless @info.customer_id == params[:customer_id] &&
               @info.order_id == params[:order_id]
    end
  end

Body:
You could reduce some of the redundancy like so.

def customer_order
  msg = case [params[:customer_id].present?, params[:order_id].present?]
  when [true, false]
    @info.customer_id == params[:customer_id] ?
      nil : 'No info found for given customer id'
  when [false, true]
    @info.order_id == params[:order_id] ?
      nil : 'No info found for given order id'
  when [true, true]
    @info.customer_id == params[:customer_id] && @info.order_id == params[:order_id] ?
      nil : 'No info found for given customer id and order id’
  else
    nil
  end
  render_error(:not_found, msg) if msg
end


问:
Browserify with twitter bootstrap
There are many similar questions including answers here on stack overflow, but none of them have worked for me, so here I am asking you guys.  I appreciate everyone's time.

I recently started using gulp with browserify, and that works great.
I then tried to use browserify for the front-end using: Backbone and Bootstrap3.

things are appearing to work, until I try to require the js file that comes with Bootstrap.  I get an error in my chrome tools stating: jQuery is undefined.

I have attempted to shim it in, but I am very confused by the shim.  I am using jQuery 2.1.1, so I should not need to shim jQuery, but it exists in the shim now, as I was desperate and trying everything.  Here is my package.json and my main.js file:

--------------package.json------------------

```<code>{
  "name": "gulp-backbone",
  "version": "0.0.0",
  "description": "Gulp Backbone Bootstrap",
  "main": "main.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Rob Luton",
  "license": "ISC",

  "devDependencies": {
    "jquery": "^2.1.1",
    "backbone": "^1.1.2",
    "browserify": "^4.2.1",
    "gulp": "^3.8.6",
    "vinyl-source-stream": "^0.1.1",
    "gulp-sass": "^0.7.2",
    "gulp-connect": "^2.0.6",
    "bootstrap-sass": "^3.2.0",
    "browserify-shim": "^3.6.0"
  },

  "browser": {
    "bootstrap": "./node_modules/bootstrap-sass/assets/javascripts/bootstrap.js",
    "jQuery": "./node_modules/jquery/dist/jquery.min.js"
  },

  "browserify": {
    "transform": ["browserify-shim"]
  },

  "browserify-shim": {
    "jquery": "global:jQuery",
    "bootstrap": {
      "depends": [
        "jQuery"
      ]
    }
  }
}
</code>```

------------------------- main.js ----------------------

```<code>var shim = require('browserify-shim');
$ = require('jquery');
var Backbone = require('backbone');
Backbone.$ = $;
var bootstrap = require('bootstrap');

/* the following logs fine if I comment out the bootstrap require, otherwise I get 'jQuery undefined' */

console.log(Backbone);
$(function() {
    alert('jquery works');
});
</code>```

答:
So to make Bootstrap to work with Browserify you're going to need one of Browserify CSS transforms.

First the index.js (browserify entry)

```<code>// Bootstrap needs jQuery on the Window
window.jQuery = $  = require('jquery');
// include popper.js if you want Bootstrap tooltips
window.Popper = require('popper.js');
// include bootstrap js libs (not the CSS libs as yet)
require('bootstrap');
// then the CSS Lib
require('bootstrap/dist/css/bootstrap.css');
</code>```

NPM Installs:

```<code>npm install bootstrap@4.0.0-alpha.6 jquery popper.js
</code>```

To use tooltips globally:

Per the Bootstrap docs.

```<code>$('[data-toggle="popover"]').popover();
</code>```

I have a Browserify-Budo repo here. If you want to see it working.

Title: Browserify with twitter bootstrap

Body:
There are many similar questions including answers here on stack overflow, but none of them have worked for me, so here I am asking you guys.  I appreciate everyone's time.

I recently started using gulp with browserify, and that works great.
I then tried to use browserify for the front-end using: Backbone and Bootstrap3.

things are appearing to work, until I try to require the js file that comes with Bootstrap.  I get an error in my chrome tools stating: jQuery is undefined.

I have attempted to shim it in, but I am very confused by the shim.  I am using jQuery 2.1.1, so I should not need to shim jQuery, but it exists in the shim now, as I was desperate and trying everything.  Here is my package.json and my main.js file:

--------------package.json------------------

{
  "name": "gulp-backbone",
  "version": "0.0.0",
  "description": "Gulp Backbone Bootstrap",
  "main": "main.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Rob Luton",
  "license": "ISC",

  "devDependencies": {
    "jquery": "^2.1.1",
    "backbone": "^1.1.2",
    "browserify": "^4.2.1",
    "gulp": "^3.8.6",
    "vinyl-source-stream": "^0.1.1",
    "gulp-sass": "^0.7.2",
    "gulp-connect": "^2.0.6",
    "bootstrap-sass": "^3.2.0",
    "browserify-shim": "^3.6.0"
  },

  "browser": {
    "bootstrap": "./node_modules/bootstrap-sass/assets/javascripts/bootstrap.js",
    "jQuery": "./node_modules/jquery/dist/jquery.min.js"
  },

  "browserify": {
    "transform": ["browserify-shim"]
  },

  "browserify-shim": {
    "jquery": "global:jQuery",
    "bootstrap": {
      "depends": [
        "jQuery"
      ]
    }
  }
}

------------------------- main.js ----------------------

var shim = require('browserify-shim');
$ = require('jquery');
var Backbone = require('backbone');
Backbone.$ = $;
var bootstrap = require('bootstrap');

/* the following logs fine if I comment out the bootstrap require, otherwise I get 'jQuery undefined' */

console.log(Backbone);
$(function() {
    alert('jquery works');
});

Body:
So to make Bootstrap to work with Browserify you're going to need one of Browserify CSS transforms.

First the index.js (browserify entry)

// Bootstrap needs jQuery on the Window
window.jQuery = $  = require('jquery');
// include popper.js if you want Bootstrap tooltips
window.Popper = require('popper.js');
// include bootstrap js libs (not the CSS libs as yet)
require('bootstrap');
// then the CSS Lib
require('bootstrap/dist/css/bootstrap.css');

NPM Installs:

npm install bootstrap@4.0.0-alpha.6 jquery popper.js

To use tooltips globally:

Per the Bootstrap docs.

$('[data-toggle="popover"]').popover();

I have a Browserify-Budo repo here. If you want to see it working.


问:
Wordpress page template dont appear inside Template Dropdown List
I've just add a new custom template file on my WP theme folder.
This new template begin like my others template files :

```<code><?php
/*
Template Name: My Template Name
*/
</code>```

Strangly, this new template do not appear inside Template Dropdown List inside admin page editing.

It seem to have a WP caching issue or something like this... I've tried to clear the cookies and cache of my browser, clear my server cache, and more... but it do not work.

答:
After more than an hour searching the Web and testing many things, I've found that I need to change my theme version to let WP know the new files structure (inside style.css) :

```<code>/*
Theme Name: My Theme Name
Version: 1.0.0
*/
</code>```

TO

```<code>/*
Theme Name: My Theme Name
Version: 1.0.1
*/
</code>```

And it finally work!
Hope it will help someone else ;)

Body:
I've just add a new custom template file on my WP theme folder.
This new template begin like my others template files :

<?php
/*
Template Name: My Template Name
*/

Strangly, this new template do not appear inside Template Dropdown List inside admin page editing.

It seem to have a WP caching issue or something like this... I've tried to clear the cookies and cache of my browser, clear my server cache, and more... but it do not work.

Body:
After more than an hour searching the Web and testing many things, I've found that I need to change my theme version to let WP know the new files structure (inside style.css) :

/*
Theme Name: My Theme Name
Version: 1.0.0
*/

TO

/*
Theme Name: My Theme Name
Version: 1.0.1
*/

And it finally work!
Hope it will help someone else ;)


问:
How to properly sanitize a filename (protect against shell injection)?
What is the common practice to sanitize a filename from an outside source (e.g.: xml file) before using it within a subprocess (shell=False)?

Update:
Before sending some parsed strings around I would like to make some basic security checks. The given example uses mpg123 (a command line audioplayer) in remote mode to play a sound file.

```<code>filename = child.find("filename").text # e.g.: filename = "sound.mp3"
pid = subprocess.Popen(["mpg123"],"-R"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
command = "L "+filename+"\n"
pid.stdin.write(command.encode())
</code>```

答:
There's a couple of things I can think of.

A lightweight verification can be done if the systems are tolerant.  It may also be appropriate if there is little chance of data destruction, or compromise of sensitive data.  You can test to see if the string your given is an actual file by using os.path.isfile.

A more classic "secure" programming design would have you index the acceptable files that can be played and do a lookup based on user input.  In this way you never actually pass on user input.  It get's "filtered" by the lookup to already validated data (the accepted playable files list).

"Sanitizing" input is a black-listing type of technique.  They are always less secure than a white-listing type of technique (above). If you have no choice but to "sanitize" the data you have to understand how that data passes through your system, and any other systems you depend on.  You then have to craft rules to take into account any flaws or limitations within ALL of the systems.  You would also have to cover classic malicious input cases like data input size, unacceptable character encoding and others.

Body:
What is the common practice to sanitize a filename from an outside source (e.g.: xml file) before using it within a subprocess (shell=False)?

Update:
Before sending some parsed strings around I would like to make some basic security checks. The given example uses mpg123 (a command line audioplayer) in remote mode to play a sound file.

filename = child.find("filename").text # e.g.: filename = "sound.mp3"
pid = subprocess.Popen(["mpg123"],"-R"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
command = "L "+filename+"\n"
pid.stdin.write(command.encode())


问:
How to find the index of a missing element?
Let's say you have the following lists:

```<code>fruit_types = ["apple","pear","strawberry","mango"]
fruits = ["apple","strawberry","mango"]
</code>```

How would I write a loop that identifies that the "pear" element is missing in the
"fruits" list's 2nd index?

I do know the first step begins with:

```<code>for element in fruit_types:
    if element not in fruits:
</code>```

But I am completely lost where else to go from here.

答:
You could do:

```<code>fruit_types = ["apple","pear","strawberry","mango"]
fruits = ["apple","strawberry","mango"]
missing_elements = []
for element in fruit_types:
    if(element not in fruits):
        missing_elements.append(element)
print(missing_elements)
>>> ["pear"]
</code>```

Create an empty list, then add to that list if the element is not in fruits.

Body:
Let's say you have the following lists:

fruit_types = ["apple","pear","strawberry","mango"]
fruits = ["apple","strawberry","mango"]

How would I write a loop that identifies that the "pear" element is missing in the
"fruits" list's 2nd index?

I do know the first step begins with:

for element in fruit_types:
    if element not in fruits:

But I am completely lost where else to go from here.

Body:
You could do:

fruit_types = ["apple","pear","strawberry","mango"]
fruits = ["apple","strawberry","mango"]
missing_elements = []
for element in fruit_types:
    if(element not in fruits):
        missing_elements.append(element)
print(missing_elements)
>>> ["pear"]

Create an empty list, then add to that list if the element is not in fruits.


问:
Redux state wont propagate to component
I've been attempting to make a component using Reacts component functionality. In this case I was particularly interested in componentDidMount.

However, no matter what I try, my state wont propagate to the component.

Here is the component:

```<code>class MainPage extends React.Component
{
    componentDidMount() {
        this.props.actions.requestPosts();
    }
    render() {
        return(
            <div className="main-page">
                <PreviewList posts={this.props.posts}/>
            </div>
        );
    }
}

const mapStateToProps = state => ({
    posts: state.main_posts,
    errors: state.main_errors
});

const mapDispatchToProps = dispatch => {
    return {
        actions: {
            requestPosts: () => dispatch(requestPosts())
        }
    }
};

export default connect(mapStateToProps, mapDispatchToProps)(MainPage);
</code>```

The reducer:

```<code>export default (state = {main_posts: [], main_errors: []}, action) => {
    switch(action.type) {
        case USER_REQUESTS_POSTS_SUCCEEDED:
            return Object.assign({}, state, {
                main_posts: action.posts
            });
        case USER_REQUESTS_POSTS_FAILED:
            return Object.assign({}, state, {
                main_errors: action.errors
            });
        default:
            return state;
    }
};
</code>```

For the purpose of simplicity, I did not include the import statements. I use redux-thunk. I've tested the actions, they successfully arrive at the reducer. The new state is successfully created and returned. It simply does not arrive at the desired component however.

I have tried researching and I've only found examples of reducers that mutated the state, but I can't see anything where I mutate the state. What am I doing wrong? (Ironically the code is similiar to my other react apps that work fine).

In case it is helpful, here is my store:

```<code>export const history = createHistory();

const middleware = [
    thunk,
    routerMiddleware(history)
];

const reducers = {
    main: mainReducer,
    router: routerReducer
};

const store = createStore(
    combineReducers(reducers),
    {},
    applyMiddleware(...middleware)
);

export default store;
</code>```

EDIT: As requested, here are my actions:

```<code>export const USER_REQUESTS_POSTS_SUCCEEDED = 'user/REQUESTS/POSTS/SUCCESS';
export const USER_REQUESTS_POSTS_FAILED = 'user/REQUESTS/POSTS/FAILURE';

export const requestPosts = () => {
    return function(dispatch) {
        return fetchPosts().then(
            posts => dispatch(requestPostsSucceeded(posts)),
            errors => dispatch(requestPostsFailed(errors))
        );
    };
};

function fetchPosts() {
    return Promise.resolve([{title: 'Test Post', content_short: 'Hello World', author: 'Extremo', category: 'development', tags: ['test'], date: '15.11.17'}]);
}

export const requestPostsSucceeded = (posts) => {
    return {type: USER_REQUESTS_POSTS_SUCCEEDED, posts: posts};
};

export const requestPostsFailed = (errors) => {
    return {type: USER_REQUESTS_POSTS_FAILED, errors: errors};
};
</code>```

答:
Your mapStateToProps function should be:

```<code>function mapStateToProps(state) {
  return {
    posts: state.main.main_posts,
    errors: state.main.main_errors
  }
}
</code>```

You are passing down posts and errors as undefined currently

Title: Redux state wont propagate to component

Body:
I've been attempting to make a component using Reacts component functionality. In this case I was particularly interested in componentDidMount.

However, no matter what I try, my state wont propagate to the component.

Here is the component:

class MainPage extends React.Component
{
    componentDidMount() {
        this.props.actions.requestPosts();
    }
    render() {
        return(

                <PreviewList posts={this.props.posts}/>

        );
    }
}

const mapStateToProps = state => ({
    posts: state.main_posts,
    errors: state.main_errors
});

const mapDispatchToProps = dispatch => {
    return {
        actions: {
            requestPosts: () => dispatch(requestPosts())
        }
    }
};

export default connect(mapStateToProps, mapDispatchToProps)(MainPage);

The reducer:

export default (state = {main_posts: [], main_errors: []}, action) => {
    switch(action.type) {
        case USER_REQUESTS_POSTS_SUCCEEDED:
            return Object.assign({}, state, {
                main_posts: action.posts
            });
        case USER_REQUESTS_POSTS_FAILED:
            return Object.assign({}, state, {
                main_errors: action.errors
            });
        default:
            return state;
    }
};

For the purpose of simplicity, I did not include the import statements. I use redux-thunk. I've tested the actions, they successfully arrive at the reducer. The new state is successfully created and returned. It simply does not arrive at the desired component however.

I have tried researching and I've only found examples of reducers that mutated the state, but I can't see anything where I mutate the state. What am I doing wrong? (Ironically the code is similiar to my other react apps that work fine).

In case it is helpful, here is my store:

export const history = createHistory();

const middleware = [
    thunk,
    routerMiddleware(history)
];

const reducers = {
    main: mainReducer,
    router: routerReducer
};

const store = createStore(
    combineReducers(reducers),
    {},
    applyMiddleware(...middleware)
);

export default store;

EDIT: As requested, here are my actions:

export const USER_REQUESTS_POSTS_SUCCEEDED = 'user/REQUESTS/POSTS/SUCCESS';
export const USER_REQUESTS_POSTS_FAILED = 'user/REQUESTS/POSTS/FAILURE';

export const requestPosts = () => {
    return function(dispatch) {
        return fetchPosts().then(
            posts => dispatch(requestPostsSucceeded(posts)),
            errors => dispatch(requestPostsFailed(errors))
        );
    };
};

function fetchPosts() {
    return Promise.resolve([{title: 'Test Post', content_short: 'Hello World', author: 'Extremo', category: 'development', tags: ['test'], date: '15.11.17'}]);
}

export const requestPostsSucceeded = (posts) => {
    return {type: USER_REQUESTS_POSTS_SUCCEEDED, posts: posts};
};

export const requestPostsFailed = (errors) => {
    return {type: USER_REQUESTS_POSTS_FAILED, errors: errors};
};

Body:
Your mapStateToProps function should be:

function mapStateToProps(state) {
  return {
    posts: state.main.main_posts,
    errors: state.main.main_errors
  }
}

You are passing down posts and errors as undefined currently


问:
python3/contextlib: Converting @contextlib.contextmanager to acquire/release?
I'm using some 3rd-party code which enables locking via routines that are decorated with @contextlib.contextmanager. I'm also using large python3 code base in which we can plug in different locking software, as long as I am able to implement acquire and release methods.

I'm trying to use the 3rd-party code (without knowing how it's written) within this software structure.

To clarify what I'm looking for, suppose that one of the 3rd-party lock routines is written as a standard @contextlib.contextmanager generator, like this:

```<code>@contextlib.contextmanager
def lock(arg0, arg1):
    try:
        # This section of code corresponds to `acquire`.
        # Acquire a lock called 'lock', and then ...
        yield lock
    finally:
        # This section of code coresponds to `release`.
        # Do cleanup.
</code>```

It would normally be used like this ...

```<code>with third.party.lock(arg0, arg1):
    # Do stuff in this critical section
</code>```

But as I mentioned above, I want to write a class that has an acquire method and a release method which make use of third.party.lock, and I'd like to do it via the existing third.party.lock module, without rewriting it.

In other words, I want to write a class which looks like this ...

```<code>class LockWrapper(object):

    def __init__(self):
        # initialization

    def acquire(self):
        # Use third.party.lock to obtain a lock.
        # ??? ??? ???

    def release(self):
        # I don't know what to do here. There is no yield
        # in the `finally` section of a normal
        # @contextlib.contextmanager decorated method/
        # ??? ??? ???
</code>```

As I stated in the comments of my sample code, I don't see how to make acquire and release do anything meaningful.

It looks like I would have to steal code from the original third.party.lock module in order to accomplish this, but I'm hoping that I'm overlooking a way to do this without having to know anything about this 3rd-party code.

Am I out of luck?

Thank you very much.

答:
Why not call the contextlib wrapper's __enter__ and __exit__ explicitly?

```<code>import contextlib

# Something to wrap
class Test:
    def __init__(self):
        print('Opening Test')
    def use(self):
        print('Using Test')
    def close(self):
        print('Closing Test')

# Wrap in the standard contextlib
@contextlib.contextmanager
def test():
    try:
        t = Test()
        yield t
    finally:
        t.close()

# Does it work?  yes...
with test() as t:
    t.use()

# Implementing acquire/release...
class TestWrapper(object):
    def __init__(self):
        pass
    def acquire(self):
        self.t = test()
        return self.t.__enter__()
    def release(self):
        self.t.__exit__(None,None,None)

# Also works...
tw = TestWrapper()
t = tw.acquire()
t.use()
tw.release()
</code>```

Output:

```<code>Opening Test
Using Test
Closing Test
Opening Test
Using Test
Closing Test
</code>```

Body:
I'm using some 3rd-party code which enables locking via routines that are decorated with @contextlib.contextmanager. I'm also using large python3 code base in which we can plug in different locking software, as long as I am able to implement acquire and release methods.

I'm trying to use the 3rd-party code (without knowing how it's written) within this software structure.

To clarify what I'm looking for, suppose that one of the 3rd-party lock routines is written as a standard @contextlib.contextmanager generator, like this:

@contextlib.contextmanager
def lock(arg0, arg1):
    try:
        # This section of code corresponds to `acquire`.
        # Acquire a lock called 'lock', and then ...
        yield lock
    finally:
        # This section of code coresponds to `release`.
        # Do cleanup.

It would normally be used like this ...

with third.party.lock(arg0, arg1):
    # Do stuff in this critical section

But as I mentioned above, I want to write a class that has an acquire method and a release method which make use of third.party.lock, and I'd like to do it via the existing third.party.lock module, without rewriting it.

In other words, I want to write a class which looks like this ...

class LockWrapper(object):

    def __init__(self):
        # initialization

    def acquire(self):
        # Use third.party.lock to obtain a lock.
        # ??? ??? ???

    def release(self):
        # I don't know what to do here. There is no yield
        # in the `finally` section of a normal
        # @contextlib.contextmanager decorated method/
        # ??? ??? ???

As I stated in the comments of my sample code, I don't see how to make acquire and release do anything meaningful.

It looks like I would have to steal code from the original third.party.lock module in order to accomplish this, but I'm hoping that I'm overlooking a way to do this without having to know anything about this 3rd-party code.

Am I out of luck?

Thank you very much.

Body:
Why not call the contextlib wrapper's __enter__ and __exit__ explicitly?

import contextlib

# Something to wrap
class Test:
    def __init__(self):
        print('Opening Test')
    def use(self):
        print('Using Test')
    def close(self):
        print('Closing Test')

# Wrap in the standard contextlib
@contextlib.contextmanager
def test():
    try:
        t = Test()
        yield t
    finally:
        t.close()

# Does it work?  yes...
with test() as t:
    t.use()

# Implementing acquire/release...
class TestWrapper(object):
    def __init__(self):
        pass
    def acquire(self):
        self.t = test()
        return self.t.__enter__()
    def release(self):
        self.t.__exit__(None,None,None)

# Also works...
tw = TestWrapper()
t = tw.acquire()
t.use()
tw.release()

Output:

Opening Test
Using Test
Closing Test
Opening Test
Using Test
Closing Test


问:
Force Non-Monospace Font into Fixed Width Using CSS
Is there any way to force a font to be monospaced using CSS?

By this I mean, using a non-monospace font, can you force the browser to render each character at a fixed width?

答:
If this is for aligning digits in tables where some fonts (with traditional typography) render them by default with variable width (e.g. Segoe UI on Windows), you should look into CSS properties for:

```<code>font-variant-numeric: tabular-nums;
</code>```

(this disables the proportional-nums default value for the numeric-spacing variant supported at least by OpenType fonts, and possibly by other font formats supported by the text renderer of your web browser for your particular platform)

No JavaScript needed! It is the cleanest way to disable the variable-width glyphs in these fonts and force them to use tabular digits (this generally uses in the same glyphs in the same font, but their leading and trailing gap is increased so the 10 digits from 0 to 9 will render at the same width; however some font may avoid the visual variable interdigit spacing and will slightly widden some digits, or could add bottom serifs to the foot of digit 1.

Note that this does not disable the variable height observed with Segoe UI (such as some digits will be x-height only like lowercase letters, others will have ascenders or descenders). These traditional digit forms may be disabled with CSS too, using

```<code>font-variant-numeric: lining-nums;
</code>```

(this disables the default oldstyle-nums value for the numeric-figure variant supported at least by OpenType fonts, and by possibly other font formats supported by the text renderer of your web browser for your particular platform)

You can combine both:

```<code>font-variant-numeric: tabular-nums lining-nums;
</code>```

--

The snippet below demonstrates this using a single proportional font (not monospaced!) featuring shape variants for digits, such as 'Segoe UI' on Windows and shows the different horizontal and vertical alignments produced.

Note that this style does not prohibit digits to change width if different styles like bold or italic is applied instead of medium roman as shown below because these will use different fonts with their own distinct metrics (this is not warrantied as well with all monospace fonts).

html { font-family: 'Segoe UI'; /* proportional with digit variants */ }
table { margin: 0; padding: 0; border: 1px solid #AAA; border-collapse: collapse; }
th, td { vertical-align:top; text-align:right; }
.unset       { font-variant-numeric: unset; }
.traditional { font-variant-numeric: proportional-nums oldstyle-nums; }
.lining      { font-variant-numeric: proportional-nums lining-nums;   }
.tabular-old { font-variant-numeric: tabular-nums      oldstyle-nums; }
.tabular-new { font-variant-numeric: tabular-nums      lining-nums;   }
.normal      { font-variant-numeric: normal; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
<tr><th>unset<td><table width="100%" class="unset">
  <tr><td>Rs12,34,56,789.00/Gal<td><i>Difference Rs86,41,97,532.11/Gal
  <tr><td>Rs98,76,54,321.11/Gal<td><b>Total Rs1,11,11,11,110.11/Gal
  </table>
<tr><th>traditional<td><table width="100%" class="traditional">
  <tr><td>Rs12,34,56,789.00/Gal<td><i>Difference Rs86,41,97,532.11/Gal
  <tr><td>Rs98,76,54,321.11/Gal<td><b>Total Rs1,11,11,11,110.11/Gal
  </table>
<tr><th>lining<td><table width="100%" class="lining">
  <tr><td>Rs12,34,56,789.00/Gal<td><i>Difference Rs86,41,97,532.11/Gal
  <tr><td>Rs98,76,54,321.11/Gal<td><b>Total Rs1,11,11,11,110.11/Gal
  </table>
<tr><th>tabular-old<td><table width="100%" class="tabular-old">
  <tr><td>Rs12,34,56,789.00/Gal<td><i>Difference Rs86,41,97,532.11/Gal
  <tr><td>Rs98,76,54,321.11/Gal<td><b>Total Rs1,11,11,11,110.11/Gal
  </table>
<tr><th>tabular-new<td><table width="100%" class="tabular-new">
  <tr><td>Rs12,34,56,789.00/Gal<td><i>Difference Rs86,41,97,532.11/Gal
  <tr><td>Rs98,76,54,321.11/Gal<td><b>Total Rs1,11,11,11,110.11/Gal
  </table>
<tr><th>normal<td><table width="100%" class="normal">
  <tr><td>Rs12,34,56,789.00/Gal<td><i>Difference Rs86,41,97,532.11/Gal
  <tr><td>Rs98,76,54,321.11/Gal<td><b>Total Rs1,11,11,11,110.11/Gal
  </table>
</table></code>```

Reference: https://developer.mozilla.org/docs/Web/CSS/font-variant-numeric

Body:
If this is for aligning digits in tables where some fonts (with traditional typography) render them by default with variable width (e.g. Segoe UI on Windows), you should look into CSS properties for:

font-variant-numeric: tabular-nums;

(this disables the proportional-nums default value for the numeric-spacing variant supported at least by OpenType fonts, and possibly by other font formats supported by the text renderer of your web browser for your particular platform)

No JavaScript needed! It is the cleanest way to disable the variable-width glyphs in these fonts and force them to use tabular digits (this generally uses in the same glyphs in the same font, but their leading and trailing gap is increased so the 10 digits from 0 to 9 will render at the same width; however some font may avoid the visual variable interdigit spacing and will slightly widden some digits, or could add bottom serifs to the foot of digit 1.

Note that this does not disable the variable height observed with Segoe UI (such as some digits will be x-height only like lowercase letters, others will have ascenders or descenders). These traditional digit forms may be disabled with CSS too, using

font-variant-numeric: lining-nums;

(this disables the default oldstyle-nums value for the numeric-figure variant supported at least by OpenType fonts, and by possibly other font formats supported by the text renderer of your web browser for your particular platform)

You can combine both:

font-variant-numeric: tabular-nums lining-nums;

--

The snippet below demonstrates this using a single proportional font (not monospaced!) featuring shape variants for digits, such as 'Segoe UI' on Windows and shows the different horizontal and vertical alignments produced.

Note that this style does not prohibit digits to change width if different styles like bold or italic is applied instead of medium roman as shown below because these will use different fonts with their own distinct metrics (this is not warrantied as well with all monospace fonts).

html { font-family: 'Segoe UI'; /* proportional with digit variants */ }
table { margin: 0; padding: 0; border: 1px solid #AAA; border-collapse: collapse; }
th, td { vertical-align:top; text-align:right; }
.unset       { font-variant-numeric: unset; }
.traditional { font-variant-numeric: proportional-nums oldstyle-nums; }
.lining      { font-variant-numeric: proportional-nums lining-nums;   }
.tabular-old { font-variant-numeric: tabular-nums      oldstyle-nums; }
.tabular-new { font-variant-numeric: tabular-nums      lining-nums;   }
.normal      { font-variant-numeric: normal; }

<table>
<tr><th>unset<td><table width="100%" class="unset">
  <tr><td>Rs12,34,56,789.00/Gal<td><i>Difference Rs86,41,97,532.11/Gal
  <tr><td>Rs98,76,54,321.11/Gal<td><b>Total Rs1,11,11,11,110.11/Gal
  </table>
<tr><th>traditional<td><table width="100%" class="traditional">
  <tr><td>Rs12,34,56,789.00/Gal<td><i>Difference Rs86,41,97,532.11/Gal
  <tr><td>Rs98,76,54,321.11/Gal<td><b>Total Rs1,11,11,11,110.11/Gal
  </table>
<tr><th>lining<td><table width="100%" class="lining">
  <tr><td>Rs12,34,56,789.00/Gal<td><i>Difference Rs86,41,97,532.11/Gal
  <tr><td>Rs98,76,54,321.11/Gal<td><b>Total Rs1,11,11,11,110.11/Gal
  </table>
<tr><th>tabular-old<td><table width="100%" class="tabular-old">
  <tr><td>Rs12,34,56,789.00/Gal<td><i>Difference Rs86,41,97,532.11/Gal
  <tr><td>Rs98,76,54,321.11/Gal<td><b>Total Rs1,11,11,11,110.11/Gal
  </table>
<tr><th>tabular-new<td><table width="100%" class="tabular-new">
  <tr><td>Rs12,34,56,789.00/Gal<td><i>Difference Rs86,41,97,532.11/Gal
  <tr><td>Rs98,76,54,321.11/Gal<td><b>Total Rs1,11,11,11,110.11/Gal
  </table>
<tr><th>normal<td><table width="100%" class="normal">
  <tr><td>Rs12,34,56,789.00/Gal<td><i>Difference Rs86,41,97,532.11/Gal
  <tr><td>Rs98,76,54,321.11/Gal<td><b>Total Rs1,11,11,11,110.11/Gal
  </table>
</table>

Reference: https://developer.mozilla.org/docs/Web/CSS/font-variant-numeric

ContentLicense: CC BY-SA 4.0


问:
Using Auth0 to authenticate against multiple resources with a single application login
My app is authenticated using Auth0. The user enters their username + password and Auth0 gives back a token which my app uses to call my backend.

My app also uses 3rd party applications behind the scenes, and those 3rd party applications all have their own authentication. When a user logs in to my application, it needs to go out and get authentication tokens for all these 3rd party apps as well.

For example, my app needs to use an API on Watson which is authenticated using a different username + password. The user can’t know what that username + password are. Instead, they are ‘known’ by my app, which uses them to login to Watson and get an auth token to make the API calls.

That Watson API isn’t the only 3rd party API my app needs to use.  The 3rd party APIs all have their own authentication schemes. Some use a username + password, others use an App ID and Secret, etc. But in all of these cases, the authentication credentials are owned and managed by my application - not by the user of my application.

So the question is, how can I use Auth0 to automatically go out and get all these 3rd party authentication tokens when the user logs in to my app?

答:
When the user has authenticated with Auth0, the client will receive JSON Web Token (JWT) that can be used with APIs server or other 3rd party servers. It also contains the information about the user such as UID or email.

See https://auth0.com/learn/json-web-tokens/

In order to use Auth0 to automatically get all 3rd party authentication tokens, you can simply use Rules to get those tokens and merge it with your idToken. The client can then decode the JWT and get the token or secret it needed.

Rules are JavaScript code that will execute after the user is authenticated.

Here is the sample code from Auth0

```<code>function (user, context, callback) {

// this is the private key you downloaded from your service account.
// make sure you remove the password from the key and convert it to PEM using the following
// openssl pkcs12 -in yourkey.p12 -out yourkey.pem -nocerts -nodes
// finally, you should put this as a configuration encrypted in Auth0
var KEY = '....RSA private key downloaded from service account...';

// this is the email address of the service account created (NOT the Client ID)
var GOOGLE_CLIENT_ID_EMAIL = '.....@developer.gserviceaccount.com';

// the scope you want access to. Full list of scopes https://developers.google.com/admin-sdk/directory/v1/guides/authorizing
var SCOPE = 'https://www.googleapis.com/auth/admin.directory.user.readonly';

// a user of your Google Apps domain that this rule would impersonate
var ADMIN_EMAIL = 'foo@corp.com';

var token = jwt.sign({ scope: SCOPE, sub: ADMIN_EMAIL }, KEY, { audience: "https://accounts.google.com/o/oauth2/token", issuer: GOOGLE_CLIENT_ID_EMAIL, expiresInMinutes: 60, algorithm: 'RS256'});

request.post({ url: 'https://accounts.google.com/o/oauth2/token', form: { grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', assertion: token } }, function(err, resp, body) {
    if (err) return callback(null, user, context);
    var result = JSON.parse(body);
    if (result.error) {
    console.log(body);
    // log and swallow
    return callback(null, user, context);
    }

    context.idToken['https://example.com/admin_access_token'] = result.access_token;
    callback(null, user, context);
});

}
</code>```

After user logged in, this rule will request the Access_token from Google then put it in the response idToken. You can use this similar pattern for other APIs.

See https://auth0.com/docs/rules

Body:
When the user has authenticated with Auth0, the client will receive JSON Web Token (JWT) that can be used with APIs server or other 3rd party servers. It also contains the information about the user such as UID or email.

See https://auth0.com/learn/json-web-tokens/

In order to use Auth0 to automatically get all 3rd party authentication tokens, you can simply use Rules to get those tokens and merge it with your idToken. The client can then decode the JWT and get the token or secret it needed.

Rules are JavaScript code that will execute after the user is authenticated.

Here is the sample code from Auth0

function (user, context, callback) {

// this is the private key you downloaded from your service account.
// make sure you remove the password from the key and convert it to PEM using the following
// openssl pkcs12 -in yourkey.p12 -out yourkey.pem -nocerts -nodes
// finally, you should put this as a configuration encrypted in Auth0
var KEY = '....RSA private key downloaded from service account...';

// this is the email address of the service account created (NOT the Client ID)
var GOOGLE_CLIENT_ID_EMAIL = '.....@developer.gserviceaccount.com';

// the scope you want access to. Full list of scopes https://developers.google.com/admin-sdk/directory/v1/guides/authorizing
var SCOPE = 'https://www.googleapis.com/auth/admin.directory.user.readonly';

// a user of your Google Apps domain that this rule would impersonate
var ADMIN_EMAIL = 'foo@corp.com';

var token = jwt.sign({ scope: SCOPE, sub: ADMIN_EMAIL }, KEY, { audience: "https://accounts.google.com/o/oauth2/token", issuer: GOOGLE_CLIENT_ID_EMAIL, expiresInMinutes: 60, algorithm: 'RS256'});

request.post({ url: 'https://accounts.google.com/o/oauth2/token', form: { grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', assertion: token } }, function(err, resp, body) {
    if (err) return callback(null, user, context);
    var result = JSON.parse(body);
    if (result.error) {
    console.log(body);
    // log and swallow
    return callback(null, user, context);
    }

    context.idToken['https://example.com/admin_access_token'] = result.access_token;
    callback(null, user, context);
});

}

After user logged in, this rule will request the Access_token from Google then put it in the response idToken. You can use this similar pattern for other APIs.

See https://auth0.com/docs/rules


问:
Custom MKAnnotation with drag & drop animation
I have an annotation with custom image and drag'n'drop support. But I need to animate the annotation the same way default Google pin is animated. That means the annotation should "jump up" when I drag it and "fall down" when I release it.

I was quite surprised that this animation isn't working anymore when I change annotation's image.

Thanks.

答: I have found the answer here: Subclassing MKAnnotationView and overriding setDragState. I used bad keywords when I was trying to find the answer before.</p>


问:
How to scan the entire Firebase database?
I need to scan all my firebase, to make the following queries which I already researched in the documentation and did not find:

1) I need to count how many shopping malls in the database.

2) I need to get the Arrays of numbers from each mall so I can insert
  into a ".push ()" function in google maps api and create the lat and
  lng for each polygon.

I'll explain how my firebase architecture will look:

I have several "Shopping Center Administrators", which in this JSON
  they call themselves (Aliansce, New Company).

Within each Administrator Shopping Mall, I have several shopping malls
  which are (Aliansce: Bangu, New York, ny2) and (New Company: luc2,
  luc1).

Within each Shopping, I have the ID's for each.

Within the ID's I have the ID's dates.

Inside the ID's date I have I have the store that contains in the
  mall.

FIREBASE DATABASE:

```<code>{
  "aliansce" : {
    "AliansceShopping1" : {
      "1" : {
        "loja1" : {
          "coordenadasLat" : [ -33.564, -35.259, -35.155 ],
          "coordenadasLng" : [ 149.276, 148.705, 150.1 ],
          "nomefantasia" : "loja1"
        }
      },
      "2" : {
        "loja2" : {
          "coordenadasLat" : [ 2.258579, -59.008697, -55.493581, 13.727475 ],
          "coordenadasLng" : [ -95.338008, -82.330197, -14.127078, -37.857544 ],
          "nomefantasia" : "loja2"
        }
      }
    },
    "AliansceShopping2" : {
      "3" : {
        "loja1" : {
          "coordenadasLat" : [ -33.564, -35.259, -35.155 ],
          "coordenadasLng" : [ 149.276, 148.705, 150.1 ],
          "nomefantasia" : "Loja1"
        }
      },
      "4" : {
        "loja2" : {
          "coordenadasLat" : [ 2.258579, -59.008697, -55.493581, 13.727475 ],
          "coordenadasLng" : [ -95.338008, -82.330197, -14.127078, -37.857544 ],
          "nomefantasia" : "Loja2"
        }
      }
    },
    "versoes" : {
      "bangu" : {
        "190001" : "13/11/2017",
        "201701" : "13/11/2017",
        "201706" : "13/11/2017"
      }
    }
  },
  "novoAdm" : {
    "novoAdmShopping1" : {
      "1n" : {
        "loja1" : {
          "coordenadasLat" : [ -33.564, -35.259, -35.155 ],
          "coordenadasLng" : [ 149.276, 148.705, 150.1 ],
          "nomefantasia" : "loja1"
        }
      },
      "2n" : {
        "loja2" : {
          "coordenadasLat" : [ 2.258579, -59.008697, -55.493581, 13.727475 ],
          "coordenadasLng" : [ -95.338008, -82.330197, -14.127078, -37.857544 ],
          "nomefantasia" : "loja2"
        }
      }
    },
    "novoAdmShopping2" : {
      "3n" : {
        "loja1" : {
          "coordenadasLat" : [ -33.564, -35.259, -35.155 ],
          "coordenadasLng" : [ 149.276, 148.705, 150.1 ],
          "nomefantasia" : "Loja1"
        }
      },
      "4n" : {
        "loja2" : {
          "coordenadasLat" : [ 2.258579, -59.008697, -55.493581, 13.727475 ],
          "coordenadasLng" : [ -95.338008, -82.330197, -14.127078, -37.857544 ],
          "nomefantasia" : "Loja2"
        }
      }
    },
    "versoes" : {
      "nwVer" : {
        "190001" : "13/11/2017",
        "201701" : "13/11/2017",
        "201706" : "13/11/2017"
      }
    }
  }
}
</code>```

OBS: I'M USING JAVASCRIPT

CODE:

```<code>function initFireBase(){
    var config = {
        apiKey: "",
        authDomain: "",
        databaseURL: "",
        projectId: "",
        storageBucket: "",
        messagingSenderId: ""
    };
    firebase.initializeApp(config);

    var ref = firebase.database().ref('/'); // INICIA NA RAIZ DO NÓ
    var rootDatabase = new Array();
    var childRootDatabase = new Array();
    var childParentDatabase = new Array();
    var tst;
    var tst2;

    ref.on('value', function(snap){
        // PERCORRE TODOS OS "CHILD'S" DO {REF}
        snap.forEach(function(rootSnapshot){
            rootDatabase = [...rootDatabase, rootSnapshot.key]; // CRIA UM ARRAY PARA AS "KEYS" DOS "CHILD'S"
        });

        for(a in rootDatabase){

                    tst = firebase.database().ref('' + rootDatabase[a]);

                    tst.on('child_added', function(snap){
                        snap.forEach(function(sna){
                            childRootDatabase = [...childRootDatabase, sna.key];
                        });
                    });

                    for(b in childRootDatabase){
                        tst2 = firebase.database().ref('/' + rootDatabase[a] + '/' + childRootDatabase[b]);
                        console.log(tst2.key);
                    }
        }

    });
</code>```

I was able to access all these children, but I can not get the coordinatesLat and lng;

答:
I'm not sure I understand what you're trying to accomplish. But the code looks suboptimal, so hopefully an explanation of that will help you along.

Since you're loading the value from the root, there is no need to use any more nested listeners. Instead you can just iterate over the (nested) snapshots and get to the data you need. A more idiomatic way to do what your code currently does is:

```<code>ref.on('value', function(snap){
    mallKeys = [];
    snap.forEach(function(adminSnapshot){
        adminSnapshot.forEach(function(mallSnapshot) {
            mallKeys.push(mallSnapshot.key);
        });
    });
    console.log("There are "+mallKeys.length+" malls");
});
</code>```

Body:
I need to scan all my firebase, to make the following queries which I already researched in the documentation and did not find:

1) I need to count how many shopping malls in the database.

2) I need to get the Arrays of numbers from each mall so I can insert
  into a ".push ()" function in google maps api and create the lat and
  lng for each polygon.

I'll explain how my firebase architecture will look:

I have several "Shopping Center Administrators", which in this JSON
  they call themselves (Aliansce, New Company).

Within each Administrator Shopping Mall, I have several shopping malls
  which are (Aliansce: Bangu, New York, ny2) and (New Company: luc2,
  luc1).

Within each Shopping, I have the ID's for each.

Within the ID's I have the ID's dates.

Inside the ID's date I have I have the store that contains in the
  mall.

FIREBASE DATABASE:

{
  "aliansce" : {
    "AliansceShopping1" : {
      "1" : {
        "loja1" : {
          "coordenadasLat" : [ -33.564, -35.259, -35.155 ],
          "coordenadasLng" : [ 149.276, 148.705, 150.1 ],
          "nomefantasia" : "loja1"
        }
      },
      "2" : {
        "loja2" : {
          "coordenadasLat" : [ 2.258579, -59.008697, -55.493581, 13.727475 ],
          "coordenadasLng" : [ -95.338008, -82.330197, -14.127078, -37.857544 ],
          "nomefantasia" : "loja2"
        }
      }
    },
    "AliansceShopping2" : {
      "3" : {
        "loja1" : {
          "coordenadasLat" : [ -33.564, -35.259, -35.155 ],
          "coordenadasLng" : [ 149.276, 148.705, 150.1 ],
          "nomefantasia" : "Loja1"
        }
      },
      "4" : {
        "loja2" : {
          "coordenadasLat" : [ 2.258579, -59.008697, -55.493581, 13.727475 ],
          "coordenadasLng" : [ -95.338008, -82.330197, -14.127078, -37.857544 ],
          "nomefantasia" : "Loja2"
        }
      }
    },
    "versoes" : {
      "bangu" : {
        "190001" : "13/11/2017",
        "201701" : "13/11/2017",
        "201706" : "13/11/2017"
      }
    }
  },
  "novoAdm" : {
    "novoAdmShopping1" : {
      "1n" : {
        "loja1" : {
          "coordenadasLat" : [ -33.564, -35.259, -35.155 ],
          "coordenadasLng" : [ 149.276, 148.705, 150.1 ],
          "nomefantasia" : "loja1"
        }
      },
      "2n" : {
        "loja2" : {
          "coordenadasLat" : [ 2.258579, -59.008697, -55.493581, 13.727475 ],
          "coordenadasLng" : [ -95.338008, -82.330197, -14.127078, -37.857544 ],
          "nomefantasia" : "loja2"
        }
      }
    },
    "novoAdmShopping2" : {
      "3n" : {
        "loja1" : {
          "coordenadasLat" : [ -33.564, -35.259, -35.155 ],
          "coordenadasLng" : [ 149.276, 148.705, 150.1 ],
          "nomefantasia" : "Loja1"
        }
      },
      "4n" : {
        "loja2" : {
          "coordenadasLat" : [ 2.258579, -59.008697, -55.493581, 13.727475 ],
          "coordenadasLng" : [ -95.338008, -82.330197, -14.127078, -37.857544 ],
          "nomefantasia" : "Loja2"
        }
      }
    },
    "versoes" : {
      "nwVer" : {
        "190001" : "13/11/2017",
        "201701" : "13/11/2017",
        "201706" : "13/11/2017"
      }
    }
  }
}

OBS: I'M USING JAVASCRIPT

CODE:

function initFireBase(){
    var config = {
        apiKey: "",
        authDomain: "",
        databaseURL: "",
        projectId: "",
        storageBucket: "",
        messagingSenderId: ""
    };
    firebase.initializeApp(config);

    var ref = firebase.database().ref('/'); // INICIA NA RAIZ DO NÓ
    var rootDatabase = new Array();
    var childRootDatabase = new Array();
    var childParentDatabase = new Array();
    var tst;
    var tst2;

    ref.on('value', function(snap){
        // PERCORRE TODOS OS "CHILD'S" DO {REF}
        snap.forEach(function(rootSnapshot){
            rootDatabase = [...rootDatabase, rootSnapshot.key]; // CRIA UM ARRAY PARA AS "KEYS" DOS "CHILD'S"
        });

        for(a in rootDatabase){

                    tst = firebase.database().ref('' + rootDatabase[a]);

                    tst.on('child_added', function(snap){
                        snap.forEach(function(sna){
                            childRootDatabase = [...childRootDatabase, sna.key];
                        });
                    });

                    for(b in childRootDatabase){
                        tst2 = firebase.database().ref('/' + rootDatabase[a] + '/' + childRootDatabase[b]);
                        console.log(tst2.key);
                    }
        }

    });

I was able to access all these children, but I can not get the coordinatesLat and lng;

Body:
I'm not sure I understand what you're trying to accomplish. But the code looks suboptimal, so hopefully an explanation of that will help you along.

Since you're loading the value from the root, there is no need to use any more nested listeners. Instead you can just iterate over the (nested) snapshots and get to the data you need. A more idiomatic way to do what your code currently does is:

ref.on('value', function(snap){
    mallKeys = [];
    snap.forEach(function(adminSnapshot){
        adminSnapshot.forEach(function(mallSnapshot) {
            mallKeys.push(mallSnapshot.key);
        });
    });
    console.log("There are "+mallKeys.length+" malls");
});


问:
Dependency injection not working with League\Route and League\Container
I'm building a web application right now and I'm facing a problem with my controller.

I want to send to my controller my League\Plate\Engine (registred in my Container) but I keep having the same error : Argument 3 passed to App\Controller\Main::index() must be an instance of League\Plates\Engine, array given

Here is my files :

dependencies.php

```<code>use League\Container\Container;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use Yajra\Pdo\Oci8;
use League\Container\ReflectionContainer;

$container = new Container();

// Active auto-wiring
$container->delegate(
    new ReflectionContainer
);

// Others dependencies
// ...

// Views
$container->add('view', function () {
    $templates = new League\Plates\Engine();

    $templates->addFolder('web', __DIR__ . '/templates/views/');
    $templates->addFolder('emails', __DIR__ . '/templates/emails/');

    // Extension
    //$templates->loadExtension(new League\Plates\Extension\Asset('/path/to/public'));
    //$templates->loadExtension(new League\Plates\Extension\URI($_SERVER['PATH_INFO']));

    return $templates;
});

return $container;
</code>```

routes.php

```<code>use League\Route\RouteCollection;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

$route = new RouteCollection($container);

// Page index
$route->get('/', 'App\Controller\Main::index');

// Others routes...

return $route;
</code>```

Main.php

```<code>namespace App\Controller;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use League\Plates\Engine;

class Main
{
    public function index(ServerRequestInterface $request, ResponseInterface $response, Engine $templates) {
        //return $response->getBody()->write($this->templates->render('web::home'));
        return $response;
    }
}
</code>```

Thank you in advance

EDIT

I've made a progress.
I extended the Main class to extends the abstract class BaseController which looks like this :

```<code>namespace App\Controller;

use League\Plates\Engine;

 class BaseController
{
    protected $templates;

    public function __construct(Engine $templates) {
        $this->templates = $templates;
    }
}
</code>```

The first error goes away, but another one show up. In the Main class, I would like to use the view object that I instanciate in the container, but the object passed to the constructor is an empty one :

Main.php

```<code>class Main extends BaseController
{
    public function index(ServerRequestInterface $request, ResponseInterface $response) {
        echo '```'.print_r($this->templates,1).'```'; // Return an empty Plate Engine object
        return $response->getBody()->write($this->templates->render('web::home'));
        //return $response;
    }
}
</code>```

And this doesn't explain why the first error shows up

EDIT 2

After some digging, I finally make it works, but I sense that something is wrong.
I replaced in the container the term view by the namespace of the Engine class :

```<code>$container->add('League\Plates\Engine', function () {
    // The same as before
});
</code>```

In Main.php I've updated the index function like this :

```<code>public function index(ServerRequestInterface $request, ResponseInterface $response) {
        $body = $response->getBody();
        $body->write($this->templates->render('web::home'));
        return $response->withBody($body);
    }
</code>```

And the page doesn't throw a 500 error and the html file is displayed correctly.

But, what if I want to change the template engine by Twig for example ? This would mean I'll need to change all the call to $container->get('League\Plate\Engine'); by $container->get('What\Ever'); ? That's not very practical!
I probably missed something!
And the problem will rise again when I'll want to use my PDO object... or every other object.

答:
This works, because you are registering with the container your controller class, and telling the container to dependency inject your View class in the constructor..

The line you added, here, is doing that:

$container->add('App\Controller\Main')
    ->withArgument($container->get('view'));

The Hello World documentation example explains it perfectly.

http://container.thephpleague.com/3.x/constructor-injection/

Body:
I'm building a web application right now and I'm facing a problem with my controller.

I want to send to my controller my League\Plate\Engine (registred in my Container) but I keep having the same error : Argument 3 passed to App\Controller\Main::index() must be an instance of League\Plates\Engine, array given

Here is my files :

dependencies.php

use League\Container\Container;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use Yajra\Pdo\Oci8;
use League\Container\ReflectionContainer;

$container = new Container();

// Active auto-wiring
$container->delegate(
    new ReflectionContainer
);

// Others dependencies
// ...

// Views
$container->add('view', function () {
    $templates = new League\Plates\Engine();

    $templates->addFolder('web', __DIR__ . '/templates/views/');
    $templates->addFolder('emails', __DIR__ . '/templates/emails/');

    // Extension
    //$templates->loadExtension(new League\Plates\Extension\Asset('/path/to/public'));
    //$templates->loadExtension(new League\Plates\Extension\URI($_SERVER['PATH_INFO']));

    return $templates;
});

return $container;

routes.php

use League\Route\RouteCollection;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

$route = new RouteCollection($container);

// Page index
$route->get('/', 'App\Controller\Main::index');

// Others routes...

return $route;

Main.php

namespace App\Controller;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use League\Plates\Engine;

class Main
{
    public function index(ServerRequestInterface $request, ResponseInterface $response, Engine $templates) {
        //return $response->getBody()->write($this->templates->render('web::home'));
        return $response;
    }
}

Thank you in advance

EDIT

I've made a progress.
I extended the Main class to extends the abstract class BaseController which looks like this :

namespace App\Controller;

use League\Plates\Engine;

 class BaseController
{
    protected $templates;

    public function __construct(Engine $templates) {
        $this->templates = $templates;
    }
}

The first error goes away, but another one show up. In the Main class, I would like to use the view object that I instanciate in the container, but the object passed to the constructor is an empty one :

Main.php

class Main extends BaseController
{
    public function index(ServerRequestInterface $request, ResponseInterface $response) {
        echo '
'.print_r($this->templates,1).'
'; // Return an empty Plate Engine object
        return $response->getBody()->write($this->templates->render('web::home'));
        //return $response;
    }
}

And this doesn't explain why the first error shows up

EDIT 2

After some digging, I finally make it works, but I sense that something is wrong.
I replaced in the container the term view by the namespace of the Engine class :

$container->add('League\Plates\Engine', function () {
    // The same as before
});

In Main.php I've updated the index function like this :

public function index(ServerRequestInterface $request, ResponseInterface $response) {
        $body = $response->getBody();
        $body->write($this->templates->render('web::home'));
        return $response->withBody($body);
    }

And the page doesn't throw a 500 error and the html file is displayed correctly.

But, what if I want to change the template engine by Twig for example ? This would mean I'll need to change all the call to $container->get('League\Plate\Engine'); by $container->get('What\Ever'); ? That's not very practical!
I probably missed something!
And the problem will rise again when I'll want to use my PDO object... or every other object.


问:
How to create multiple datasources for collection view?
I have a tableview with two cells and two embedded collectionviews inside those cells. My app keeps crashing when it tries to duque the second cell. I used Ash Furrows tutorial as a basis for this project which I will link here.  Tutorial link

How can I fix this issue? Here is some sample code.

I have two different cells with each of them having their own class with this code

```<code>    class TableViewCell: UITableViewCell {

    @IBOutlet weak var collectionView: UICollectionView!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

    func setCollectionViewDataSourceDelegate <D: UICollectionViewDataSource & UICollectionViewDelegate> (dataSourceDelegate: D, forRow row: Int) {
        collectionView.delegate = dataSourceDelegate
        collectionView.dataSource = dataSourceDelegate
        collectionView.tag = row
        collectionView.reloadData()
    }
}
</code>```

This is the rest of the code showing how I dequeue my cell

```<code>    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        if indexPath.section == 1 {
            guard let tableViewCell = cell as? TableViewCell else {
                return
            }

            tableViewCell.setCollectionViewDataSourceDelegate(dataSourceDelegate: self, forRow: indexPath.row)
        }

        if indexPath.section == 2 {
            guard let tableViewCell2 = cell as? TableViewCell2 else {
                return
            }
            tableViewCell2.setCollectionViewDataSourceDelegate(dataSourceDelegate: self, forRow: indexPath.row)
        }

        // we store the offset from here into the dictionary we created above
        //tableViewCell.collectionViewOffset = storedOffsets[indexPath.row] ?? 0
    }

    func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        guard let tableViewCell = cell as? TableViewCell else { return }

        storedOffsets[indexPath.row] = tableViewCell.collectionViewOffset
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print(indexPath)
    }
}

// collectionView inside tableview cell

extension TabViewController1: UICollectionViewDelegate, UICollectionViewDataSource {

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return model[collectionView.tag].count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath) as? CollectionCell1 {
            cell.backgroundColor = UIColor.gray
            return cell
        }

        if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell2", for: indexPath) as? CollectionCell2 {
            cell.backgroundColor = UIColor.purple
            return cell
        }

        return UICollectionViewCell()
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("Collection view at row \(collectionView.tag) selected index path \(indexPath)")
    }
}
</code>```

Any help will are greatly appreciated!

EDIT: This is the whole view controller class

```<code>    class TabViewController1: UIViewController, UITableViewDelegate {

    @IBOutlet private var tableView: UITableView!

    var model: [[UIColor]] = []

    // Here we create a new dictionary to store the offests, corresponding to their rows.
    var storedOffsets = [Int: CGFloat]()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        print("tab1")

        model = generateRandomData()
        tableView.delegate = self
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        print("tab 1 viewWillAppear")
    }

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

    func generateRandomData() -> [[UIColor]] {
        let numberOfRows = 20
        let numberOfItemsPerRow = 15

        return (0..<numberOfRows).map { _ in
            return (0..<numberOfItemsPerRow).map { _ in UIColor.randomColor() }
        }
    }
}

extension TabViewController1: UITableViewDataSource {

    func numberOfSections(in tableView: UITableView) -> Int {
        return 5
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 3 {
            return 1
        }
        if section == 4 {
            return 6
        } else {
            return 1
        }
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "featuredPicture", for: indexPath) as! FeaturedVideoTableViewCell
            return cell
        }

        if indexPath.section == 1 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TableViewCell
            return cell
        }

        if indexPath.section == 2 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "Cell2", for: indexPath) as! TableViewCell2
            return cell
        }

        if indexPath.section == 3 {

            let cell = tableView.dequeueReusableCell(withIdentifier: "headerCell", for: indexPath) as! HeaderTableViewCell
            return cell
        }

        if indexPath.section == 4 {

            let cell = tableView.dequeueReusableCell(withIdentifier: "categoryCell", for: indexPath) as! CategoryTableViewCell
            return cell
        }

        return UITableViewCell()

    }

    // titleForHeaderInSection doesnt get called because I implemented the bottom method which is `viewForHeaderInSection`.
    // I am trying to figure out if we can use both at the same time
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

        if section == 0 {
            return "Featured"
        }

        if section == 1 {
            return "Cool Stuff"
        }

        if section == 2 {
            return "Awesome Stuff"
        }

        if section == 3 {
            return "nothing"
        }

        if section == 4 {
            return "Categories"
        }

        return String()
    }

    // viewForHeaderInSection
//  func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
//      if section == 3 {
//          let cell = tableView.dequeueReusableCell(withIdentifier: "headerCell") as! HeaderTableViewCell
//          return cell
//      }
//      return UIView()
//  }

//  func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
//      if section == 3 {
//          return 50
//      }
//      return CGFloat()
//  }

    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        if indexPath.section == 1 {
            guard let tableViewCell = cell as? TableViewCell else {
                return
            }

            tableViewCell.setCollectionViewDataSourceDelegate(dataSourceDelegate: self, forRow: indexPath.row)
        }

        if indexPath.section == 2 {
            guard let tableViewCell2 = cell as? TableViewCell2 else {
                return
            }
            tableViewCell2.setCollectionViewDataSourceDelegate(dataSourceDelegate: self, forRow: indexPath.row)
        }

        // we store the offset from here into the dictionary we created above
        //tableViewCell.collectionViewOffset = storedOffsets[indexPath.row] ?? 0
    }

    func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        guard let tableViewCell = cell as? TableViewCell else { return }

        storedOffsets[indexPath.row] = tableViewCell.collectionViewOffset
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            return 350
        }

        if indexPath.section == 1 {
            return 130
        }

        if indexPath.section == 2 {
            return 200
        }

        if indexPath.section == 3 {
            return 50
        }

        if indexPath.section == 4 {
            return 220
        }

        return CGFloat()
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print(indexPath)
    }
}

// collectionView inside tableview cell

extension TabViewController1: UICollectionViewDelegate, UICollectionViewDataSource {

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return model[collectionView.tag].count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath) as? CollectionCell1 {
            cell.backgroundColor = UIColor.gray
            return cell
        }

        if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell2", for: indexPath) as? CollectionCell2 {
            cell.backgroundColor = UIColor.purple
            return cell
        }

        return UICollectionViewCell()
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("Collection view at row \(collectionView.tag) selected index path \(indexPath)")
    }
}
</code>```

答: Without seeing where you're registering your cell classes, it's hard to say for certain, but my suspicion is that you're getting back something other than a TableViewCell2 (or wherever it's actually crashing) in your -cellForRow… or -cellForItemAt… methods. All of your force unwrapping (!) is likely to cause a problem. Put a breakpoint right before the crash, and check to see what you're actually getting back from your -dequeueReusableCell call.</p>

Body:
I have a tableview with two cells and two embedded collectionviews inside those cells. My app keeps crashing when it tries to duque the second cell. I used Ash Furrows tutorial as a basis for this project which I will link here.  Tutorial link

How can I fix this issue? Here is some sample code.

I have two different cells with each of them having their own class with this code

    class TableViewCell: UITableViewCell {

    @IBOutlet weak var collectionView: UICollectionView!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

    func setCollectionViewDataSourceDelegate <D: UICollectionViewDataSource & UICollectionViewDelegate> (dataSourceDelegate: D, forRow row: Int) {
        collectionView.delegate = dataSourceDelegate
        collectionView.dataSource = dataSourceDelegate
        collectionView.tag = row
        collectionView.reloadData()
    }
}

This is the rest of the code showing how I dequeue my cell

    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        if indexPath.section == 1 {
            guard let tableViewCell = cell as? TableViewCell else {
                return
            }

            tableViewCell.setCollectionViewDataSourceDelegate(dataSourceDelegate: self, forRow: indexPath.row)
        }

        if indexPath.section == 2 {
            guard let tableViewCell2 = cell as? TableViewCell2 else {
                return
            }
            tableViewCell2.setCollectionViewDataSourceDelegate(dataSourceDelegate: self, forRow: indexPath.row)
        }

        // we store the offset from here into the dictionary we created above
        //tableViewCell.collectionViewOffset = storedOffsets[indexPath.row] ?? 0
    }

    func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        guard let tableViewCell = cell as? TableViewCell else { return }

        storedOffsets[indexPath.row] = tableViewCell.collectionViewOffset
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print(indexPath)
    }
}

// collectionView inside tableview cell

extension TabViewController1: UICollectionViewDelegate, UICollectionViewDataSource {

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return model[collectionView.tag].count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath) as? CollectionCell1 {
            cell.backgroundColor = UIColor.gray
            return cell
        }

        if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell2", for: indexPath) as? CollectionCell2 {
            cell.backgroundColor = UIColor.purple
            return cell
        }

        return UICollectionViewCell()
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("Collection view at row \(collectionView.tag) selected index path \(indexPath)")
    }
}

Any help will are greatly appreciated!

EDIT: This is the whole view controller class

    class TabViewController1: UIViewController, UITableViewDelegate {

    @IBOutlet private var tableView: UITableView!

    var model: [[UIColor]] = []

    // Here we create a new dictionary to store the offests, corresponding to their rows.
    var storedOffsets = [Int: CGFloat]()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        print("tab1")

        model = generateRandomData()
        tableView.delegate = self
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        print("tab 1 viewWillAppear")
    }

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

    func generateRandomData() -> [[UIColor]] {
        let numberOfRows = 20
        let numberOfItemsPerRow = 15

        return (0..<numberOfRows).map { _ in
            return (0..<numberOfItemsPerRow).map { _ in UIColor.randomColor() }
        }
    }
}

extension TabViewController1: UITableViewDataSource {

    func numberOfSections(in tableView: UITableView) -> Int {
        return 5
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 3 {
            return 1
        }
        if section == 4 {
            return 6
        } else {
            return 1
        }
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "featuredPicture", for: indexPath) as! FeaturedVideoTableViewCell
            return cell
        }

        if indexPath.section == 1 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TableViewCell
            return cell
        }

        if indexPath.section == 2 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "Cell2", for: indexPath) as! TableViewCell2
            return cell
        }

        if indexPath.section == 3 {

            let cell = tableView.dequeueReusableCell(withIdentifier: "headerCell", for: indexPath) as! HeaderTableViewCell
            return cell
        }

        if indexPath.section == 4 {

            let cell = tableView.dequeueReusableCell(withIdentifier: "categoryCell", for: indexPath) as! CategoryTableViewCell
            return cell
        }

        return UITableViewCell()

    }

    // titleForHeaderInSection doesnt get called because I implemented the bottom method which is `viewForHeaderInSection`.
    // I am trying to figure out if we can use both at the same time
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

        if section == 0 {
            return "Featured"
        }

        if section == 1 {
            return "Cool Stuff"
        }

        if section == 2 {
            return "Awesome Stuff"
        }

        if section == 3 {
            return "nothing"
        }

        if section == 4 {
            return "Categories"
        }

        return String()
    }

    // viewForHeaderInSection
//  func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
//      if section == 3 {
//          let cell = tableView.dequeueReusableCell(withIdentifier: "headerCell") as! HeaderTableViewCell
//          return cell
//      }
//      return UIView()
//  }

//  func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
//      if section == 3 {
//          return 50
//      }
//      return CGFloat()
//  }

    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        if indexPath.section == 1 {
            guard let tableViewCell = cell as? TableViewCell else {
                return
            }

            tableViewCell.setCollectionViewDataSourceDelegate(dataSourceDelegate: self, forRow: indexPath.row)
        }

        if indexPath.section == 2 {
            guard let tableViewCell2 = cell as? TableViewCell2 else {
                return
            }
            tableViewCell2.setCollectionViewDataSourceDelegate(dataSourceDelegate: self, forRow: indexPath.row)
        }

        // we store the offset from here into the dictionary we created above
        //tableViewCell.collectionViewOffset = storedOffsets[indexPath.row] ?? 0
    }

    func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        guard let tableViewCell = cell as? TableViewCell else { return }

        storedOffsets[indexPath.row] = tableViewCell.collectionViewOffset
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            return 350
        }

        if indexPath.section == 1 {
            return 130
        }

        if indexPath.section == 2 {
            return 200
        }

        if indexPath.section == 3 {
            return 50
        }

        if indexPath.section == 4 {
            return 220
        }

        return CGFloat()
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print(indexPath)
    }
}

// collectionView inside tableview cell

extension TabViewController1: UICollectionViewDelegate, UICollectionViewDataSource {

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return model[collectionView.tag].count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath) as? CollectionCell1 {
            cell.backgroundColor = UIColor.gray
            return cell
        }

        if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell2", for: indexPath) as? CollectionCell2 {
            cell.backgroundColor = UIColor.purple
            return cell
        }

        return UICollectionViewCell()
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("Collection view at row \(collectionView.tag) selected index path \(indexPath)")
    }
}


问:
Error when calling PSI web service: HTTP request is unauthorized with client authentication scheme 'Anonymous'
Could someone please help me?  I am trying to create a project in project server programatically (PSI webservice) but am failing to do so because of the error below.  Does anyone know what might be the issue?  I am also getting this error when attempting to update the web service in VS2008.

Here is the error and it happens when I call QueueCreateProject (see code below):

```<code>System.ServiceModel.Security.MessageSecurityException: The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was 'NTLM'. ---> System.Net.WebException: The remote server returned an error: (401) Unauthorized.
   at System.Net.HttpWebRequest.GetResponse()
   at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
   --- End of inner exception stack trace ---
</code>```

Here is the code:

```<code>       objProject = new pstest.ProjectWS.ProjectSoapClient();

           dsProjectDataSet = new pstest.ProjectWS.ProjectDataSet();
            ProjectWS.ProjectDataSet.ProjectRow projectRow = dsProjectDataSet.Project.NewProjectRow();
            Guid _projectGUID = Guid.NewGuid(); // new GUID for each project
            projectRow.PROJ_UID = _projectGUID;
            projectRow.PROJ_NAME = "My new Project";
            projectRow.PROJ_INFO_START_DATE = System.DateTime.Now;
            projectRow.PROJ_TYPE = 0; //0 is for project and 1 is for template
            dsProjectDataSet.Project.AddProjectRow(projectRow);

            //create a project using project.asmx

            objProject.QueueCreateProject(Guid.NewGuid(), dsProjectDataSet,false);
</code>```

答:
Most likely your app.config is misconfigured. Depending on your security configuration, you probably need to change part of it:

```<code><security mode="TransportCredentialOnly">
  <transport clientCredentialType="Ntlm"/>
</security>
</code>```

Take a look at this thread for more information.

Body:
Could someone please help me?  I am trying to create a project in project server programatically (PSI webservice) but am failing to do so because of the error below.  Does anyone know what might be the issue?  I am also getting this error when attempting to update the web service in VS2008.

Here is the error and it happens when I call QueueCreateProject (see code below):

System.ServiceModel.Security.MessageSecurityException: The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was 'NTLM'. ---> System.Net.WebException: The remote server returned an error: (401) Unauthorized.
   at System.Net.HttpWebRequest.GetResponse()
   at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
   --- End of inner exception stack trace ---

Here is the code:

       objProject = new pstest.ProjectWS.ProjectSoapClient();

           dsProjectDataSet = new pstest.ProjectWS.ProjectDataSet();
            ProjectWS.ProjectDataSet.ProjectRow projectRow = dsProjectDataSet.Project.NewProjectRow();
            Guid _projectGUID = Guid.NewGuid(); // new GUID for each project
            projectRow.PROJ_UID = _projectGUID;
            projectRow.PROJ_NAME = "My new Project";
            projectRow.PROJ_INFO_START_DATE = System.DateTime.Now;
            projectRow.PROJ_TYPE = 0; //0 is for project and 1 is for template
            dsProjectDataSet.Project.AddProjectRow(projectRow);

            //create a project using project.asmx

            objProject.QueueCreateProject(Guid.NewGuid(), dsProjectDataSet,false);

Body:
Most likely your app.config is misconfigured. Depending on your security configuration, you probably need to change part of it:

<security mode="TransportCredentialOnly">
  <transport clientCredentialType="Ntlm"/>
</security>

Take a look at this thread for more information.