Blank page is coming without any error

Question: I know ReactJs but I am new to Redux. I am trying to perform async action like I am calling an API and want to display data received from it. When I am implementing redux in single page, i.e. actions, reducers, containers all on one page its working fine. Single page code is as follows:
import React from 'react';
import { render } from 'react-dom';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import thunk from 'redux-thunk';
import { connect } from 'react-redux';

function fetchPostsRequest(){
  return {
    type: "FETCH_REQUEST"
  }
}

function fetchPostsSuccess(payload) {
  return {
    type: "FETCH_SUCCESS",
    payload
  }
}

function fetchPostsError() {
  return {
    type: "FETCH_ERROR"
  }
}

const reducer = (state = {}, action) => {
  switch (action.type) {
    case "FETCH_REQUEST":
      return state;
    case "FETCH_SUCCESS":
      return {...state, posts: action.payload};
    default:
      return state;
  }
}

function fetchPostsWithRedux() {
    return (dispatch) => {
    dispatch(fetchPostsRequest());
    return fetchPosts().then(([response, json]) =>{
        if(response.status === 200){
        dispatch(fetchPostsSuccess(json.data))
      }
      else{
        dispatch(fetchPostsError())
      }
    })
  }
}

function fetchPosts() {
  const URL = "api-url";
  let user = JSON.parse(localStorage.getItem('user'));
  return fetch(URL, {
          method: 'POST',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            api_token: user.api_token,
            type: 'task',
          })
        }).then(response => Promise.all([response, response.json()]));
}

class App extends React.Component {
    componentDidMount(){
    this.props.fetchPostsWithRedux()
  }
    render(){
      return (

                {
            this.props.posts &&
          this.props.posts.map((post,i) =>{
            return(

{JSON.parse(post.form_data).title}

            )
          })
        }

    )
  }
}

function mapStateToProps(state){
    return {
    posts: state.posts
  }
}

let Container = connect(mapStateToProps, {fetchPostsWithRedux})(App);

const store = createStore(
    reducer,
    applyMiddleware(thunk)
);
ReactDOM.render(
    <Provider store={store}>
        <Container/>
    </Provider>,
    document.getElementById('app')
);

But when I am trying to make actions, reducers, containers in different files, blank page is coming. There are no errors coming in console, only three warnings as:

Warning: Accessing PropTypes via the main React package is deprecated. Use the prop-types package from npm instead.
Warning: RouterContext: React.createClass is deprecated and will be removed in version 16. Use plain JavaScript classes instead. If you're not yet ready to migrate, create-react-class is available on npm as a drop-in replacement.
Warning: Automatically setting basename using  is deprecated and will be removed in the next major release. The semantics of  are subtly different from basename. Please pass the basename explicitly in the options to createHistory.

Store.js code is as follows:
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import thunk from 'redux-thunk';
import reducer from '../reducers/loginReducer';

const store = createStore(
  reducer,
  applyMiddleware(thunk)
);
var routes =(
    <Provider store={store}>
      <Router history={browserHistory}>
        <Route path="/" component={Main}>
        <Route path="/testing" component={Testing}>
      </Router>
    </Provider>
);

Testing.js code is as:
import React from 'react';
import { render } from 'react-dom';
import ReactDOM from 'react-dom';
import loginContainer from '../containers/loginContainer';

export default class Testing extends React.Component {

    render() {
        console.log("jgkj");
        return (
                <loginContainer />
        );
    }
}
module.exports = Testing;

loginContainer.js code is as follows:
import React, {Component} from 'react';
import {  Link } from 'react-router';
import ReactDOM from 'react-dom';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { fetchPostsWithRedux,fetchPosts,fetchPostsError,fetchPostsSuccess,fetchPostsRequest } from '../actions/loginAction';

class loginContainer extends React.Component {
    componentDidMount(){
    this.props.fetchPostsWithRedux()
  }
    render(){
      return (

                {
            this.props.posts &&
          this.props.posts.map((post,i) =>{
            return(

{JSON.parse(post.form_data).title}

            )
          })
        }

    )
  }
}

function mapStateToProps(state){
    return {
    posts: state.posts
  }
}
export default connect(mapStateToProps, {fetchPostsWithRedux})(loginContainer);

loginReducer.js code is:
import {
  FETCH_REQUEST,
  FETCH_SUCCESS,
  FETCH_ERROR
} from '../actions/loginAction';

export default function reducer (state = {}, action)  {
  switch (action.type) {
    case "FETCH_REQUEST":
      return state;
    case "FETCH_SUCCESS":
      return {...state, posts: action.payload};
    default:
      return state;
  }
}

loginAction.js code is as:
export function fetchPostsRequest(){
  return {
    type: "FETCH_REQUEST"
  }
}

export function fetchPostsSuccess(payload) {
  return {
    type: "FETCH_SUCCESS",
    payload
  }
}

export function fetchPostsError() {
  return {
    type: "FETCH_ERROR"
  }
}

export function fetchPostsWithRedux() {
    return (dispatch) => {
    dispatch(fetchPostsRequest());
    return fetchPosts().then(([response, json]) =>{
        if(response.status === 200){
        dispatch(fetchPostsSuccess(json.data))
      }
      else{
        dispatch(fetchPostsError())
      }
    })
  }
}

export function fetchPosts() {
  const URL = "api-url";
  let user = JSON.parse(localStorage.getItem('user'));
  return fetch(URL, {
          method: 'POST',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            api_token: user.api_token,
            type: 'task',
          })
        }).then(response => Promise.all([response, response.json()]));
}

Answer: You class loginContainer name begins with a lower case letter which should not be the case, it should begin with a upper case letter for your transpiler, Change to
 import {bindActionCreators} from 'redux';

 class LoginContainer extends React.Component {
    componentDidMount(){
    this.props.fetchPostsWithRedux()
  }
    render(){
      return (

                {
            this.props.posts &&
          this.props.posts.map((post,i) =>{
            return(

{JSON.parse(post.form_data).title}

            )
          })
        }

    )
  }
}
function mapStateToProps(state){
    return {
    posts: state.posts
  }
}
function mapDispatchToProps(dispatch) {
     return bindActionCreators({fetchPostsWithRedux: fetchPostsWithRedux}, dispatch)

}
export default connect(mapStateToProps,mapDispatchToProps)(LoginContainer);

Also you are not using dispatch for your actions. Make use of bindActionCreators to bind your action to dispatch
Similarly in Testing.js use
import LoginContainer from '../containers/loginContainer';

export default class Testing extends React.Component {

    render() {
        console.log("jgkj");
        return (
                <LoginContainer />
        );
    }
}
module.exports = Testing;

Comment: Thanks for answering but its giving syntax error in `export default connect(mapStateToProps, {(dispatch) => { return {fetchPostsWithRedux: bindActionCreators(fetchPostsWithRedux, dispatch)}}})(LoginContainer);`
Comment: BTW its coming blank again when I am tring to use `combineReducers` as: export default combineReducers({
  Login,
  Register,
  reducer
})
Comment: In that case you need to check whether the component returned by combineReducers is used to create store
Comment: I have created an indexreducer and imported single reducer in that using combineReducer
Comment: In store.js import the indexReducer and then create store with that. Also is there any other error. Can you ask a separate question for that, maybe others also can provide their inputs on that
Comment: I have done that `import reducer from '../reducers';` and then `const middleware = [ thunk ];
const store = createStore(
 reducer,
  applyMiddleware(...middleware)
)` There is no error.
Comment: Is reducer a folder and the file inwhich you have defined combineReducer named `indexReducer.js`
Comment: reducers is a folder and then index.js in which I have defined combineReducer
Comment: Can you please ask a separate question with the concerned files, its difficult to spot here
Comment: Asked: http://stackoverflow.com/questions/43996402/redux-using-combinereducers-returning-blank-page
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/144320/discussion-between-triyugi-narayan-mani-and-shubham-khatri).
Comment: Working on something, will look at your question in a while

Blank page is coming without any error


For each linear transformation A on an n-dimensional vector space there exists a linear transformation B such that AB=0 and ρ(A)+ρ(B)=n

Question: From Halmos Linear Algebra:
For each linear transformation $A$ on an $n$-dimensional vector space there exists a linear transformation $B$ such that $AB=0$ and such that $\rho(A)+\rho(B)=n$.
I know that if $AB=0$, then $\rho(A)+\rho(B) \le n$. I am having trouble proving that there must exist a $B$ such that $AB=0$ and how to go from that to $\rho(A)+\rho(B)=n$. I think I have to assume that $\rho(B)=v(A)$ and determine the $B$ accordingly, but lost on how to do so.
Comment: What do you mean with $\rho$ and $v$?
Comment: $\rho$ being the rank and $v$ the nullity
Answer: I suppose $\rho$ must mean rank.
Hint: Find a $B$ whose range is  the null space of $A$.


Perl: "noisy logs problem" Create array of regex queries from multiple arrays/hashes

Question: Problem:
I need to pull data from auth logs for approx. 30 locations. The logs are in CSV format.
In order for the analysis to be useful the log entries must be matched up with the hours of operation of the locations. The data is stored in directories named for the time period the data covers: eg., data/june1-june30/. The CSV files are simply named with the location code
eg., LOC1.csv , LOC2.csv. Here is a sample of a typical log:
2010-06-01, 08:30:00 , 0
2010-06-01, 09:30:00 , 1
2010-06-01, 10:30:00 , 10
2010-06-01, 11:30:00 , 7
2010-06-01, 12:30:00 , 8
2010-06-01, 13:30:00 , 6
2010-06-01, 14:30:00 , 3
2010-06-01, 15:30:00 , 8
2010-06-01, 16:30:00 , 11

The entries show the number of successful authenticated sessions during the time period indicated in the 3rd field. The logs represent 24 hours of data which is useless for analysis since the hours of operation differ from location to location. The problem now becomes how to pull only the data that matches the hours of operation. The analysis must show activity for the hours of operation to be useful.
Setup - so far
I decided to create a config file using YAML with arrays/hashes for each location.
eg.,
- branch: headquarters
  abbrev: HQ
  months: [04, 06]
  DOW: [M, T, W, Th]
  hours:
      M:                [12, 13, 14, 15, 16, 17, 18]
      T:                [12, 13, 14, 15, 16, 17, 18]
      W:        [09, 10, 11, 12, 13, 14, 15,
                         16, 17, 18]
      Th:       [12, 13, 14, 15, 16, 17, 18,
                         19, 20]

The months designation shows the busiest months, as that's all we care about.
Where I'm at
The code will find the appropriate directories using the months array, then it pulls the correct CSV files using the abbrev array. So I have the files I need stored in an array @files. My question comes down to design. The results must be matched to the appropriate dates for each month. Mondays, Tuesdays ...etc. Do I create month arrays storing the dates for each day of the week?
I'm stuck and unsure where to go from here.
To clarify: The code already pulls the correct
files and loads them into an array ( using globbing and Find::File ) for each branch. The question is now about iterating through the @files array for each branch and pulling the info.
EDIT:
as per request: I will put up some code. This is the goods for getting a hold of those files
by the months indicated in the hash. That's the easy part.
foreach my $branch (@$config) {
        my $name = $branch->{'branch'};
        my $months = $branch->{'months'};
        my $abbrev = $branch->{'abbrev'};

        # find directories for busy months, load in @dirs
        my @dirs;
        foreach my $month (@$months) {
                my $regex2 = qr(stats_2010-$month.*);
                map { push(@dirs, $_) if $_ =~ $regex2 } @stats_dir;
        }

        # find csv files within directories, load in @files
        my @files;
        find(\&wanted, @dirs);
        sub wanted {
                push(@files, $_) if $_ =~ /$abbrev\.csv/;
        }

Output:
The output I'm hoping to get is: The lines from each file representing the hours of operation for that branch. I think they could be output to a separate file for the sake of simplicity. And in the same format. What makes it hard is that you have to match Mondays,Tuesdays ..etc. with dates somehow. This is due to different hours of operation for different days.
Am I making the problem harder than it needs to be? I've sat with this too long and am hoping for a fresh set of eyes to set me straight. My Perl is OK, but I need some help in the design/algorithm dept. I can figure out how to Perlify it, I think. But feel free to post Perl. I love reading good Perl!
Eventually I will average the activity for the Mondays, Tuesdays ...etc. of each month.
Thanks ~
Bubnoff
Comment: It might help to show us some of your code already, and explain the output you need.
Comment: Posted the main part of the code. Using YAML for config. @stats_dir is globbed directories array.
Comment: See below for solution using dlamblin's suggestion.
Answer: The solution I'm using is from dlamblin ( Thanks again for your help!! ).
Here's the adjusted YAML config:
- branch: Headquarters
  abbrev: HQ
  months: [04, 06]
  DOW:
      1:    {12: 1, 13: 1, 14: 1, 15: 1,
            16: 1, 17: 1, 18: 1}
      2:    {12: 2, 13: 2, 14: 2, 15: 2,
            16: 2, 17: 2, 18: 2}
      3:    {09: 3, 10: 3, 11: 3, 12: 3,
            13: 3, 14: 3, 15: 3, 16: 3, 17: 3, 18: 3}
      4:    {12: 4, 13: 4, 14: 4, 15: 4, 16: 4,
            17: 4, 18: 4, 19: 4, 20: 4}

Here's the Perl:
foreach my $dir (@dirs) {
    my $file = qq($dir/$abbrev.csv);
    open(F, $file);
    my @data=<F>;
    foreach my $line (@data) {
        chomp($line);
        unless ($line =~ m/^(\d+)-(\d+)-(\d+), (\d+):(\d+):(\d+) , (\d+)/){next;}
        my $dt = DateTime->new( year    => $1,
                                month  => $2,
                                day    => $3,
                                hour   => $4,
                                minute => $5,
                                second => $6,
                                );
         my $count = $7;
         if (exists $DOW{$dt->day_of_week} && exists $DOW{$dt->day_of_week}{$dt->hour}) {
             print $line . "\n";
         }
     }
     close(F);
}

Answer: There are modules that will give you the dow from the date and time you have, but if they are too heavy you can use Time::Local.  Parse the date--you'll need to do this anyway I think--on each line and feed it through timelocal, then through localtime which will give you the dow.  You'll have to massage $mon and $year appropriately.
$dow = ( localtime( timelocal( 0, 0, 0, $mday, $mon, $year ) ) )[6];

Once you've got the dow for the entry you'll know what to do with it.
Comment: Thanks, I will check that out. That would simplify things.
Answer: Convert the Day of Week to a number when Monday is 1 and Sunday is 7. Then create a hash that looks like 1=>{12=>1,13=>1,14=>1,15=>1,16=>1,17=>1,18=>1},2=>{12=>1,13=>1,14=>1,15=>1,16=>1,17=>1,18=>1},... (notice how DOW in your YAML is redundant).
so far:
use DateTime;
foreach $file (@files) {
  open F "<$file";
  foreach $line (<F>) {
    $line =~ m/^(\d+)-(\d+)-(\d+), (\d+):(\d+):(\d+) , (\d+)/;
    $dt = DateTime->new( year   => $1,
                         month  => $2,
                         day    => $3,
                         hour   => $4,
                         minute => $5,
                         second => $6,
                       );
    $count = $7; #Possibly redundant; Use it if you're aggregating.
    if (exits $selection{$dt->day_of_week}
     && exists $selection{$dt->day_of_week}{$dt->hour}) {
      print $line;
    }
  }
}

Comment: I see where you're going. I'll try this and check back in later. Thanks!


Creating entity in Rules causes PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry

Question: My application based on CRM-Core.
I am using several rules which launch on the event "After saving a new crm core contact" and each has a crm_core_activity entity created as the rule's action.
Is it possible that the rules happen simultaneously which causes SQL error - trying to set same activity_id (which is primary key)?
Here is the error:
<code>PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '879' for key 'PRIMARY': INSERT INTO {crm_core_activity} (activity_id, revision_id, uid, type, title, created, changed, uuid) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7); Array ( [:db_insert_placeholder_0] => 879 [:db_insert_placeholder_1] => 1552 [:db_insert_placeholder_2] => 0 [:db_insert_placeholder_3] => email [:db_insert_placeholder_4] => תודה שפנית אלינו! [:db_insert_placeholder_5] => 1465830228 [:db_insert_placeholder_6] => 1465830228 [:db_insert_placeholder_7] => 4e87b796-fc8d-49f4-85f4-9ac944563576 ) in drupal_write_record() (line 7316 of /home/roi/sites/staging/0108-ormil/drupal-7.38/includes/common.inc).
</code>
The error happens randomly which makes me think this is a timing issue between multiple rules on the same trigger.
Answer: Have a look at issue # 430274, which explains that "after saving something" actually happens ... "before saving something" (which is not a bug, simply how the Rules module  works ...).
A possible compromise to avoid these kind of issues, is to transform what's you're trying to do into a Rules Component, so that your original Rule "schedules the execution" (using the Rules Scheduler submodule) of that Rules Component (eg after only a few secs or mins later on ... if your cron job runs frequent enough, if not it'll be next time cron runs). This compromise will ensure that at the time the Rules Component is executed, the entity is for sure saved ... (so that can't be the reason anymore then why things don't work as expected ...).
Note: it's tough (virtually impossible) to pinpoint what exactly is causing your issue without knowing what exactly those rules look like. Adding a copy of your exported rules to the question may possibly help, but still. However, I'd recommend you to do some Rules debugging, using any of the techniques I described in my answer to How can I display the value of a variable inside a condition?
Comment: Which entity, in this case, do you think launching the rule 'before saving'? I also thought of scheduling components to avoid the simultaneous creation of entities, but I can't see the launching before or after should matter.
I also don't understand why the SQL 'insert' statement explicitly dictates the id (the primary auto increment key) and not letting mysql do it's part of autoincrementing.
Comment: @roi : See the "note" I added to my answer, I'm afraid debugging in your own environment is about the only thing you can do. Turn on the Rules Evaluation Log and check if what you see being executed, matches with your expectations (if not you may get a clue what's wrong).
Answer: The problem was that I created an entity using code (implementing hook_rules_action_info()). In the hook I created a new entity and also saved it.
In the rule I both called this hook implementation (create+save an entity) and also explicitly saved it is a rules action.


Variavel Calendar não é reconhecida pelo android

Question: Estou a declarar assim no meu projecto e não consegue reconhecer a variavel calendar "Cannot resolve symbol 'Calendar'"
Calendar calendario= new Calendar.getInstance();

Answer: Use:
Calendar calendar = Calendar.getInstance();

Não use new, afinal getInstance é um método estático.


Const keyword appended to the end of a function definition... what does it do?

Question: Suppose I define a function in C++ as follows:
void foo(int &x) const {
  x = x+10;
}

And suppose I call it as follows:
int x = 5;
foo(x);

Now typically (without the const keyword), this would successfully change the value of x from the caller's perspective since the variable is passed by reference. Does the const keyword change this? (i.e. From the caller's perspective, is the value of x now 15?)
I guess I'm confused as to what the const keyword does when it is appended to the end of a function definition... any help is appreciated.
Comment: Your example is incomplete, since the `const` qualifier can only be applied to class member functions.
Answer: This won't work.  You can only const-qualify a member function, not an ordinary nonmember function.
For a member function, it means that the implicit this parameter is const-qualified, so you can't call any non-const-qualified member functions or modify any non-mutable data members of the class instance on which the member function was called.
Comment: @dfetter88:  That's exactly what it does.  In a member function that is not const qualified, `this` is of type `T*`.  In a member function that is const qualified, `this` is of type `const T*`.
Comment: @defetter: There's nothing more to your particular example, since it's ill-formed. Had it been a member function of the form `R function(Args) cv`, the type of `this` is `cv class_type*`. Do you have a [C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)?
Comment: And if you want to do what you described, prevent `x` from being changed, you would define the function as `void foo(const int &x)`
Comment: The C++ FAQ handles this: http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.10.
Comment: So does it essentially make `this` a constant within the method? Or is there more to it?


7-Limit tuned 12 tones?

Question: I tried to tune the 12 tones differently to gain more harmony. Rather than equal temperament or just intonation, I picked 7-limit tuning. Here're the tones:

    C = 1/1
    C♯ = 21/20
    D = 10/9
    D♯/E♭ = 7/6
    E = 5/4
    F = 4/3
    F♯/G♭ = 7/5
    G = 3/2
    A♭ = 14/9
    A = 5/3
    A♯ = 7/4
    C♭ = 28/15

This places the tones in a 3×2×2 grid, and approximates 12-TET well. (Like just intonation does in a 4×3 grid)
My questions are:

Is G major chord out of tune in this tuning?
Does B mean C♭?
Are C7 chord and F7 chord enough to have a chord progression?
What is the name of D♯-F♯-A♯-C chord?
Comment: 4. Cm7b5 is one name. But not with those note names, just the sound.
Comment: @Tim -- I might be more inclined to call that an **Ebm6** (or possibly a **D#m6**); respelling needed in any case....
Answer:
No.  The B is 56:45 above the G, which is rather lower than a just major third at 5:4.  It's about 8 cents low, which is less of a difference than the difference between the just major third and the equal tempered major third.  That might be acceptable.  But the ratio between G and D, after adjusting the octave, is 40:27 rather than 3:2, which is in my opinion unusable as a consonant perfect fifth.
Yes.
I don't understand this question.
I'll leave this for others to argue about.

I'll also note that with most attempts to tune a keyboard to "just intonation" some intervals are too dissonant to be useful as a perfect fifth.  The E to B interval here, for example,
Comment: 3. I mean whether it's possible to have chord progression such as I - V - vi - IV? The only harmonic seventh chords are C7 and F7.
Comment: @DannyuNDos I wrote this answer having read the question carelessly and thinking that you were using 9:8 for D.  I do not think the G-to-D fifth is useable if D is 10:9.  I've edited the answer accordingly.

7-Limit tuned 12 tones?


Rotating the area between two functions around the x-axis: two methods, one correct and one is not. Why?

Question: I am taking a class in basic calculus and I came across a problem on rotation volumes that when solved with one (to me seemingly valid method) gives incorrect results. I am curious as to why and I hope someone here will be able to explain why my first method does not work.
The problem:
Calculate the volume  of the rotational body that arises when the area limited by the line $y = x$ and the parabola $y = x^2$ is rotated around the x-axis.
My first (incorrect) solution:
Use a definite integral with upper and lower bounds where the line and the parabola intersect.
$x^2 = x$
gives $x_1 = 0$ and $x_2 = 1$
My idea was that since radius $R$ for the rotation is equal to the distance in $y$ between $y = x$ and $y = x^2$ I could insert $x-x^2$ as $R$ in $A = \pi R^2$
Using the disc method and $x_1$ and $x_2$ as as our lower and upper bounds gives
$V = \int_{x_1}^{x_2}\pi(x-x^2)^2dx$
I don't like that integral so I wanted to expand the $(x-x^2)^2$ factor by using the formula:
$(a-b)^2 = a^2 + b^2 - 2ab$
This resulted in:
$V = \int_{x_1}^{x_2}\pi(x^2+x^4-2x^3)dx$
$\pi$ is a constant so I moved it out of the integral, and split the integral up resulting in:
$\pi\int_{x_1}^{x_2}x^2dx + \pi\int_{x_1}^{x_2}x^4dx - \pi\int_{x_1}^{x_2}2x^3dx$
Integration gave the following:
$\pi\int_{x_1}^{x_2}x^2dx = \pi\frac{x^3}{3}|_0^1 = \pi(\frac{1^3}{3}-\frac{0^3}{3}) = \frac{\pi}{3}$
$\pi\int_{x_1}^{x_2}x^4dx = \pi\frac{x^5}{5}|_0^1 = \pi(\frac{1^5}{5}-\frac{0^5}{5}) = \frac{\pi}{5}$
$-\pi\int_{x_1}^{x_2}2x^3dx = -\pi\frac{x^4}{2}|_0^1 = -\pi(\frac{1^4}{2}-\frac{0^4}{2}) = -\frac{\pi}{2}$
Adding these together gave me the incorrect answer:
$V = \frac{\pi}{30}$
The second (correct) solution:
Again using the disc method with lower and upper bounds $x_1$ and $x_2$ but expressing $V$ as the difference between the rotational volume of $y = x$ and $y = x^2$ gives:
$V = \pi\int_{x_1}^{x_2}(x)^2dx - \pi\int_{x_1}^{x_2}(x^2)^2dx = \pi\frac{x^3}{3}|_0^1 - \pi\frac{x^5}{5}|_0^1 = \frac{\pi}{3}-\frac{\pi}{5} = \frac{2\pi}{15}$
The question:
Why did the first solution not work?
Comment: I mean in your first attempt you directly subtracted $(x-x^2)^2$, in your second attempt you did $(x)^2-(x^2)^2$ and clearly these two expressions are not the same
Comment: $y=x$ is a cone when rotated, when you remove the volume of $y=x^2$ from $y=x$ you get the volume of the cone with its centre part ($y=x^2$) removed,  plot $y=x-x^2$ and check its volume when rotated, the two figures are not the same
Comment: Why would the figures looking different have that severe of an impact when rotating? The end goal is to find a volume, which is a number. The figure that arise from $y=x-x^2$ represents the difference between $y=x$ and $y=x^2$. The same difference that we get when we remove the volume of $x^2$ rotated with the second integral in the second method.
Comment: In your first solution you set $(a-b)^2=a^2-b^2$
Comment: Where did I do that?
Comment: When You subtracted the radii and squared the difference,
Comment: I spotted an error in the Area formula. Should be $A = \pi R^2$ not $A= \pi R$. Was this what you commented on?
Comment: No, $(x-x^2)^2$ is not equal to $x^2-x^4$
Comment: Where did I write that? I wrote $(x-x^2)^2 = x^2 + x^4 - 2x^3$
Answer: Imagine a pie which has a circular cut around the middle of the pie.  The cut is halfway between the center and the crust.  There is an inner circle and an outer ring and each of them has the same 'height'.  The outer ring contains much more pie because the rotation of something further from the center traces out more volume than something close to the center.
To put numbers to it, assume a cylindrical pie with a radius of 8 inches and a height of 1 inch.  The inside cylinder will have volume 1*pi*(4)^2 = 16pi.  The entire pie will have a volume of 1*pi*(8)^2 = 64pi.  So by subtraction, the outer ring will have 48pi volume.
Your first attempt puts the height to be rotated right next to the center instead of further away, so the volume ends up smaller.


SharePoint and deployment of global.asax code

Question: I want to start logging some custom messages into the ULS from my custom SharePoint code.  My code is running inside list item receivers attached to some lists.  I'd like to configure this logging mechanism within the application start event handler in global.asax.  What's the best-practices way to deploy a SharePoint solution package that modifies global.asax?
Answer: I don't know about "best practice", but I would be quite keen on making the edits via code in the feature reciever.
With a line that backs up the file for later restoration.
For logging, we have used Scott hilliers code here to create a trace provider to log with.
Works a treat.
I should clarify that we use a static readonly wrapper for the trace provider
static readonly Log instance = new Log();

that registers itself with the code
SPFarm farm = SPFarm.Local;
Guid traceGuid = farm.TraceSessionGuid;
unit result = NativeMethods.RegisterTraceGuids(ControlCallback, null, ref traceGuid, 0, IntPrt.Zero, null, null, out hTraceReg);
System.Diagnostics.Debug.Assert(result==NativeMethods.ERROR_SUCCESS, "TraceRegister result = " + result.ToString());

Gah!
This then gets instanciated only once and we use the destructor to unregister it.
Comment: Do you have pointers on how to best safely modify that file?  It seems pretty scary to just find the method's opening "{" and start pushing in my code, but I guess that might be okay.  I was half hoping for something like SharePoint does with web.config files, but global.asax seems easier in a way.
Comment: Nah, it seems a bit scary to me aswell. That is why I liked the Trace Provider way, not necessary to add to the global.asax.
Comment: I have added a http module and have been using Log4net in a complex sharepoint farm the log provider can fail at random, and then there is the fact that filtering through the ULogs is pain.


Storybook with absolute paths

Question: In our app we use absolute paths for importing. As an example if we have a path which is relative to the src folder, we can just write import module from "components/myComponent".
The issue is that this is not working in storybook. After some digging it turns out you can take the default webpack config and extend it as needed as seen in the documentation here. My thought process based on this was to simply push my src directory on the modules array like so,
module.exports = (baseConfig, env, defaultConfig) => {
    // Extend defaultConfig as you need.
    defaultConfig.resolve.modules.push("src");

    return defaultConfig;
};

After doing this however, I end up getting the following error when trying to run storybook.

ERROR in ./node_modules/@storybook/addon-knobs/src/react/index.js
  Module parse failed: Unexpected token (26:9) You may need an
  appropriate loader to handle this file type. |   const initialContent
  = getStory(context); |   const props = { context, storyFn: getStory, channel, knobStore, initialContent }; |   return ; | }; |

Really not sure where to go from here.
Answer: I got this issue after using CLI and I was able to resolve it by modifying my .storybook/main.js to:
const path = require('path');

module.exports = {
  ...other settings....,

  webpackFinal: async (config) => {
    config.resolve.modules = [
      ...(config.resolve.modules || []),
      path.resolve(__dirname, "../src"),
    ];

    return config;
  },

}

Note that I am using Typescript and ReactJS and the base URL for my Typescript file is set to src. That is my tsconfig has this:
{
...,
 "baseUrl": "./src/",
}

Comment: Should one also include 'node_modules' the way it was done in the approved answer?
Comment: He doesn't need to as he's spreading Storybook modules in there, which already has node_modules
Comment: Note: if you have `"baseUrl": ".",`, then you'd resolve using "../" instead
Answer: This looks very similar to this GitHub issue https://github.com/storybooks/storybook/issues/2704 where the suggested fix is to make the src directory absolute in your webpack config.
module.exports = {
  //...
  resolve: {
    modules: [path.resolve(__dirname, 'src'), 'node_modules']
  }
};

Answer: Similar to @Sahin D.'s answer above but it looks like it's been updated since.
// .storybook/main.js

const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');

module.exports = {
  webpackFinal: async (config) => {
    config.resolve.plugins = [
      ...(config.resolve.plugins || []),
      new TsconfigPathsPlugin({
        extensions: config.resolve.extensions,
      }),
    ];
    return config;
  },
};

Source: https://storybook.js.org/docs/react/configure/webpack#typescript-module-resolution
Comment: I ended up ditching storybook altogether and just used next13 as a storybook to show my components. Too many issues with storybook time after time for me personally
Comment: Doesn't work for webpack 5+
Comment: This article talks about this solution
https://www.getfishtank.com/blog/fix-typescript-path-mapping-in-storybook
Answer: And also you can resolve your paths in storybook in this way:

// .storybook/main.js

const path = require("path");
module.exports = {
  "webpackFinal": async (config) => {
    config.resolve.alias['res'] = path.resolve(__dirname, '../src/res'),
    config.resolve.alias['components'] = path.resolve(__dirname, '../src/components')
    return config
  }
}

For example, my absolute addresses are "components/common/Button" and "res/Images" which will resolve on the storybook's build.
Maybe it's not the best answer, but I hope it would be helpful!
Answer: I've tried other solutions, but they didn't help. So I used a webpack plugin for my case to solve this issue out.
After following the instructions here: https://storybook.js.org/docs/riot/configure/webpack#extending-storybooks-webpack-config
I'm using the TypeScript version, and I have changed the webpackFinal field as the following:
// main.ts
import { TsconfigPathsPlugin } from 'tsconfig-paths-webpack-plugin';
import type { Configuration } from 'webpack';

export default {
  // ... other fields
  webpackFinal: async (config: Configuration) => {
    if (!config.resolve) {
      config.resolve = {};
    }

    config.resolve.plugins = [
      ...(config.resolve.plugins || []),
      new TsconfigPathsPlugin(),
    ];

    return config;
  },
};

Comment: this had worked to resolve it for me, with ts modules

Storybook with absolute paths


Como fazer translação de uma imagem em python?

Question: Minha intenção é fazer como na figura abaixo:
http://postimg.org/image/pdb6urf1d/
Minha função:
def translacao(imagem1):
    imagem1.save("translate.png")
    destino = Image.open("translate.png")
    destino = destino.resize((400,400))
    #Tamanho Imagem - Largura e Altura
    width = destino.size[0]
    height = destino.size[1]
    x_loc = 20
    y_loc = 20
    x_loc = int(x_loc)
    y_loc = int(y_loc)
    imagem1.convert("RGB")
    destino.convert("RGB")
    for y in range(0, height):
        for x in range(0, width):
             xy = (x, y)
             red, green, blue = destino.getpixel(xy)
             x += x_loc
             y += y_loc
            destino.putpixel((x, y), (red, green, blue))

    return destino.save("translate.png")

Aparece esse erro:
  C:\Python27\python.exe C:/Users/Mikhail/PycharmProjects/SistMult/histograma.py
  Traceback (most recent call last):
  File "C:/Users/Mikhail/PycharmProjects/SistMult/histograma.py", line 289, in <module>
  translacao(imagem1)
  File "C:/Users/Mikhail/PycharmProjects/SistMult/histograma.py", line 262, in translacao
  destino.putpixel((x, y), (red, green, blue))
  File "C:\Python27\lib\site-packages\PIL\Image.py", line 1269, in putpixel
  return self.im.putpixel(xy, value)
  IndexError: image index out of range

  Process finished with exit code 1

Comment: O erro diz que vc está ultrapassando o limite da imagem, ela tem 400x400 e em determinado momento do for vc está colocando +20 indo para 401, 402... 420, tentando colocar pixel alem do limite.
Comment: O que eu altero no código para fazer a Translação na Imagem?
Answer: Meu colega conseguiu resolver o problema. Solução logo abaixo:
destino = Image.open("foto.png")
      #Tamanho Imagem - Largura e Altura
      lar = destino.size[0]
      alt = destino.size[1]
      x_loc = 200
      y_loc = 200
      imagem_original = np.asarray(destino.convert('RGB'))
      for x in range(lar):
           for y in range(alt):
                if x >= x_loc and y >= y_loc:
                     yo = x - x_loc
                     xo = y - y_loc
                     destino.putpixel((x,y), (imagem_original[xo,yo][0],imagem_original[xo,yo][1],imagem_original[xo,yo][2]))
                else:
                     destino.putpixel((x,y), (255, 255, 255, 255))
      destino.save("translate.png")


How can I make a delay for sending an ajax request?

Question: Here is my code:
$("input").on('keydown', function(){
    $.ajax({
        url :  '/files/tags_autocomplete.php',
        dataType : 'JSON',
        success : function (tags) {
            $("ul").html(tags.output);
        }
    });
});

My code suggests some tags (the ones that have a matched substring  with what the user has written so far) to user as an autocomplete box when he is typing his tags.
What's my problem? My current code sends a new ajax request per each keydown. For example, if the user writes something, my script sends 9 ajax requests which seems like a nightmare.
Anyway, how can I handle that? I mean do I need to implement a delay for sending? Something like "don't send the request until 1 sec after last character inserted"? or is there any better idea?
Comment: You might consider jQuery UI autocomplete. It has your requested functionality built in. http://jqueryui.com/autocomplete/. It might not be worth using *just* for autocomplete, but it's worth a look.
Comment: @JasonP Thank you for the link you provided .. but I seen that before .. and yes exactly as you said, using it just for autocomplete isn't affordable. though I heard we can download every part of jQuery UI we need *(for example, we can download only autocomplete part)*
Answer: You could create a simple throttle mechanism
$("input").on('keydown', function(){

    clearTimeout( $(this).data('timer'); )

    var timer = setTimeout(function() {
      $.ajax({
          url :  '/files/tags_autocomplete.php',
          dataType : 'JSON',
          success : function (tags) {
              $("ul").html(tags.output);
          }
      });
    }, 500);

    $(this).data('timer', timer);
});

Comment: At the time that line runs, `xhr` wouldn't be the ajax request, that is correct. Only after 500ms would `xhr` be the ajax request, but that's the only time it would need to be aborted, so it should work just fine.
Comment: @stack - every time the user types something, a timeout is set so that the ajax calls happens a little later. If the user types something more, the previous timeout is cleared, and a new timeout is set. That way, the ajax call only happens when the user stops typing for more than half a second (500ms), effectively throttling the calls.
Comment: @stack - That example has the variable inside the function, so it won't "remember" it the next time the function is called. It has to be like [this](https://jsfiddle.net/adeneo/vj5ojtck/1/), but I'm just using `data()` to avoid the global variable and to store the timer on each element in case there are multiple elements matching the selector.
Comment: Oh, great .. I was something exactly like this .. upvote. Just for my information, is this a standard approach? For example how stackoverflow does it?
Comment: @MartinAJ - It's not uncommon. I have no idea what SO does ?
Comment: I meant was [how SO handle this](http://i.stack.imgur.com/8tuTU.png) ... but never mind.
Comment: Ok well, now there is a small problem .. when the user writes `java` and waits `0.5 sec`, a request will be sent for `java` input. then before returning matched tags by php script, the user continues to writing and makes it `javascript`. in this case, first the result of `java` input will be shown, and then after a while the result of `javascript` input. I want to know, can I **abort** everything when the user starts writing again? *(even when a request has been sent and no result returned yet)*
Comment: That's generally not an issue, as most servers will return results almost instantly, but if your server is slow or is returning large datasets, you can try to play with the timeout and shorten the 500ms a little etc. You could probably abort the ajax call as well, but it does get a little more complicated, and you can't always abort calls that have been made etc. but maybe some variaton of something like this would work -> https://jsfiddle.net/adeneo/kzgzponL/
Comment: Sorry to ping you again, just one thing: Defining `timeout` within each `keydown` event could cause issue? I mean you appear to define `xhr` inside of `setTimeout;` how can `xhr : xhr` at `$(this).data({timer : timer, xhr : xhr});` reference `xhr` within `setTimeout` which occurs 500 ms after `$(this).data({timer : timer, xhr : xhr});` call?
Comment: Maybe you want to take a look at [this](http://stackoverflow.com/questions/39714740/cannot-use-in-operator-to-search-for-sth-in-undefined).
Comment: @MartinAJ - aah, I see the issue there, the answers you've gotten is the same as this one before I added the aborts you wanted, so I'll roll this answer back, and the aborts in the other questions, hopefully working this time, as I just forgot to check the object before using `in`, and that's really the only change needed.
Comment: Seems nice, Upvote. But honestly I cannot understand how your code works. Can you please add some explanations to your answer and explain why you remove `timeOut` in the first of your code and set it in the end of your code?! What's the reason?!
Comment: Thanks for the explanation. But my main confusion is what's the reason of using `.data()` in this case? What's wrong whit [this](https://jsfiddle.net/vj5ojtck/)?
Comment: @adeneo - How can I use the timer function to delay the success callback of an **Ajax** call (which is being used in tandem with Django view)? The scenario will be, variables are sent as an array to the **Django function** and after processing all the inputs, the callback should happen **after a certain delay**. Without a delay in place the setup is otherwise working but **sometimes the view throws up the intermediate values (results) too**.


All linear functions are homogeneous of degree one?

Question: I was looking through the Wikipedia page of "Homogeneous functions" and it stated that any linear function that maps V onto W is homogeneous of degree one. However, when I try to apply the definition of a homogeneous function to a line defined by one variable "v" and a non-zero constant "z":
f(v)=v+z
f(tv)=(tv)+z
f(tv)=t(v+z/t)≠tf(v)
I find that the line is not homogeneous.
So why is it that a linear function is always homogeneous even though the example I gave shows that it's not? What conceptual/calculation mistake did I make in in the process?
Comment: By the definition in (https://en.wikipedia.org/wiki/Linear_map#Definition_and_first_consequences) though your function wouldn't be a linear map anymore. The page on (https://en.wikipedia.org/wiki/Linear_function) defines "linear function" either as a polynomial of degree 0 or 1 (that is, $y=ax+b$ or $y=c$) or a linear map. For the above problem, the *linear maps* must have been meant. Article should be updated for clarity though.
Comment: See the definition of "linear function" that applies to vector spaces.  I assume $V,W$ are vector spaces.
Answer: a homogeneous function is a polynomial function  which all the
terms have the same degree. then in your example (in this case of
one dimension) $v \rightarrow av + z$ is not a homogeneous
polynomial since $z$ is a vector constant, not a variable.


Does Naive Bayes( library:klar) in R calculates denominator of conditional probability while giving output?

Question: Generally, when using Naive Bayes for classification, denominator is ignored as probability is directly proportional to the numerator as denominator is same for all the classes.
So, I want to know if Naive Bayes in R includes denominator calculation while giving/predicting output for the values other than training data ?
Answer: Excerpt from the documentation:

Values
An object of class "NaiveBayes" including components:
apriori
      Class distribution for the dependent variable.
tables
      A list of tables, one for each predictor variable. For each categorical variable a table giving, for each attribute level, the  conditional probabilities given the target class. For each numeric
  variable, a table giving, for each target class, mean and standard
  deviation of the (sub-)variable or a object of class density.

So the output depends on the input type. As about probabilities: if it is said that the software returns probabilities, then they need to be normalized (i.e. the denominator needs to be used), because otherwise they wouldn't be probabilities (the numbers would not agree with the axioms of probability).


Prove that there are two compact subsets $K_1$ and $K_2$ of $X$ such that $K = K_1 \cup K_2, K_1 \subset U_1, K_2 \subset U_2$.

Question: Let $X$ be a Hausdorff space, let $K$ be a compact subset of $X$, and let $U_1,U_2$ be an open sets of $X$ such that $K\subset U_1\cup U_2$. Prove that there are two compact subsets $K_1$ and $K_2$ of $X$ such that $K = K_1 \cup K_2, K_1 \subset U_1, K_2 \subset U_2$.
Hello, could someone guide me to solve this problem, please?
Best regards.
Answer: $K\setminus U_1$ and $K\setminus U_2$ are disjoint compact sets. By a standard theorem we can find disjoint open sets $V_1$ and $V_2$ such that $K\setminus U_1 \subset V_1$ and $K\setminus U_2 \subset V_2$. You can take $K_1=K\setminus V_1$ and $K_2=K\setminus V_2$. Let me know if you need more details or reference for the theorem I have used.
Comment: @Emmy  This is Theorem 9, page 141 in Kelley's General Topology. The proof is obtained by repeatedly applying Hausdorff property.
Comment: Thank you very much, I am understanding the idea. I would be very useful to know more details of the theorem you just used, thanks in advance.


Cannot reshape array of size 0 into shape

Question: After a correction on the program i am using, i get an error on my code :
import numpy as np
import gzip
import struct

def load_images(filename):
    # Open and unzip the file of images :
    with gzip.open(filename, 'rb') as f:
        # read the header, information into a bunch of variables:
        _ignored, n_images, image_columns, image_rows = struct.unpack('>IIII', bytearray(f.read()[:16]))
        print(_ignored, n_images, image_columns, image_rows)
        print(f.read()[:16])
        # read all the pixels into a long numpy array :
        all_pixels = np.frombuffer(f.read(), dtype=np.uint8)
        print(all_pixels)
        print(all_pixels.shape)
        print(all_pixels.ndim)
        # reshape the array into a matrix where each line is an image:
        images_matrix = all_pixels.reshape(n_images, image_columns * image_rows)

I get this error:
load_images("\\MNIST\\train-images-idx3-ubyte.gz")
2051 60000 28 28
b''
[]
(0,)
1
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "<input>", line 19, in load_images
ValueError: cannot reshape array of size 0 into shape (60000,784)

I tried to defined the array, but still not working....
Answer: You read() the file twice. After the first read, the cursor is placed at the bottom. So if you read again ,it does not return anything.
Your object is empty so it is impossible to resize.
For more information click here
Answer: The problem is that in the line that is supposed to grab the data from the file (all_pixels = np.frombuffer(f.read(), dtype=np.uint8)), the call to f.read() does not read anything, resulting in an empty array, which you cannot reshape, for obvious reasons.
The underlying reason is that file.read() without any argument will read/consume all the bytes from the open file. So by the next file.read() call, you are at the end of the file and nothing is fetched.
Instead, it looks like you would want to read the first 16 bytes as header, and read the rest as data.
To do so, you should replace your first call to .read() with the number of bytes you want to read for the header.
This will ensure that you get read only the first few bytes, leaving the rest to be read by the subsequent f.read() call:
import numpy as np
import gzip
import struct

def load_images(filename):
    # Open and unzip the file of images :
    with gzip.open(filename, 'rb') as f:
        header = f.read(16)  # read the header bytes
        # read the header, information into a bunch of variables:
        _ignored, n_images, image_columns, image_rows = struct.unpack('>IIII', bytearray(header))
        print(_ignored, n_images, image_columns, image_rows)
        print(header)
        # read all the pixels into a long numpy array:
        data = f.read()  # read the data bytes
        all_pixels = np.frombuffer(data, dtype=np.uint8)
        print(all_pixels)
        print(all_pixels.shape)
        print(all_pixels.ndim)
        # reshape the array into a matrix where each line is an image:
        images_matrix = all_pixels.reshape(n_images, image_columns * image_rows)


Effect of muted strings on chord formation

Question: Many chord formations ask for one or more strings to be muted.  IF, that string when played OPEN is one of the notes forming the triad chord, is it okay to use chord formations that include notes that are repeated, and are part of the triad?
In other words, can any note that is part of the triad be included in the chord form and played instead of muted? ?
Comment: I'm new to this board.  Can everyone see this comment?  Thanks to the expert answers on my question.  I sometimes seek alternate chord formations, to make my playing easier.  This question came from forming a C9 chord. My voicing. to make it easier for me.. is Muted6th, C, G, Bb, D, G. This is a barre at the 3rd fret, with 6string skipped( or muted), and 4th string at 5th fret.   This also makes the form useable for Bb9, B9, C9,C#9, etc.Thanks to all for the answers... very much appreciated.........Pops
Comment: I can see your comment.  I'd point out that omitting the E from that particular chord is problematic, as it is a fairly important note for the chord.  If you are going to remove a note from a chord, it's usually the fifth (G for this chord).  I'd recommend playing C, E, Bb, D for this.
Answer: Absolutely. A basic triad is three notes - no surprise there! They can be played in any order, and doubled or tripled which is often the case with guitar. Any open string that's one of the three can be part of the chord - although sometimes a barre will get in their way.
Sometimes they won't sound so good. Take an open C chord. The bottom string open being E will fit, although that gives a first inversion, not the strongest sounding. Make that low note a G, and it sounds more solid. The lowest note doesn't have to be the root, even though an awful lot of pundits seem to advocate this.
Comment: I'm new to this board. Can everyone see this comment? Thanks to the expert answers on my question. I sometimes seek alternate chord formations, to make my playing easier. This question came from forming a C9 chord. My voicing. to make it easier for me.. is Muted6th, C, G, Bb, D, G. This is a barre at the 3rd fret, with 6string skipped( or muted), and 4th string at 5th fret. This also makes the form useable for Bb9, B9, C9,C#9, etc.Thanks to all for the answers... very much appreciated.........Pops – JBrimmer
Comment: Yes, your comment is for all to see. It's good that people try making their own shapes for chords. It's doubtful anyone will find one that's never been used before, but the point is that people use a bit of theory to come up with their own ideas. It's how I sometimes get my students to produce a chord shape. There's the notes - get on with it! Somewhat better than the 'I'm here - feed me' brigade. Well done, keep it up! Brutal? Possibly. Realistic? Definitely!
Answer: Yes. Chords are defined by the notes they contain, not the order of those notes. There are multiple ways to form every chord, and these different formations are called "voicings." It is fine if the same note is played on different strings - there are only three notes in a triad, yet many guitar voicings use all six strings.
One thing to keep in mind, though, is the lowest sounding note in your voicing. Generally, you want the root of the chord to be sounding the lowest. So, if you are playing an F chord, you want the note F to be in the bass. This is called "root position." A voicing with a different chord tone in the bass is called an "inversion."
Answer: This largely is based on the context that you are playing the chords in.  If you are just playing for yourself, then you can definitely use whatever chord voicings you like.  If you are trying to play someone else's songs, like learning a cover song, if you play those extra notes, you're not really playing what the songs is.  This can be ok if you're not trying to play the song exactly like the original.  In some cases, you and/or the audience may never notice the difference between the original and the change in voicing that you've decided upon.
If you are trying to emulate a particular style of music, changing voicings may pose a larger problem, particularly for voice leading.  If you're not familiar with the rules of voice leading, the general idea is that there are "rules" for how to go about voicing chords and how those voices move from chord to chord, which allow the different voices of the chords to remain independent.  Proper voice leading can lead to a richer sounding harmony and by breaking these conventions, it can take away from the fullness/richness of the harmony in general.  This is most common in Classical music but you can certainly find other styles of music that employee these voice leading rules.  You'll find most often that proper voice leading on guitar is best accommodated by the open chord voicings.  One or two notes that are in the chord may be dropped to maintain proper voice leading, so adding these back into the mix can subvert voice independence and remove the richness of the harmony.  This is something that a newer player or someone that mostly plays rock and pop would likely not notice but can make a fairly big difference in the overall feel of the harmony.
You also want to pay attention to your bass note, as Peter mentioned in his answer.  Changing the lowest note of your chord, called an inversion, can drastically change the feel of a given chord, particularly if you are putting the third in the bass, which feels much less stable.  A good example of this would be the open C voicing, where you typically mute the low E string, even though the E is part of the chord.  If you add the E in, the chord will usually feel less stable and more dissonant.  There are also what we call Functions for different chords and inverting chords can affect the Function or the effectiveness of the Function.  Back to the C/E example, this chord would have a stronger desire to resolve to F than a normal C chord, so it would work best in a situation where it moves to F.  There are plenty of ways to incorporate inversions but it's a good idea to be aware of how it is affecting the overall feel of the harmony.
You should also be mindful of whether or not you're playing with a bass player, or another instrument that may be playing a lower note than your lowest.  If the bass player is playing a low C, then the overall chord would be describe just as C, not C/E but some guitar players may still refer to the voicing of the chord as C/E.  If the bass player is playing the same octave as the C you are playing, and then you decide to add the E in the bass, you're effectively changing the harmony to C/E because the bass player is actually not playing the lowest note anymore.  You can also run into chord voicings getting a little muddy sounding if the note you're adding into the mix is particularly close to what the bass player is playing, so you'll want to pay attention to that.
Answer: It is technically fine, but placing different notes of a chord in the bottom of a chord (bottom meaning lowest pitch) results in different inversions and these can sound different, and sometimes it just won't sound best but it depends on the sound you are shooting for.
If you have a bass player you may sometimes even want to avoid playing the low E or even A strings because the bass player will have that sonic range covered.  Your sound will be more focused if you play simpler chords, but again it depends on the sound you are shooting for.  ;-)
If your motivation for asking the question is that it is easier to strum all the strings, I recommend you practice your strumming hand so that you can reliably strum only the strings you want.  Personally I found this hard to do at first, but after some time it has become second nature to me.  If you don't strum or pick the string, muting it is less important.


What does the "name" parameter mean in the syscall_32.tbl linux file?

Question: I am adding some custom system calls to linux Fedora and I am currently trying to update "syscall_32.tbl". The only hiccup is that I am not too sure what the name field for the call table means.
Is this something we just make up? As in a name that we decide to call this particular system call?
For example the structure of the table is:
<number> <abi> <name> <entry point> <compat entry point>

For the <name> section is this a parameter that we decide on and just enter there? Or is it something more specific like the filename that the system call is located in?
Comment: When I tried a couple years ago syscalls were impossible to extend without kernel recompiltaion. Are you writing a module?
Answer: There is a system call table in the kernel, listing all the system calls and their implementing functions. The user-land requests a system call by specifying the index number of the syscall. Therefore this index number must match between kernel compilations and user-land code compilations. Since this list is an error-prone thing to maintain, the system call table that you have found was introduced, and code is generated from it automatically. That table correlates the system calls: their index number, the name to be used in the user-land, and the kernel function name implementing the system call. From this table, the Makefile generates the header files.
There is a header file syscalls_xx.h, it defines the table within the kernel (it lists all the kernel functions implementing the syscalls by their index).
There is another header file unistd_xx.h, it provides #define's for the user-land, listing the syscall index numbers by name. The name field you are asking will get into this list, by which the user-land can refer to this system call: __NR_<xxx>. This header file is copied and used in user-space code so that the syscall index numbers can be referenced by name (see the glibc sources, how these are used).
syscall_32.tbl:
350     i386    finit_module            sys_finit_module

unistd_32.h:
#define __NR_finit_module 350

syscalls_32.h:
__SYSCALL_I386(350, sys_finit_module, sys_finit_module)

Comment: Ok so the names are essentially the user-land function names that map to the system calls. So I could write a c file and use *name*(*needed arguments*) where name is a particular syscall name instead of the entry point name... correct?
Comment: No, you dont' have to. Those names are the strings used in the #define labels. You can name your user-space function whatever you like - inside that function you'll use the #define label from that header file, and nowhere else.
Answer: you also can use the complete list of system calls with their relative system call number in strace source code. e.g for i386 system here is the link:
syscallent.h (i386) in strace sourceforge


Proving an Equation by Induction

Question: I'm trying to prove the following equation by mathematical induction but I'm stuck on the last part. How do I get (k+1)^2 (k+2)^2?
Comment: Shouldn't it be $(k+1)^3$ on second line left hand (i.e. second summand) from word "Assume" ?
Answer: $$\frac{k^2(k+1)^2}{4}+(k+1)^3=(k+1)^2\left[ \frac{k^2}{4}+k+1\right]=\\
=\frac{(k+1)^2(k+2)^2 }{4}$$
Answer: Posting this because you are apparently studying a Math analysis written by someone who is in the wrong line of work. I regard the whole analysis as poorly written.  This is how I would express it.
You are trying to prove by induction that for all $n \in \Bbb{Z^+}$, that
$$\sum_{i=1}^n i^3 = \frac{n^2(n+1)^2}{4}. \tag1 $$
(1) above is true for $n=1$.
Assume that (1) above is true for $n=N$, and then prove that (1) above is also true for $n=(N+1)$.
You have that
$$\sum_{i=1}^{N+1} i^3 = \left[\sum_{i=1}^N i^3\right] + (N+1)^3. \tag2 $$
By inductive assumption the first term (i.e. the summation) on the RHS equals
$$\frac{N^2(N+1)^2}{4}. \tag3 $$
The 2nd RHS term equals
$$(N+1)^2 \times (N+1) = \frac{4(N+1)^2(N+1)}{4}. \tag4 $$
Examining (3) and (4) you notice that they each have the common factor of $\displaystyle ~\frac{(N+1)^2}{4}.$
Therefore, when you combine the expressions in (3) and (4) above, you have:
$$\frac{(N+1)^2}{4} \times \left[N^2 + 4N + 4\right]. \tag5 $$
(5) above may be re-expressed as
$$\frac{(N+1)^2(N+2)^2}{4}. \tag6 $$
Putting (6) and (2) together, you have that
$$\sum_{i=1}^{N+1} i^3 = \frac{(N+1)^2(N+2)^2}{4}. \tag7 $$
Setting $K = N+1$, (7) above may be re-expressed as
$$\sum_{i=1}^K i^3 = \frac{K^2(K+1)^2}{4}.$$
This is consistent with the original assertion that was expressed in (1) above.  Therefore, if the assertion is true for $n=N$, then the assertion is true for $n=(N+1).$

Proving an Equation by Induction


Highest test innings one batsman scoring most of the runs

Question: I haven't been able to find this record by searching. Obviously England's first innings in the current Ashes test is unusual, with Cook scoring 244, and the other 10 Englishmen scoring only 235 (12 extras prevent Cook from getting most of the runs in the innings). But what is the highest test innings in which one batsman has scored more than all the others combined?
Answer: For the sake of this answer I'm going to assume that "Highest test innings" is referring to the highest team score in which one batsman scored the majority of the runs. As it turns out, it doesn't change the answer much - pretty much the only thing that changes is the year!
If you don't care about all eleven batsmen getting out on the ground at some point, there's a pleasingly elegant answer: It's Brian Lara's 400* against England in 2004, part of a West Indies innings that declared at 5/751. Jayawardene came close to beating that record in 2006 when he top scored with 374 runs in an innings of 5/756, but he scored one boundary too few for his knock to comprise 50% of the innings.
For a completed innings, the record holder is the same as the record holder for every other batting-related record: Sir Don Bradman, who was responsible for 304 of Australia's first innings total of 584 in the 4th Test of the 1934 Ashes. Remarkably, four years earlier in Bradman's inning of 334 against England, he scored 59% of a total team score of 566 (including 14 extras), which is the highest score by an individual that comprised more than 50% of a completed innings total.
Comment: For declared innings, in [Brian Lara's inning of 375 against England Apr 1994](http://www.espncricinfo.com/series/16362/scorecard/63641/west-indies-vs-england-5th-test-england-tour-of-west-indies-1993-94/), he scored 63% of team total score of 593/5 (26 extras).


Merge entries in CakePHP

Question: Let's say I have a Model, for example User, and I want to merge two instances of this Model, say merge User2 into User1. Explicitly this is what I mean:

If a field is already filled in User1, it should remain the same
If a field is missing in User1 but is present in User2, it should be copied
If SomeModel BelongsTo User, every instance of SomeModel pointing to User2 should be modified to point to User1
Same if SomeModel HasAndBelongsToMany User
If SomeModel HasMany User, and SomeModel1 Has User2 but no other instance Has User1, it should be modified so that SomeModel1 has User1 instead
If SomeModel HasMany User, SomeModel1 Has User1 and SomeModel2 Has User2... well, I'm not sure here, I guess the only solution is to discard SomeModel2, since User1 can BelongTo only one SomeModel.

Finally User2 should be removed.
Is there a way to automate this? Maybe a Behaviour? If not, I may consider creating it, since I will need it a lot.
Comment: You have a pretty well defined set of requirements, so your best bet may be to create the behavior yourself. I'm not aware of any native function/method/mechanism for merging two _objects_.
Comment: Indeed this is what I will do if no answer comes out. My list should not be seen as requirements, rather as a description of what I guess it would mean to merge. More like a spec.
Answer: We made a Merge behaviour exactly for this purpose back in 2008.
It may require some tweaking to work correctly with the latest CakePHP stable release but you can find it here
Comment: Thank you very much. I never found the time to write one myself, but I'll be happy to adjust and use yours. :-)
Comment: I had to use it again yesterday and found that it still worked except for HABTM on the same model with a different alias. Which is probably a case we never thought of when we made it.

Merge entries in CakePHP


Envio de formulário usando firebase

Question: Como consigo enviar os dados do formulário junto com imagem para o firebase utilizando flutter?
Comment: Por favor, edite a pergunta para limitá-la a um problema específico com detalhes suficientes para identificar uma resposta adequada.
Answer: Para enviar os dados do formulário junto com imagem para o Firebase utilizando Flutter, você pode seguir os seguintes passos:

Importe as bibliotecas necessárias:

import 'package:firebase_storage/firebase_storage.dart';
import 'package:firebase_auth/firebase_auth.dart';

Crie uma referência ao bucket do Firebase Storage:

final storageRef = FirebaseStorage.instance.ref();

Obtenha o arquivo da imagem do formulário:

final imageFile = await _imagePicker.pickImage(source: ImageSource.gallery);

Crie uma referência ao arquivo no Firebase Storage:

final imageRef = storageRef.child('images/' + imageFile.name);

Faça o upload da imagem para o Firebase Storage:

await imageRef.putFile(imageFile);

Obtenha o URL da imagem no Firebase Storage:

final imageUrl = await imageRef.getDownloadURL();

Envie os dados do formulário para o Firebase:

final user = FirebaseAuth.instance.currentUser;
final data = {
  'nome': _nomeController.text,
  'email': _emailController.text,
  'imagem': imageUrl,
};

FirebaseFirestore.instance.collection('users').doc(user.uid).set(data);

Aqui está um exemplo de código completo que mostra como fazer isso:
import 'package:firebase_storage/firebase_storage.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';

class FormPage extends StatefulWidget {
  @override
  _FormPageState createState() => _FormPageState();
}

class _FormPageState extends State<FormPage> {
  final _nomeController = TextEditingController();
  final _emailController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Enviar formulário'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            TextField(
              controller: _nomeController,
              decoration: InputDecoration(labelText: 'Nome'),
            ),
            TextField(
              controller: _emailController,
              decoration: InputDecoration(labelText: 'E-mail'),
            ),
            Row(
              children: [
                Expanded(
                  child: RaisedButton(
                    child: Text('Enviar'),
                    onPressed: () async {
                      final imageFile = await _imagePicker.pickImage(source: ImageSource.gallery);
                      final imageRef = FirebaseStorage.instance.ref().child('images/' + imageFile.name);
                      await imageRef.putFile(imageFile);
                      final imageUrl = await imageRef.getDownloadURL();

                      final user = FirebaseAuth.instance.currentUser;
                      final data = {
                        'nome': _nomeController.text,
                        'email': _emailController.text,
                        'imagem': imageUrl,
                      };

                      FirebaseFirestore.instance.collection('users').doc(user.uid).set(data);

                      Navigator.pop(context);
                    },
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

Este código primeiro obtém o arquivo da imagem do formulário usando o plugin image_picker. Em seguida, cria uma referência ao arquivo no Firebase Storage e faz o upload da imagem. Por fim, obtém o URL da imagem no Firebase Storage e envia os dados do formulário para o Firebase.
Você pode personalizar este código conforme necessário para atender às suas necessidades específicas. Por exemplo, você pode adicionar mais campos ao formulário ou usar uma estrutura de dados diferente para armazenar os dados no Firebase.
Fontes
github.com/90lucasgabriel/flutter-07-chat
github.com/AbirAhsan/BloodHero
github.com/JaimeBaldin/App_IMC
github.com/2018Patty/flutter_codes
github.com/Eder-Hayduki/bytebank-ultimate
github.com/chiucchi/Agenda

Envio de formulário usando firebase


Retrieve reference to content type in preprocess

Question: I have a content type (let's name it Wheel for an example) that have a field referencing an other content type (which could be Car, Motorbike, Bicycle ...).
So a node named WheelMotorbikeBrand whould reference the content type Motorbike.
I would like to retrieve the value of this field in a preprocess with something like $node->get('field_wheel-type') but I'm not able to obtain a value.
How can I retrieve the value of my field ?
Answer: You get a field value:
$value = $node->field_text->value;

If the field has a property value like fields for texts, numbers or booleans usually have.
A reference field has no value property, but one for target_id. So you get the id of the referenced entity with:
$target_id = $node->field_reference->target_id;

Or the referenced entity already loaded:
$referenced_node = $node->field_reference->entity;

Which you then can use to obtain a field value from the referenced node:
$value = $referenced_node->field_text->value;

The method ->getValue():
$values = $node->field_text->getValue();

gets an array of all properties and field items and so works also if you don't know the properties of a field or how many items it has.
Caveat: You don't find the property entity from the example above in this array, because it is computed and not stored in the database.
Answer: try :
$value = $node->get('field_wheel-type')->getValue();

Comment: It's working indeed. What is the difference between ->getValue() and ->value ? I thought it was the same.
Thanks for the answer.
Comment: ->value is a protected attribute.
->getValue() is a public method to get that protected attribute.


Strict inequality logical implication in optimization problems

Question: I have $ x \in \{0,1\}$ and $y \geq 0$ and I want to model that $x=1$ iff $y>0$, is this possible while keeping the constraint linear? Thanks.
One part of the implication is easy $ y \leq Mx$. The other part I can approximate as $ \epsilon x \leq y $. Where $\epsilon$ is small and $M$ is big. But this doesn't work if $y$ is very small.
Comment: Your constraint handles $y>0\implies x=1$. To handle the reverse case, you want $x=1$ to be less optimal than $x=0$ when $y=0$. You can handle this by adjusting the objective function by $-Mx$ (in the case of maximisation), as it will force $x=0$ unless it is required to be positive at the optimal solution.
Comment: thanks, there's no other way?
Comment: As you've observed, trying to put an upper bound on $x$ changes the range of values available for $y$. I don't have all of my literature available to check at the moment, but the method I described is my usual approach when the remainder of the problem is linear.
Answer: In practice, if $y$ is computed (as opposed to a parameter that is read in and never changed), the chances are high that you will get a nonzero value (possibly even negative) when it should be zero, due to rounding error. Constraints aside, you probably should set a tolerance value $\epsilon > 0$, small but not too small, and round $y$ to $0$ any time $|y|<\epsilon$. That will let you proceed as you proposed in your question.
Answer:
Your constraint handles y>0⟹x=1. To handle the reverse case, you want
  x=1 to be less optimal than x=0 when y=0. You can handle this by
  adjusting the objective function by −Mx (in the case of maximisation),
  as it will force x=0 unless it is required to be positive at the
  optimal solution. – Daryl


why is the capacity of the slice changing? shouldn't it be the same?

Question: I am fairly new to go and this example has had me baffled:
import "fmt"

func main() {
    s := []int{2, 3, 5, 7, 11, 13}
    printSlice(s)

    // Slice the slice to give it zero length.
    s = s[:0]
    printSlice(s)

    // Extend its length.
    s = s[:4]
    printSlice(s)

    // Drop its first two values.
    s = s[2:]
    printSlice(s)
}

func printSlice(s []int) {
    fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
}

output:
len=6 cap=6 [2 3 5 7 11 13]
len=0 cap=6 []
len=4 cap=6 [2 3 5 7]
len=2 cap=4 [5 7]

why does the capacity change to 4 in the last one? capacity by definition is the length of the underlying array.
Answer: Slice is built on arrays, it consists of a pointer to the array, the length of the segment, and its capacity (the maximum length of the segment).
The key point is segment, not the array.
    s = s[2:]

when you drop the first two values, s became a slice pointed to the other half segment of the array, starting from the third element, so that it's cap is 4.
just like you can not do an s[-1] to point to the previous part of the array, that part can not be count into the cap.
ref: https://blog.golang.org/slices-intro
Comment: Got it makes sense now. I'll look at Slices as a reference to segment of an array rather than the whole array.
Answer: The capacity of a slice is the number of elements in the underlying array, counting from the first element in the slice.
In your example, in the last case starting element of the slice is 5 and in the underlying arrray({2, 3, 5, 7, 11, 13}) poistion of 5 is 2. To count the capacity you should start counting from index 2. If you count from that position you will get the correct capacity 4


Modify readonly fields in CECIL

Question: I have the below field declaration in one of my classes
private readonly string name = "some name";

How can I remove the 'readonly' in the assembly at run time using FieldDefinition or some other way?
Answer: I was in hurry to get this answer and tried myself later. So found that below property will do it
IsInitOnly

Modify readonly fields in CECIL


MVC: Model View Controller -- does the View call the Model?

Question: I've been reading about MVC design for a while now and it seems officially the View calls objects and methods in the Model, builds and outputs a view.
I think this is mainly wrong.
The Controller should act and retrieve/update objects inside the Model, select an appropriate View and pass the information to it so it may display. Only crude and rudiementary PHP variables/simple if statements should appear inside the View.
If the View gets the information it needs to display from the Model, surely there will be a lot of PHP inside the View -- completely violating the point of seperating presentation logic.
Answer: As with all things programming we need to be pragmatic. A view should only contain presentation logic. That logic can be very simple or can be quite complex. As long as that logic only handles what is displayed on the screen, printed on the report, etc.

The Controller should act and retrieve/update objects inside the Model, select an appropriate View and pass the information to it so it may display.

What is this information you are passing? Possibly a subset of a model. You could create a new class containing only the information the view should know about or just pass along the model and make sure you only access appropriate data. Anyway, the view should be free to query this passed in model to be able to display a view.
The point of controversy is if you from the view should be able to update the model directly, bypassing the controller. This is where the pragmatic side comes in. I think there are cases that can warrant updating the model directly. Especially if you can use data bindings. The you can assign a text box to a property of the model and let the update automagically happen. If there are a lot of simple property setting this approach can save a bunch of code in the controller. MVC is not a set of rules set in stone. It's guidelines that when used correctly can produce better code but if used too rigorously can lead to pain and suffering.
Be pragmatic!
Answer: There isn't one absolute and correct way to do MVC. Variations are possible.
For example, instead of having the View actively querying the Model, the Controller can notify the view of any changes in the Model, using some sort of notification mechanism. In that case, the View is just listening for updates, which are then being presented.
Answer: It's probably not what one would call "pure" MVC, but IMHO it's not a huge deal as long as the view PHP code doesn't mutate the model. The most important rule of MVC is that the model doesn't know about the view. Having the view not know about the model is less important.
The main downside to using the model directly is that the view can't be reused with a different model. This is rarely a problem, because the view is almost always specific to one particular type of model object (or a list thereof).
Answer: Would the following modifications to DisgruntledGoat's code snippet be considered too "complex"? Should objects be passed to the view?

<?=$item->description?>

Or maybe?

<?=$item->getDescription()?>

I've seen several examples where only arrays are used:-

<?=$item['description']?>

Comment: Passing an object or variable is a just design preference, though I would swing towards an array because not all of my data passed to the view will be already in an object form. I like to keep things consistent across my views, choose to either always pass by objects or arrays. For `getDescription()` I'd say it depends on what getDescription is actually doing. If it's using a helper function to just *format* code in a complex manner then that's fine. Though if it's causing a SQL query to be made, that's not a good idea; that's the job of the controller to get the data from the models.
Comment: Thanks for reply. Was thinking of controller passing data to view as objects rather than arrays, and then the resultant "creeping" complexity (public attribute access replaced by methods) of the php, when advice seems to be keep the PHP simple.
Answer: MVC is not a law set in stone. Depending on where you read about it it can differ. Personally I don't allow the View to read directly from the Model.
Update
This post has some good examples as well. The model is the engine of the car with start() like methods, the view is the color of the car with paint() or change() methods and the controller is the driver. I prefer to let the controller drive() the car and start() the engine instead of letting the wheels or the paint doing it.
:)
Comment: "Personally I don't allow the View to read directly from the Model." - Also when using AJAX?
Comment: @Mr.Pallazzo as well. Ajax requests are still processed by the controller, not directly by the model. There is no difference conceptually from the server point of view between a normal request and an Ajax one. The difference is in the output and in the client.
Comment: I think its better to see the View as more of a template. MVT as I like to see it. The only downside to having the information retrieved from the controller and passed to the View is that the View now depends on the controller. The View cannot be called directly to display a page, it has to go through the Controller -- but then again, this is the whole *purpose* of a controller -- to route HTTP GET/POST requests.
Answer: MVC refers to layers, not components. So they are more abstract concepts, than a blueprints. Since it's not really possible to separate the layers entirely (Information has to flow between them), it's really a continuum where you have spaghetti on one extreme and bureaucratic type systems on the other. You probably want to find somewhere in between those two.
I generally don't spend too much effort on the controller-view separation. The separation between model and (controller-view) is much more important.
Comment: It's very important to seperate the model functions from controller and views, but then I think its relatively straight forward knowing what belongs in the model; all things to do with the data, buisness logic, validation, etc. Now the line between the view and controller, you could easily end up with spagehetti code.
Answer: I think you are absolutely correct - Views shouldn't call methods from the Models. Like others said, there are variations on MVC but the point it to separate logic from data from output.
So generally, you have a controller which is the start point for the application. In PHP, this would be your index.php file. At a minimum this file would process the input data (i.e. the query string or URL parameters). It's usually a good idea to add separate controllers for separate parts of the app.
Each controller then simply decides what data needs to be displayed, gets it from the model, and passes it to the view. In PHP, you would call various classes/methods that fetch data from the database, storing it in variables.
Then you simply include another PHP file containing mostly HTML, but with some PHP echoing variables. Loops are fine, too. If you have a list of things, you may want to do something like this:

<?php foreach ($items as $item) : ?>

<?=$item?>

<?php endforeach; ?>


Intermittent slow response & timeouts - Apache + mod_wsgi + Web2py

Question: I've Ubuntu 14.04.5 LTS (i686) on a Digital Ocean droplet with 2x2.4GHzCPU & 4gb physical memory. I am running a web2py application on it with Apache and mod_wsgi. There are a few additional python modules installed on the box, like numpy and opencv2. The database is MySQL 5.5.
A Wordpress website on another server calls this web2py application using php-curl. Usually the response time is 2-5 seconds. But occasionally it timeouts (response time goes to >1000 seconds). I've added logging points in the Web2py application and they tell that after reaching the application, everything completes in 2-3 seconds. But in Apache2 access log, response time logged as a number higher than 1000 seconds. In the access log, the request time is approximately the same when request is initiated from the Wordpress website.
Can anyone point out how to find-out the reason of this intermittent slow response?
Thanks
Comment: Have you added logging of timestamp right into the beginning and end of your web2py application?
Comment: Yes, I did it initially in the controller, the controller function and the main model file but it didn't help revealing the root cause.
But finally I found that the developer left a db connection statement in the default model file. This was for a remote database, was not being used in the application and causing the slow response.
Answer: In order to discover the root cause of the timeout, you could use php slowlog, which will explain which function is responsible.
You have to modify your www.conf and change the 0 default value of the option request_slowlog_timeout.
For example :
request_slowlog_timeout = 10s

You can read a little more about activating slowlog here, and take a look on some common sources of slowness here.
Comment: The slow response is from **apache+mod_wsgi** which is serving a python based application and has nothing to do with **php**. php-curl is being used here on client-side.
Are you suggesting to do this modification on the server running wordpress website and acting as a client for the python-application?
Thanks
Answer: Finally I've been able to find out the cause of the problem. It was a  connection statement to a remote database in the default model file of the web2py application. This database connection was not being used in the application anywhere. But since it was in a model file, whenever a controller function is called the application tries to unnecessarily connect to that remote database.
Initially I added logging points everywhere in the application but didn't add in the default model file of the application; Therefore logs were silent about the root cause. Then I tested the application by just replacing the application folder contents one by one with the files of a demo application (which comes with web2py) and helped revealing the root cause of the problem. The root cause was then verified by adding the logging at the start and end of the default model files of the application.


Is it true that $\sigma(X_1,X_1+X_2)=\sigma(X_1,X_2)$?

Question: Given a sequence $(X_k)_{k\in\mathbb{N}}$ of real centered r.v.'s, and a sequence $(Y_n)_{n\in\mathbb{N}}$ defined by
$$Y_n = X_1 + ..+X_n$$
it is stated, in a chapter on martingales of the book I'm studying, that
$$\sigma(Y_1,..,Y_m)=\sigma(X_1,...X_m)$$
without any hint for a proof, as if it were trivial.
All I know, in general, is that $\sigma(X_n+X_m)\subseteq\sigma(X_n,X_m)$, which should imply that  $\sigma(X_n,X_n+X_m)\subseteq\sigma(X_n,X_m)$. But how to go from here?
The source is: P. Baldi, Stochastic Calculus - An Introduction Through Theory and Exercises, Springer, Section 5.1, page 109.
Comment: In a nutshell, the reason is that each $Y_i$ can be written as a function of $X_1, \ldots,X_m$, and each $X_i$ can be written as a function of $Y_1, \ldots, Y_m$.
Comment: Definitely $\subseteq$ but not sure about $\supseteq$. Less sure about $\supseteq$ if + were replaced with say x. But if just +...then maybe? I have a feeling there's already a question about this asked like about how sigma algebras of sums / products of random variables relate to so and so
Comment: That is a great book btw :)
Answer: Elaborating on my comment:
For a measurable function $f$,
$$\sigma(f(X)) \subseteq \sigma(X),$$
since a set $\{\omega : f(X(\omega)) \in B\}$ can be expressed as $\{\omega : X(\omega) \in f^{-1}(B)\}$. This also holds if $X$ is a random vector $X=(X_1, \ldots, X_m)$.

Since $Y_i = X_1 + \cdots + X_i$, we therefore have $\sigma(Y_i) \subseteq \sigma(X_1, \ldots, X_m)$ for $i \le m$. Consequently, $\sigma(Y_1, \ldots, Y_m) \subseteq \sigma(X_1, \ldots, X_m)$.
Conversely, since $X_1 = Y_1$ and $X_i = Y_i - Y_{i-1}$ for $i \ge 2$, we have $\sigma(X_i) \subseteq \sigma(Y_1, \ldots, Y_m)$ for $i \le m$, and thus $\sigma(X_1, \ldots, X_m) \subseteq \sigma(Y_1, \ldots, Y_m)$.


About sat4j, how to use sat4j to solve pseudo boolean problems?

Question: I have pseudo boolean problems and I need to solve it with sat4j.
Can someone help me?
Here's my problem:

I have a list of variables named: a,b,c,d,e,f
And I have a list of values represented by: #1, #2, #3.....
h(a,#1) means assign #1 to a

I have some example constraints:
h(a,#1)=1
h(a,#1)+h(b,#1)+h(c,#1)=1
h(a,#1)+h(a,#5)>=1
h(b,#2)+h(b,#3)+h(b,#4)>=1

So many constraints like examples above.
Finally, I want a result of assign which values to which value.
How can I solve it with sat4J? How should I represent the constraints?
Comment: I wouldn't use a CNF solver on this.  SMT is a much better fit.
Comment: what kind of SMT solver? can you recommend one to me? i need to integrate the code with my java project, so i want a tool that both solve pesudo boolean problem and offers java API.
Comment: Z3 is a popular SMT solver that I've used recreationally.  I haven't tried to use Java to talk to it, but others have, at least according to Google.  Z3's simple LISPy I/O syntax won't be hard to parse in any event.
Comment: yeah, i know the tool z3, but it doesn't offer java api.
Comment: Looks like other people have already done the API work.  I suspect it will be easier to use Z3 than coding adders and comparison circuits, which is what you'll need to do to use a CNF-based solver.
Comment: @KyleJones A pseudo-boolean solver like `org.sat4j.pb` doesn't require manually built adders and comparators to express these constraints.
Answer: If I understand your problem correctly as a pseudo-boolean satisfaction problem, you can directly encode it as an OPB file:
* #variable= 7 #constraint= 4
1 x1 = 1;
1 x1 1 x2 1 x3 = 1;
1 x1 1 x4 >= 1;
1 x5 1 x6 1 x7 >= 1;

where I have arbitrarily encoded h(a,#1) as x1, h(b,#1) as x2, h(c,#1) as x3, h(a,#5) as x4, h(b,#2) as x5, h(b,#3) as x6, and h(b,#4) as x7.  (You may wish to add constraints like
-1 x1 -1 x4 >= -1;
-1 x2 -1 x5 -1 x6 -1 x7 >= -1;

stating that each variable has at most one value, or = for exactly one value.)
Then run
java -jar org.sat4j.pb.jar yourfile.opb

which outputs (ignoring many comment lines beginning with c):
s SATISFIA@KyleJones You don't need to manually build adders and comparators to use a pseudo-boolean solver like `org.sat4j.pb`.BLE
v x1 -x2 -x3 -x4 x5 -x6 -x7

meaning x1 and x5 are true while x2, x3, x4, x6, and x7 are false.
(I'm sure there's a way to do the same thing using the org.sat4j.pb Java API, but perhaps this command-line recipe gives you a starting point to help you figure that out.)