How to resolve typescript Redux connect error ActionCreatorsMapObject

Question: Have error with typescript
ERROR in [at-loader] ./src/app/components/profile/userProfile/_userMain.tsx:130:37
    TS2345: Argument of type 'typeof "/usr/src/app/src/js/src/app/redux/actions/sessionActions"' is not assignable to parameter of type 'ActionCreatorsMapObject'.

ERROR in [at-loader] ./src/app/components/profile/userProfile/_userMain.tsx:133:124
    TS2345: Argument of type 'typeof UserProfileMain' is not assignable to parameter of type 'ComponentClass<(state: any) => any> | StatelessComponent<(state: any) => any>'.
  Type 'typeof UserProfileMain' is not assignable to type 'StatelessComponent<(state: any) => any>'.
    Type 'typeof UserProfileMain' provides no match for the signature '(props: ((state: any) => any) & { children?: ReactNode; }, context?: any): ReactElement<any>'

Is it possible to fix this without decorators? ( @connect )
interface IActions {
    avatarUpload: (file:any) => void;
}

export interface IMainProps {
    auth: number,
    actions: IActions
}

class UserProfileMain extends React.Component<IMainProps, any> {
    constructor(props:any){
        super(props);
        this.state ={
            files: [],
        }
    }

    render(){
        return(
)
    }
}

const mapStateToProps = (state:any):any => {
    return {
        auth: state.authStatus.data.user.id,
    };
};

const mapDispatchToProps = (dispatch:any):any => {
    return {
        actions: bindActionCreators(sessionActions, dispatch) //First error (130:37)
    };
}
export default connect<typeof mapStateToProps, typeof mapDispatchToProps, IMainProps>(mapStateToProps, mapDispatchToProps)(UserProfileMain); //second error (133:124)

Already tried with UserProfileMain as any but got other bunch of errors
Maybe you know some best practice for that
Hope your support
Comment: Where is sessionActions defined? Can you please show this? It's difficult to be sure of what exactly is wrong without seeing all of the code.
Answer: You need to change your
actions: bindActionCreators(sessionActions, dispatch)

line to
actions: bindActionCreators<any>(sessionActions, dispatch)

or something more specific because the redux typescript definitions are using generics.
See the redux typescript definitions here.
The generic type in the <> should be the same type of sessionActions, which is also the return value of the bindActionCreators() function call.
Answer: You might need
bindActionCreators<any, any>


Tournament of Towns Geometry Problem, Proof by Construction?

Question: I was to prove the following proposition from an old Tournament of Towns problems archive:
Problem. A circle $\omega_{1}$ with center $O_{1}$ passes through the center $O_{2}$ of another circle $\omega_{2}$. The tangent lines to $\omega_{2}$ from a point $C$ on $\omega_{1}$ intersect $\omega_{1}$ again at points $A$ and $B$. Prove that $AB$ is perpendicular to $O_{1}O_{2}$.
The proof I have come up with (below) seems slightly weird to me, in that I construct the second circle $\omega_{2}$ from an arbitrary inscribed triangle $ABC$ in the first circle $\omega_{2}$ with perpendicular $O_{1}O_{2}$ to $AB$, instead of directly proving that $AB$ is perpendicular to $O_{1}O_{2}$. I think this is right since everything I started with is arbitrary, but it still seems like I may be missing something. I wanted to know if there are any holes to my logic (or non-logic).
Proof. Let $ABC$ be an inscribed triangle of $\omega_{1}$, and let $O_{1}O_{2}$ be the radius of $\omega_{1}$ that is a perpendicular bisector of $AB$. Then arcs $AO_{2}$ and $BO_{2}$ are equivalent in measure, whence $\angle ACO_{2}$ and $\angle BCO_{2}$ are of the same degree measure. Let $O_{2}P$ and $O_{2}Q$ be perpendiculars to the extended lines $CA$ and $CB$, respectively. Then it is now immediate that triangles $PCO_{2}$ and $QCO_{2}$ are similar by their angles. In fact, they are congruent since they share side $CO_{2}$. Thus, $|AO_{2}| = |BO_{2}|$, and these are radii of a circle $\omega_{2}$ with center $O_{2}$ that has the extended lines $CA$ and $CB$ as tangents.
Since there is a unique circle $\omega_{2}$ with center $O_{2}$ as described above, I think the logic in the proof works.
Comment: Sorry that was a typo. Meant $PCO_{2}$ and $QCO_{2}$. Thanks.
Answer: Your "reverse" reasoning looks correct, but I think a more direct approach would be easier. As $CA$ and $CB$ are tangent to $\omega_2$ then $CO_2$ is the bisector of $\angle ACB$. It follows that arcs $AO_2$ and $BO_2$ are congruent and so are their chords: $AO_2\cong BO_2$. But then triangles $AO_1O_2$ and $BO_1O_2$ are congruent and it follows immediately that $AB\perp O_1O_2$.
Comment: You are correct, this is much easier. I'm still wondering though if the logic I followed in my proof is a correct way, in general, to go about such a geometry problem. Thanks.


Can't resolve all parameters' JwtInterceptor

Question: When i start building my application which the main purpose was to implement login service, whenever, when it starts, it shows blank page and i get this error from console which is:
compiler.js:2193 Uncaught Error: Can't resolve all parameters for JwtInterceptor: (?).
    at syntaxError (compiler.js:2193)
    at CompileMetadataResolver._getDependenciesMetadata (compiler.js:17643)
    at CompileMetadataResolver._getTypeMetadata (compiler.js:17539)

Spent much time on googling, don't have an idea what to do…
Here is how I provide the Interceptor in AppModule:
 providers: [CookieService,
    {provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true},
    {provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true}],
  bootstrap: [AppComponent]
})

Here is the Interceptor itself:
@Injectable({
    providedIn: 'root'
})
export class JwtInterceptor implements HttpInterceptor {

    constructor(private userService: UserService,
    ) {

    }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        // add authorization header with jwt token if available
        const currentUser = this.userService.currentUserValue;
        if (currentUser && currentUser.token) {
            request = request.clone({
                setHeaders: {
                    Authorization: `${currentUser.type} ${currentUser.token}`,
                    'Content-Type': 'application/json'
                }
            });
        }
        return next.handle(request);
    }
}

Here is th UserService :
Injectable({
    providedIn: 'root'
})
export class UserService {

    private currentUserSubject: BehaviorSubject<JwtResponse>;
    public currentUser: Observable<JwtResponse>;
    public nameTerms = new Subject<string>();
    public name$ = this.nameTerms.asObservable();
    constructor(private http: HttpClient,
                private cookieService: CookieService) {
        const memo = localStorage.getItem('currentUser');
        this.currentUserSubject = new BehaviorSubject<JwtResponse>(JSON.parse(memo));
        this.currentUser = this.currentUserSubject.asObservable();
        cookieService.set('currentUser', memo);
    }

    get currentUserValue() {
        return this.currentUserSubject.value;
    }

    login(loginForm): Observable<JwtResponse> {
        const url = `${apiUrl}/login`;
        return this.http.post<JwtResponse>(url, loginForm).pipe(
            tap(user => {
                if (user && user.token) {
                    this.cookieService.set('currentUser', JSON.stringify(user));
                    if (loginForm.remembered) {
                        localStorage.setItem('currentUser', JSON.stringify(user));
                    }
                    console.log((user.name));
                    this.nameTerms.next(user.name);
                    this.currentUserSubject.next(user);
                    return user;
                }
            }),
            catchError(this.handleError('Login Failed', null))
        );
    }

    logout() {
        this.currentUserSubject.next(null);
        localStorage.removeItem('currentUser');
        this.cookieService.delete('currentUser');
    }

    private handleError<T>(operation = 'operation', result?: T) {
        return (error: any): Observable<T> => {

            console.log(error); // log to console instead

            // Let the app keep running by returning an empty result.
            return of(result as T);
        };
    }
}

Answer: Angular services are also providers and subjected to be declared as that.
That's why when Angular injection tries to inject JwtInterceptor with UserService it can not do it because it doesn't identify it.
Please add UserService after CookieService as well.
Comment: That's probably an issue that your UserService is not injectable, usually meaning you passed to it parameters that are not marked as injectable. Try editing your question and add to the bottom of the post the userservice constructors.
Comment: I chage it like this  providers: [CookieService,UserService, ..,..]¨and i get another one Uncaught Error: Can't resolve all parameters for UserService: (?, ?).
Comment: I edit it, u can check, the injectable is present there.
Comment: Have you added the following `import { HttpClientModule } from '@angular/common/http';` to app module file, and also added `HttpClientModule` into `imports` at app module ?
Comment: @HamzaKhadhri, Also `Injectable` should be `@Injectable`


Shortest path from $s$ to $t$ in a graph with $5$ negative edges and no negative cycles?

Question:
Let $G=(V,E)$ a directed and weighted ($w:E\to\mathbb{R}$) and let $s,t\in V$. It is given that there are exactly $5$ negative edges and no negative cycles. Find the shortest path from $s$ to $t$.

It seems to me we can still use Dijkstra's algorithm with some modifications. I think this is the intention of this exercise.
It is clear that even without negative cycles, Dijkstra's original algorithm will fail. On the other hand, we have only constant number of negative edges.
I thought about removing those edges or setting their weights to zero, but couldn't think of a proper method to utilize this.
What's the catch?
EDIT
How about running Dijkstra's algorithm on the graph $G$ without any modifications? Then, we look at the "shortest path" from $s$ to $t$ and try to fix it?
Comment: Obviously I could use Bellman-Ford algorithm, but the solution should be as efficient as possible
Comment: @Jared: I think your approach is incorrect. Consider the graph with two paths from the source $s$ to the sink $t$: the first is a unique edge $s-t$ with cost $1$, the second is the chain $s-v-t$, with costs $c_{sv}=-2$ and $c_{vt}=2$ (i.e., total cost $0$). With your approach the modified graph would give the first path cost $1+2=3$, and the second path cost $(-2+2)+(2+2)=4$. This is obviously incorrect, as the shortest path is $s-v-t$.
Comment: @Jared: [Johnson's algorithm](https://en.wikipedia.org/wiki/Johnson%27s_algorithm) provides such a re-weighting scheme, but it requires using Bellman Ford's algorithm to compute the new costs. There is probably a more efficient way than computing Bellman Ford, and then Dijkstra on the new graph, but the approach is still interesting.
Comment: I think Dijkstra's algorithm still works when the directed graph doesn't have negative cycles. If that is not the case, that is, there is at least one negative cycle, then Bellman-Ford algorithm might be what you're looking for. I don't know of any easier way, but I'm not expert, so take it with a grain of salt.
Comment: I'm almost certain that if no negative weight cycles exist (which Bellman-Ford would also fail at) there is a way to re-weight the edges so that all are positive.
Comment: My guess, and it's exactly that--a guess, is that you can simply add the most negative weight to each edge (e.g. if the most negative weight is $-5$ then you would add 5 to each edge) and then solve (in that way every edge will be $\geq 0$).  I'd have to think a lot harder than I am willing to right now to decide whether or not that is valid.
Comment: You might also try this question in the [cs stackexchange](http://cs.stackexchange.com/)
Comment: @Kuifje Yes, you are correct, so clearly a re-weighting scheme (which I'm still fairly certain is possible under the given situation) needs to be more thought out.
Answer: Dijkstra's Algorithm in its pure form does not work with negative edge weights. The reason is that it might fix the distance from $s$ to an intermediate node $v$ but finds a shorter path using a negative edge afterwards.
You might consider the following approach to fix this wrong fix:

First run Dijkstra's Algorithm in its pure form.
Check if the distance label of one of the nodes incident to the edges with negative weights is not yet minimal.
If no such node exists then you are done.
If there exists such a node $v$ for an edge $(u, v)$ with negative weight then run Dijkstra's Algorithm again with the following modifications:

Keep the precomputed distances, but mark all nodes as unvisited.
Mark $u$ as visited and start the algorithm at $u$.

Go to 2.

The running time of this approach depends on the order in which you consider the nodes whose distance is not yet minimal. If you manage to find the right order of these nodes then you simply run Dijkstra's Algorithm six times. However, if you choose a bad order then you will have to rerun it on the same node several times (up to 32 times if my calculations are correct).
I would try to rerun the algorithm on the node closest to $s$. I cannot give a proof that this is the best order, though. Furthermore, depending on the size of the graph, I would suggest using algorithm which are designed to deal with negative edge weights.


New to Python (and programming) can't see where I'm going wrong

Question: I'm learning a bit of Python in my spare time. Trying to make a phonebook, found one on this site; Python assignment for a phonebook. Have used that as a template but left out the print_menu function. That's the only difference that I can see but when I add a number it gets stuck in that part. Just asking to enter name and number, not escaping the if loop. If anyone can tell me why I get stuck like this I would appreciate it.
phoneBook = {}

def main():
    action = input("What would you like to do? \n 1. Add \n 2. Delete \n 3. Print \n 4. Quit \n")
    while action != 4:
        if action == '1':
            name = input("Enter name: ")
            num = input("Enter number: ")
            phoneBook[name] = num
        elif action == '2':
            name = input("Delete who?")
            if name in phoneBook:
                del phoneBook[name]
            else:
                print("Name not found")
        elif action == '3':
            print("Telephone numbers: ")
            for x in phoneBook.keys():
                print("Name: ", x, "\tNumber: ", phoneBook[x])
        elif action == '4':
            print("Application closed.")

main()

Comment: `while action != "4":`
Answer: input() returns a string, not an integer.
So
while action != 4:

should become:
while action != '4':

Comment: Yea just saw that, changed them all into integers instead. Just got it working before I saw the replies. Thanks!
Answer: You have two problems here. As Padraic and Leistungsabfall mention, input returns a string, but you also are only getting the input one time. If you want to continue getting input, you're going to need to put that inside your loop:
action = None
while action != '4':
    action = input('What action would you like? ')
    # the rest of your code here


Dimensão em diversos tamanhos de tela

Question: Estou criando um site no meu notebook, quando eu vou testar no meu computador que tem uma tela maior, o site fica todo bagunçado, como faço pra manter um padrão de dimensão para diversos tamanhos de tela?
Comment: Era isso mesmo que eu queria saber, só nunca vi esse nome! vlw, vou pesquisar sobre.
Comment: Sua pergunta é muito ampla, mas você pode usar _bootstrap_ pra isso. Da uma olhada no site http://getbootstrap.com/
Answer: Voce precisa usar porcentagens ao invés de pixels fixos quando vai desenvolver seu CSS.
Por exemplo, se voce usar width: 100%, voce vai pegar sempre 100% da largura da tela.
Veja esse exemplo que peguei do w3school:
<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1.0">

Chania

The Flight

The City

The Island

The Food

The City

Chania is the capital of the Chania region on the island of Crete. The city can be divided in two parts, the old town and the modern city.

What?

Chania is a city on the island of Crete.

Where?

Crete is a Greek island in the Mediterranean Sea.

How?

You can reach Chania airport from all over Europe.

Resize the browser window to see how the content respond to the resizing.

Veja como fica: https://www.w3schools.com/css/tryit.asp?filename=tryresponsive_breakpoints

Dimensão em diversos tamanhos de tela


Highcharts Areaspline - Highlight a column on hover effect

Question: Stuck with the problem of highlighting column of area spline. Didn't find any solutions via Chartjs, and Highcharts didn't help me either. I need to highlight x-axis column, but till the chart curve. In my code, I'm using Crosshair, but it's not exactly what I need.
xAxis: {
        allowDecimals:false,
        min: 1,
        max: 12,
        categories: ['', 'JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC', ''],
        labels: {
            y: -10,
            style: {
                color: '#66717c',
                fontSize: '13px'
            }
        },
        tickWidth: 0,
        lineColor: "#fff",
        crosshair: {
            width: 60,
            color: 'rgba(73,168,222,0.5)',
            zIndex: 5
        }
    },
    yAxis: {
        title: {
            text: ''
        },
        gridLineWidth: '0',
        visible: false
    }

My result:

And what I need:

Does anybody know how to achieve this?
Answer: If you will add another series that will be stacked on top of the real series with percent stacking, then you could use that area fill is partially transparent and place crosshair under series. Fake series should be used as something to cover part of the crosshair that you want to hide.
Example: http://jsfiddle.net/aft9esqr/


What is it called when 2/2 is imposed in 3/4?

Question: What is the name in music theory for when the feel of 2/2 is imposed in 3/4 time? For example in Waltz No. 2 by Shoshtakovich (i think its that one) there is a section about midway through where its 3/4, but the melody plays half notes for about 6 measures or so. Im not sure how exactly to explain it.
Comment: Other famous examples is Mozart's minuet in symphony 40, Bernstein's _America_ from _West Side Story_.
Comment: @MichaelCurtis I don't see it in the minuet of Mozart's Symphony 40. One notable extended hemiola is in the finale of Schumann's piano concerto.
Comment: @RosieF, https://en.wikipedia.org/wiki/Symphony_No._40_(Mozart) scroll down to the minuet description. After the anacrusis the first two bars use the hemiola.
Answer: I think you are asking about hemiola a combination of a 2 pattern and a 3 pattern.
https://en.wikipedia.org/wiki/Hemiola
Using accent marks <code>></code> in 3/4 it would be like...

      >   >     >      >   >      >
3/4 | / / / | / / /  | / / /  | / / / |

The hemiola effect can be realized in a score in a variety of ways:

accents like in my example above
the use of beaming in multiples of 2 against a meter of 3
simply changing chords on the pattern of 2 in a meter of 3 is enough to make hemiola felt

However the effect is created the meter of 3 needs to established as the base from which the pattern of 2 conflicts. For example, you would need to accent in 3's first to establish the 3/4 meter then shift temporarily to a pattern of accents in 2's. Or, you would need to simultaneously play accents in 2's and 3's. This pattern conflict is essential for hemiola. If the music doesn't have a proper hemiola treatment it could simply sound like a meter change.
Comment: @ToddWilcox - A hemiola is a specific type of syncopation. Syncopation can easily happen in 4/4 time, for instance, while hemiolas won't.
Comment: Is "syncopation" a synonym or is there a difference between them that I don't know?


How to create custom date display format in drupal 7?

Question: I have created content type for an events in which I mentioned multiple values for date field. I want to display date like Nov. 2, 6 & 8   or Nov. 2-5, 12 2014 & Jan 22 2015
After some research I am able to create a view of event date field like
Nov 23 2014, Nov 26 2014, Nov 30 2014, Jan 03 2015 to Jan 05 2015
But still not getting format I want like
Nov 23, 26, 30 2014 & Jan 03-05 2015
Comment: It's about to 4 days that I am working on it, still not get perfect guidence
Answer: If you are comfortable with coding then go for template file changes.
You have to do changes in node.tpl.php.
Else you can do also without coding refer https://stackoverflow.com/questions/8375674/how-can-a-custom-drupal-date-format-be-added
If you have created view for event display then it is easy to display date field as you want.
Go to date fields setting. There is a option for formatter. Like below screenshot. Here you can add custom date display format.

Comment: Ok let me know if you are getting any issue in this scenarios.
Comment: I don't think adding a custom dare format is going to help here, as there's conditional logic necessary to collate dates by arbitrary criteria. Given that your incidence and interval pattern  is variable, my suggestion would be to allow the user to input multiple date values and then loop through those via theme preprocessing functions or in a specific node--type or field-- template override rather than node.tpl.php. If you will be testing for date conflicts, that may further complicate solutions proposed here.
Comment: @murraybiscuit is there any tutorial that I can follow for this?
Comment: The solution gets pretty complicated depending on the parameters. Getting the fields out of the node and grouped into a multi-dimensional array is easy. Grouping the array by year and then by month gets more tricky. Then you sort the array. Then you loop through to combine it. What if a date falls across two months? What if it falls across two years? I'd say the Drupal parts of this are easy. The php stuff is where it's going to require some fiddly conditional logic & exceptions.
Comment: @murraybiscuit, Ok I will go through this, Big Thanks for your support :)
Comment: Cool. It's a fair bit of work. If you manage to make it work (elegantly), paste it back here as the answer. Even if it's just the php logic, someone else could use it for a display formatter module, or it could be a new feature for the Date contrib project. I could see a general use case for this code.


Using Difference in Difference (DiD) to measure the impact of austerity measures?

Question: I am trying to see if there is any causal relationship between the rise in vote share of France's leading extreme right-wing party Le Front National and the rate at which austerity measures took place after 2008.
Austerity measures started after 2008, therefore I have three 'waves' I could assess: the 2002, 2007, 2012 presidential elections. My logic is that I would be able to see if there was a significant increase in vote share for the National Front in the wake of impending austerity measures, as opposed to previous years during which public spending was untouched.
Of course there are control variables and etc, I am just wondering if my logic thus far is on the right track.
Answer: The diff-in-diff estimator is reliant on a control group to which the treatment group is being compared. You do not have such a control group.
What you might ask is rather: was there a structural break in the support for FN when austerity measures were implemented? Time-series on the support - for example, from public opinion polls - might give you an insight into this. Another might be the number of unique visitors on the FN webpage.


How could one tune the parameter alpha of the sparse group lasso method (SGL) based on cross-validation?

Question: The sparse-group lasso (SGL) method presented by Simon et al. as follow :
$\min _{\beta} \frac{1}{2 n}\left\|y-\sum_{l=1}^{m} X^{(l)} \beta^{(l)}\right\|_{2}^{2}+(1-\alpha) \lambda \sum_{l=1}^{m} \sqrt{p_{l}}\left\|\beta^{(l)}\right\|_{2}+\alpha \lambda\|\beta\|_{1}$
where $\alpha \in[0,1]-$ a convex combination of the lasso and group lasso penalties $(\alpha=0 \text { gives the group lasso fit, } \alpha=1$ gives the lasso fit).
The default value of $\alpha$ is 0.95.
It's possible to use the cross-validation to choose the optimal $\alpha$ and $\lambda$ parameters?
Question: How to choose the alpha parameter of SGL based on cross validation?
Thank you!
Comment: Why not? It seems reasonable to optimize the hyper-parameter there.
Comment: @Forgottenscience Please, could you describe to me, how to do it? How to use the cross-validation to choose alpha?
Comment: Did the answer from @Edgar answer your question? If so, you might consider accepting his answer. If not, you could add a comment clarifying what advice you are still hoping for.
Answer: I strongly recommend to use R and the package "SGL" to compute sparse-group lasso, which is maintained by the authors of the SGL paper themselves.
Within the package, you have the function "cvSGL", which does the cross-validation for you.
Be advised, the SGL-package is not optimized for speed and has different default parameters (number of iterations, minimum error for convergence) than the LASSO/Elastic-Net implementations within the "glmnet" package, so SGL-results are not directly comparable with LASSO results.


Tree comparison node by node

Question: We are looking for a build in java data structure (I am thinking some sort of tree)
that could do the following: Compare two different structures of the same type by Nodes.
So if I had Structure A with nodes 1 and 2, and Structure B with nodes 1 when I run the comparison I would get some sort of result that says Node 1 is in Structure A but not in Structure B (new node).
Vice-versa, if Structure B has nodes that are not in Structure A, the comparison would be able to tell me that. And when both structures have the same nodes it would be able to compare those.
Comment: What does ```Structure``` mean? Is it a domain object? It's not very clear if you want to check simply the presence of the object(in that case just flatten the trees and compare) or if the path in the tree is important.
Comment: By structure I meant to describe a Tree like Domain object. This structure would have
a parent (root node) and a set of children (a child can be a branch or a leaf).
When I compare 2 objects I would like to know the children that are in object One and not in Two
or vice-versa. And for the nodes that have the same signature (same key) I will run a field-by-field comparison
Answer: It seems like you are in a data structures Class so I would not suggest using anything that you haven't learned in class.
With that said I would suggest making you node class, and setting up a class that checks all the nodes in a tree recursively. AND set it up to search both trees.
When you are searching both trees you can print in the recursive statement about what nodes exist and what don't depending if the nodes match or not.
Just a node as well, don't compare the nodes because they have set ID's with java compare their values instead.

Tree comparison node by node


ANDROID: Get next item from listview to editText after 1st item is saved

Question: What I have: (1st Functionality)
I have a listview activity populated with items from JSON url. I have another activity where I get the listItem to editText field and then click "save", which saves the value to dB.
What I additionally want: (2nd Functionality)
When I click save, rather than going back to listview and select next listItem, I want the editText to fill the new listItem for me. But I am making errors in every step.
Below is the code that I have for 1st Functionality. I know it is just few lines to achieve the 2nd functionality but struggling with that.

The problem here is I cannot call the list String variable from one
  activity to another and assign position or a counter to it. Suggest me
  what to change here.

MainActivity.java (Class containing ListView populated with item from json url)
package com.example.app.listview;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends AppCompatActivity {

    ListView listView;
    ArrayList<String> tutorialList = new ArrayList<String>();

    private final static String URL = "-----json------url----file";

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

        new FetchDataTask().execute(URL);

    }

    private class FetchDataTask extends AsyncTask<String, Void, String>{

        @Override
        protected String doInBackground(String... params) {

            InputStream inputStream = null;
            String result= null;
            HttpClient client = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(params[0]);

            try {

                HttpResponse response = client.execute(httpGet);
                inputStream = response.getEntity().getContent();

                // convert inputstream to string
                if(inputStream != null){
                    result = convertInputStreamToString(inputStream);
                    Log.i("App", "Data received:" +result);

                }
                else
                    result = "Failed to fetch data";

                return result;

            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(String dataFetched) {
            //parse the JSON data and then display
            parseJSON(dataFetched);
        }

        private String convertInputStreamToString(InputStream inputStream) throws IOException{
            BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
            String line = "";
            String result = "";
            while((line = bufferedReader.readLine()) != null)
                result += line;

            inputStream.close();
            return result;

        }

        private void parseJSON(String data){

            try{
                JSONArray jsonMainNode = new JSONArray(data);

                int jsonArrLength = jsonMainNode.length();

                for(int i=0; i < jsonArrLength; i++) {
                    JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
                    String postTitle = jsonChildNode.getString("codeid");
                    tutorialList.add(postTitle);
                }

                // Get ListView object from xml
                listView = (ListView) findViewById(R.id.list);

                // Define a new Adapter
                ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, android.R.id.text1, tutorialList);

//                 Assign adapter to ListView
                listView.setAdapter(adapter);
                        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
                                Intent intent =  new Intent(MainActivity.this, AddFlowerInfo.class);
                                intent.putExtra("Code", listView.getItemAtPosition(i).toString());
                                startActivity(intent);
                            }
        });

            }catch(Exception e){
                Log.i("App", "Error parsing data" +e.getMessage());

            }
        }
    }
}

editText.java (class containing editText field and save to dB)
package com.example.app.listview;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.util.Log;
import android.view.View;

public class AddFlowerInfo extends AppCompatActivity  {
    EditText editText; //non editable codeid <<----<<----<<----<<--<<---<<1
    private static final String TAG = "AddFlowerInfo";

    Button savedata;
    String noneditcode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_flower_info);
        editText = (EditText) findViewById(R.id.codeid);
        savedata = (Button) findViewById(R.id.saveflowerinfo);

        final String Codeholder = getIntent().getStringExtra("Code");
        editText.setText(Codeholder);
      }

    public void dataflowerinfo(View view){

        noneditcode = editText.getText().toString();

        String method = "FlowerInfo";
        BackgroundTask2 backgroundTask2 = new BackgroundTask2(this);
        backgroundTask2.execute(method, noneditcode);
        finish();

    }

UPDATE AddFlowerInfo.java (OnCreate) and (OnClick)
public class AddFlowerInfo extends AppCompatActivity  {
    EditText editText; //non editable codeid <<----<<----<<----<<--<<---<<1
    private static final String TAG = "AddFlowerInfo";

    Button savedata;
    int i=0;

    String noneditcode;
    int pos;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_flower_info);
        editText = (EditText) findViewById(R.id.codeid);
        savedata = (Button) findViewById(R.id.saveflowerinfo);

        Intent i =getIntent();
        final ArrayList<String> list = i.getStringArrayListExtra("key");
          pos = i.getIntExtra("position", 0);

//        final String Codeholder = getIntent().getStringExtra("Code");
        editText.setText(list.get(pos));

        savedata.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent =  new Intent(AddFlowerInfo.this, AddFlowerInfo.class);
                startActivity(intent);

                ++pos;
                if(pos<=list.size()-1)

                    list.get(pos);

            }
        });

Comment: so are passing one string at a time to AddFlowerInfo activity.right?
Comment: yes @JinsLukose
Comment: so you have to save all data to  string array and pass it to AddFlowerInfo activity
Comment: Yes @JinsLukose , but I am not able to figure it out how to do it?
Comment: Can you write it for me, Because cannot understand that part
Comment: Instead of AddFlowerInfo as activity, why don't you make it a fragment. Show it inside/over the MainActivity. Use an interface to pass data to fragment from activity after every save.
Comment: @Arvind please wait a while
Comment: @Arvind why are you starting this
Intent intent =  new Intent(AddFlowerInfo.this, AddFlowerInfo.class);
activity again?
Comment: remove this:
Intent intent =  new Intent(AddFlowerInfo.this, AddFlowerInfo.class);
                startActivity(intent);

from onClick
Comment: because I want to redirect to the same activity page after button click
Comment: i removed it and when I click button it is doing nothing @SurajVaishnav
Comment: Please change list.get(pos);   =>  editText.setText(list.get(pos)) in onClick method
Comment: conceptually I thought after 1st item in edit text is saved, again the same activity should open with the next item in the list. So I did it, Now i removed it, No exception and error but the button click is not responding
Comment: @SurajVaishnav in the editText field the values are changing after I click but the data is not being saved in database
Comment: the flow goes like this when you click on submit button you should have to add code to save data to db if it is saved successfully then you can get new next item data and this process will goes until you reach at last item.
Comment: I guess it is because of android button on click method that I wrote to save data in dB. i think `savedata.setOnClickListener(new View.OnClickListener() {...}` and `public void dataflowerinfo(View view){...}` are clashed?
Comment: before adding this `savedata.setOnClickListener(new View.OnClickListener() {...}` the data was saved to dB and returned to listView. But now the data is not being saved but the values in editText are canging when I click them
Comment: @SurajVaishnav any suggestion or help?
Comment: Can you tell me what can I do to save the data to dB, no exception at all?
Comment: I can't give you suggestion, I am not aware of your code.
Comment: okay, thanks for you time, that is all the code I have in the question. May it is not saving because e have changed the listview items from string to array?  I think so maybe, anyway!
Answer: Pass your data from activity like this
 ArrayList<String> tutorialList = new ArrayList<String>();
 Intent intent = new Intent(ActivityName.this, Second.class);
 intent.putStringArrayListExtra("key", tutorialList);
 startActivity(intent);

To retrive at AddFlowerInfo
Intent i = getIntent();
ArrayList<String> list = i.getStringArrayListExtra("key");

Then as you are retrieving data from list using position ,each time after saving call data at next position
Comment: One concern I see with this approach is that when the user returns to the previous activity it will have old/stale data, not the one that's been edited.
Comment: @Kaustuv that's correct but that can be handled if he is not calling the Json data once again rather get the data from database
Comment: @JinsLukose if I do this, in AddFlowerInfo, It is showing error on line
`editText.setText(list)`. It is saying `cast parameter to 'java.lang.CharSequence'`, Then after I did, the app is showing an exception like     `java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.app.listview/com.example.app.listview.AddFlowerInfo}: java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.lang.CharSequence`
Comment: @JinsLukose can you help me out?
Comment: the below answer is actually correct. anyway let me check
Answer: You need to send complete array to AddFlowerInfo with the position, so change your onItemClick code:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
                Intent intent =  new Intent(MainActivity.this, AddFlowerInfo.class);
                intent.putExtra("position", i);
                intent.putStringArrayListExtra("array",tutorialList);
                startActivity(intent);
            }
        });

Now in AddFlowerInfo:
 Intent i = getIntent();
        ArrayList<String> tutorialList = i.getStringArrayListExtra("array");
        int pos=i.getIntExtra("position",0);

Use this position to get item from tutorialList.
To update data when user gets back to previous activity, place this code:
 new FetchDataTask().execute(URL);

into onResume method.
Update
After saving first item to edit second item use:
++pos;
if(pos<=tutorialList.size()-1)
    editText.setText(tutorialList.get(pos));
else
 {
   // you are after last item do whatever you want
 }

Comment: Instead of fetching everytime in onResume, won't it be better to start AddFlowerInfo activity for result, then onActivityResult fetch data if result=OK. This will prevent unnecessary fetching of data, say when coming from screen unlock.
Comment: It is showing me error on line `editText.setText(list)`. Here edit Text is have the value of the item from list and the error is `Castparameter to java.lang.Charsequence` this error is in AddFlower class where we set the text to go in to editText field @SurajVaishnav
Comment: Yes, it is working, but after saving the 1st item, I want the editText to be filled with the 2nd item from list without going back to the listView. So to that should i use the button's object and can you explain about `new FetchDataTask().execute(URL);`,
Comment: like I mean after ,
`editText.setText(list.get(position));
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // What should I write here//
            }
        });`
Comment: Yes, but `tutorialList` is in MainActivity. So it will be unresolved symbol in AddFlowerInfo class
Comment: and `++pos;
tutorialList.get(pos);` this should be written in `setOnClistener` method?
Comment: You may not following my complete answer, if you check i am using tutorialList variable in AddFlowerInfo to get data sent from MainActivity. the thing whatever name of list(you are using varable name=> list) pass new index to get data.
yes this code will be in onClick
Comment: yeah i understood it now, But I got  `java.lang.IndexOutOfBoundsException: Index: 24, Size: 24` and I am afraid that in `Onresume`,   `new FetchDataTask().execute(URL);` are unresolved, I mean what should i write inside FetchDataTask().
Comment: put if(pos<=tutorialList.size()-1) before tutorialList.get(pos); as i have updated my answer
Comment: @SurajVaishnav Actually the thing is since I am using 'position'in 'OnClick' it is asking me to declare it as `final array` and if I do that in `if` Statement, it is showing on line `if(...)` as `Operator '<=' cannot be applied to int[] and int`, So conflict!!!
Comment: make position global variable so it will not restrict you to declare final, try it and let me know if you face any problem
Comment: This is the exception :

   `java.lang.RuntimeException: Unable to start activity ComponentInfo{com.erawan.app.listview/com.example.app.listview.AddFlowerInfo}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.util.ArrayList.get(int)' on a null object reference`
Comment: And this is my code

`savedata.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent =  new Intent(AddFlowerInfo.this, AddFlowerInfo.class);
                startActivity(intent);

                ++pos;
                if(pos<=list.size()-1)

                    list.get(pos);

            }
        });`
Comment: where have you initialized list?
Comment: same as position, global
Comment: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.util.ArrayList.get(int)' on a null object reference
Comment: Please see it in UPDATE AddFlowerInfo.java (OnCreate) and (OnClick)
in question


Persistir currentUser do firebase com React Native

Question: Essa função é disparada ao clicar no botão de Login:
export const loginUser = ({ email, password }) => {
  return (dispatch) => {
    dispatch({ type: LOGIN_USER });

firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL)
.then(() => {
    firebase.auth().signInWithEmailAndPassword(email, password)
    .then(user => {
      firebase.database().ref('/admins').once('value')
      .then(snapshot => {
        const admins = _.map(snapshot.val(), (val, uid) => {
          return { ...val, uid };
        });
        if (admins.some((item) => item.s_email === email)) {
          typeAdmin(dispatch);
        } else typeStudent(dispatch);
        loginUserSuccess(dispatch, user);
      });
    }).catch(() => loginUserFail(dispatch));
  });
};
};

Comportamento Atual
Ao sair do aplicativo e voltar é necessário relogar para acessar os dados do currentUser.
Comportamento Esperado
Ao sair do aplicativo manter o currentUser da sessão e ao voltar nada ter sido perdido.
Answer: Eu já passei por isso e consegui resolver de uma maneira simples:
isLogged() {
    if(firebase.auth().currentUser){
        //Esta logado então faça algo ...
    }
}

componentDidMount() {
    isLogged();
}

O metodo isLogged() deve ser chamado após a inicialização do firebase ter sido feita ou irá gerar um erro.
Comment: Muito obrigado, essa solução deu certo. Optei por armazenar o status do usuário por AsyncStorage, assim mantenho as informações mesmo que o aplicativo seja fechado. Eu votei -1 no seu comentário sem querer e não tô conseguindo mudar. Valeu pela ajuda
Answer: Estou tentando fazer dessa forma, mas sempre que fecho o app o currentUser fica NULL
       firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL).then(() => {
          firebase.auth().signInWithEmailAndPassword(user, pass).then(loginUserSuccess)
          .catch(error => {
            console.log('erro');
           })
        })

esse console.log() abaixo mostra null sempre que abro o APP
  isLogged() {
    console.log(firebase.auth().currentUser);
    if(firebase.auth().currentUser){
      this.props.navigation.replace('Fazendas');
    }
  }

  componentDidMount() {
    this.isLogged();
  }


React Native change the state on child component

Question: I am wondering if there is a way to update a state in a parent functional component from a child component using a function, i want to assign the value of {item}  in child component to the state in parent component, i think i did that in wrong way
the parent  class components:
class Home extends Component {
  state = {
    year: '',
    month: '',
    day: '',
  };
  render() {
       <Dropdown
                 label= {i18n.locale == 'en' ? 'Year' : 'سنة'}
                 data={years}
                 onSelect={() => this.setState(year)}/>
}

the child component:
const Dropdown = ({ label, data ,onSelect}) => {
     const renderItem = ({ item }) => (
    onSelect={() => this.setState(item )}
   <TouchableOpacity style={styles.item} onPress={() => onItemPress(item)}>
      <Text style={styles.buttonText}>{item}</Text>
    </TouchableOpacity>
  );

}
Answer: Think of it like this: onSelect will be the bridge between your parent component this.setState and your child component. To do that and be flexible, onSelect should have at least one parameter. Judging from what you have, it looks like you only want Dropdown to update year:
 render() {
   <Dropdown
     label= {i18n.locale == 'en' ? 'Year' : 'سنة'}
     data={years}
     onSelect={year => this.setState({year})}/>
  }

Now in your child component think of onSelect as a function to call when it wants to update the year value in the parent component:
const Dropdown = ({ label, data ,onSelect}) => {
  const renderItem = ({ item }) => (
    <TouchableOpacity
      style={styles.item}
      onPress={() =>{
       onItemPress(item);
       onSelect(item);
      }
    >
      <Text style={styles.buttonText}>{item}</Text>
    </TouchableOpacity>
  );
}

Also just out of curiosity, is there reason why the parent component is a class?
Comment: i have another function at on press onPress={() => onItemPress(item) },
Comment: Where exactly do you intend call `onSelect` then?
Comment: this an old code i want rewrite it, so the is no reasons just i was have enough knowledge
Comment: not sure , but i want to assign the value of {item} in state of year
Comment: Okay try `onPress={ ()=>onItemPress(item);onSelect(item)}`
Comment: onPress={ ()=>onItemPress(item) +onSelect(item)}, it work like that thank you


Problem installing IP-Filters MAC for transparent proxy

Question: Am trying to compile squid to allow transparency using this command
<code>./configure --enable-ipf-transparent
</code>
on a MAC mini running 10.5.8
am getting a error
<code>WARNING: Cannot find necessary IP-Filter header files
         Transparent Proxy support WILL NOT be enabled
</code>
How can i solve this, how can I install the IP headers file, I already have the installer (IP Filter 4.1.33) but which distribution do I use for a mac
Answer: First Mac OS X uses ipfw and not ipf (I know it looks the same but it's not)
So use this command to configure your build. It's only available with Squid 3.0 and up.
<code>./configure --enable-ipfw-transparent
</code>
I'd suggest enabling SSL support as well
<code>./configure --enable-ipfw-transparent --enable-ssl
</code>


Redirect after Login using Meteor and Iron Router

Question: I'm using the built in loginButtons options with Meteor and I would like to redirect after a user logs in.  Using the built in web snippets means I can't use the callback with Meteor.loginwithPassword and I can't see any hooks inside Iron-Router to do the redirect.
Any suggestions?
Comment: did you try this https://github.com/EventedMind/iron-router#using-hooks Router.before(mustBeSignedIn, {except: ['login', 'signup', 'forgotPassword']});
Comment: I can't see any example pieces of code using this to see how to use it
Answer: Meteor often renders so quickly that the page is being loaded before the user has been defined.  You need to use Meteor.loggingIn() to account for the situation in which you are in the process of logging in. This code works for me:
this.route('myAccount', {
  path: '/',
  onBeforeAction: function () {
    if (! Meteor.user()) {
      if (!Meteor.loggingIn()) Router.go('login');
    }
  }
}

Comment: `if (!Meteor.loggingIn()) Router.go('login');`
Answer: This example might be useful
// main route render a template
Router.route('/', function () {
    this.render('main');
});

// render login template
Router.route('/login', function () {
    this.render('login');
});

// we want to be sure that the user is logging in
// for all routes but login
Router.onBeforeAction(function () {
    if (!Meteor.user() && !Meteor.loggingIn()) {
        this.redirect('/login');
    } else {
        // required by Iron to process the route handler
        this.next();
    }
}, {
    except: ['login']
});

// add here other routes

// catchall route
Router.route('/(.*)', function () {
    this.redirect('/catchallpage');
});

Answer: it should be very easy just add something like:
Tracker.autorun(function() {
  var currentRoute = Router.current();
  if (currentRoute === null) {
    return;
  }

  if (currentRoute.route.getName() === 'login' && Meteor.user() !== null)
    Router.go('WelcomeNewUser');
  }

You can also just use the same route with another template in case the user is not logged in.
just something like this:
this.route('myAccount', {
   before: function () {
     if (!Meteor.user()) {
       this.render('login');
       this.stop();
     }
   }
}

There is no magic, just looked into the docs ;)
Comment: Note that `Deps` is now called `Tracker`.
Comment: Is there a way to undo `this.stop()` after the user logged in?
Answer: You can simply use one of your existing routes you have configured in Ireland route
Router.go('/myRouterPathToTemplate')
Comment: Can you add an example of how this would be implemented


user input and loop bug in python script

Question: This is my first python project so thank you for your patience.
I have created a script to plot a route on pyplot depending on what route the user selects. To my amazement it actually works ,however, i am noticing a bug that I cannot iron out.
Once pyplot has generated a graph, it will only ask for the next input if i click on the red X to close the plot window. I want my code to produce the plot and continue to ask the user to input a new route number to plot. It is as if my code executes and then the loop stops and continues once i close the pyplot window.
from matplotlib import pyplot as plt

route001 = (3, 12, 'S', 'S', 'W', 'S', 'S', 'S', 'E', 'E', 'E', 'S', 'S', 'W',
            'W', 'S', 'E', 'E', 'E', 'E', 'N', 'N', 'N', 'N', 'W', 'N', 'N',
            'E', 'E', 'S', 'E', 'S', 'E', 'S', 'S', 'W', 'S', 'S', 'S', 'S',
            'S', 'E', 'N', 'E', 'E')

route002 = (12, 11, 'W', 'W', 'S', 'S', 'S', 'W', 'W', 'N', 'N', 'N', 'W', 'W',
        'W', 'S', 'S', 'S', 'S', 'E', 'E', 'S', 'W', 'W', 'W', 'W', 'N', 'N',
        'W', 'W', 'S', 'S', 'S', 'S', 'E', 'E', 'E', 'S', 'E', 'S', 'E', 'S')

route003 = (3, 12, 'S', 'S', 'W', 'S', 'S', 'S', 'W', 'W', 'W', 'S', 'S', 'W',
        'W', 'S', 'E', 'E', 'E', 'E', 'N', 'N', 'N', 'N', 'W', 'N', 'N', 'E',
        'E', 'S', 'E', 'S', 'E', 'S', 'S', 'W', 'S', 'S', 'S', 'S', 'S', 'E',
        'N', 'E', 'E')

while True:

route_selection = input('Select route 1, 2 or 3 ')
if route_selection == "1":
    selectedRoute = route001
elif route_selection == "2":
    selectedRoute = route002
elif route_selection == "3":
    selectedRoute = route003
else:
    print("error")

start = [selectedRoute[0]] + [selectedRoute[1]]
directions = selectedRoute[2:]
coordinates = {"N": [0, 1], 'E': [1, 0], 'S': [0, -1], 'W': [-1, 0]}
vector_list = []

def vectors():

    for d in directions:
        dx, dy = coordinates[d]
        start[0] += dx
        start[1] += dy
        if start[0] < 0 or start[0] > 12:
            print('Error: This route goes outside the grid')
            break
        elif start[1] < 0 or start[1] > 12:
            print('Error: This route goes outside the grid')
            break
        else:
            print(start)
            vector_list.append(start.copy())

vectors()
start_route = vector_list[0]
end_route = vector_list[-1]

def drone_plot():

    x = [p[0] for p in vector_list]
    y = [p[1] for p in vector_list]
    _, ax = plt.subplots()
    ax.set_xticks(range(13))
    ax.set_yticks(range(13))
    ax.plot(x, y, 'o-', color='blue')
    plt.grid()
    plt.axis([0, 12, 0, 12])
    plt.text(start_route[0], start_route[1], " START")
    plt.text(end_route[0], end_route[1], ' END')
    plt.title('Drone Route')
    plt.show()
drone_plot()

Comment: Does this help? https://www.geeksforgeeks.org/how-to-update-a-plot-in-matplotlib/
Answer: Indentation is very important in Python. You have a while loop with nothing in the loop, so the unindented code asking for input should only execute once. You code should look like this:
while True:

    route_selection = input('Select route 1, 2 or 3 ')
    if route_selection == "1":
        selectedRoute = route001
    elif route_selection == "2":
        selectedRoute = route002
    elif route_selection == "3":
        selectedRoute = route003
    else:
        print("error")

However, you should be careful, as the loop as it is seems to be an infinite loop. A loop that has while True should have some exit condition and break statement within it.


Display only banners for a specific month

Question: I need to create a View that will display a banner for a specific month (regardless of the year).
I create a field for that called, DisplayMonth, which holds an integer (so September is 9).
I would like for that banner image to change automatically for 2014. Any september month, no matter what year, it will display the record with DisplayMonth = 9.
Answer: Create a contextual filter against the field that holds the month number. Provide a default value of PHP code:
<code>return date('n');
</code>
Now only those nodes will display in September that have 9 as the month number.
Comment: The date() function without the timestamp always returns the current date: `return date('n');` will work fine.


Can I make a search that shows all results, regardless the user's permissions?

Question: We have a knowledge base with very strict user access permissions. We want users to be able to see all pages in search results, even the ones that they can't access. We want users to be able to see if the content they are interested exists and ask for permission.
Comment: It's usually not allowed by design in solutions designed for Drupal, and standard behavior for solutions that originated away from Drupal, like Solr, Google Custom Search et cetera. Could you tell what's your need? Hacking Views or one of search modules, or integrating 3rd party, possibly paid solution?
Comment: We want to have a default-deny policy, but avoid duplicated content between teams by allowing users to see global search results. That way, they can ask for permission.
Answer: You can build this in views. Build your view as you normally would, use an exposed search, then under advanced > query settings > check off "Disable SQL rewriting". This will disable node_access checks as well as other modules that implement hook_query_alter().


Selenium Radio Button not Functioning

Question: I wish to create a bot for automatically fill in Google Form survey, which is filled with radio buttons. When I am trying to fill in the form, the first Gender radio button was successfully clicked. However, the second age group button was not? Is this a bug?
import time
from selenium import webdriver

browser = webdriver.Chrome(executable_path='C:/Users/ryan/Downloads/chromedriver.exe')
browser.get('https://docs.google.com/forms/d/e/1FAIpQLScA8I-O5FQoYPwU6yoYJmAwrIJdBB/viewform?fbzx=-1760864547538697754')

RadioGender= browser.find_element_by_xpath('//*[@id="i5"]/div[3]/div')
RadioGender.click()

RadioAge= browser.find_element_by_xpath('//*[@id="i18"]/div[3]/div/div')
RadioAge.click()

Answer: To handle dynamic element use WebDriverWait() and wait for element to be clickable and following locator strategy.
browser.get("https://docs.google.com/forms/d/e/1FAIpQLScA8I-O5FQoYPwU6yoYJmAwrIJdBBt1MqEgoQOz9oHWWmTY1Q/viewform?fbzx=-1760864547538697754")
WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.XPATH, '//span[text()="Next"]'))).click()
RadioGender= WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.XPATH, '//*[@data-value="Male"]')))
RadioGender.click()

RadioAge=  WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.XPATH, '//*[@data-value="21-23"]')))
RadioAge.click()

You need to import following libraries.
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

Note: If you would like to select other age range, you need pass those values as data value.

Selenium Radio Button not Functioning


Proof: $\operatorname{exp}G=o(g)$ for a finite abelian group ($g$ maximal order)

Question:
I don't understand why $h^{o(g)}\neq 1$ implies $f_i>e_i$, and not just $f_i\neq e_i$. It seems rather counterintuitive to me that $f_i>e_i$, given that $o(h)\leq o(g)$. Could someone clarify this step for me?
Answer: Suppose it's not true: then, for every $i$, $f_i\le e_i$, so $o(h)$ is a divisor of  $o(g)$, and $h^{o(g)}=1$, contrary to the hypothesis.


My SMS Transfer related App rejected due to Violation of Permissions policy

Question: I had submitted my SMS Transfer app on Google Play Store and I had added READ_SMS and WRITE_SMS permission in the manifest. I had selected "Cross-device synchronization or transfer of SMS or calls" from Declare permissions for your app but Google rejected the app with the below information:

Apps with a declared core functionality for Cross-device synchronization or transfer of SMS or calls can only access these permissions: READ_SMS, RECEIVE_MMS, RECEIVE_SMS, RECEIVE_WAP_PUSH, SEND_SMS, READ_CALL_LOG. Please remove the permission(s) WRITE_SMS.
Based on our review, we found your app's expressed user experience did not match your declared core functionality Cross-device synchronization or transfer of SMS or calls. Please remove these permissions from your app.
Your app has default handler capability, which was not disclosed in the declaration form. Please remove the unnecessary capability and / or submit a revised declaration form.
Comment: https://meta.stackoverflow.com/questions/272165/are-developer-centric-questions-about-application-stores-on-topic
Comment: I'm voting to close this question as off-topic because it concerns Google Play Store policies and procedures, rather than programming. Please refer to: [Are developer-centric questions about application stores on topic?](http://meta.stackoverflow.com/q/272165), [Why can't I ask customer service-related questions?](http://meta.stackoverflow.com/a/255746)
Answer: It is due to Google's restriction on SMS or Call log permission.
If you really need these permissions to fulfil certain functionalities, you should be filling 6-page Permission Declaration Form and submitting to Google Play for review.
Comment: Can I resubmit that form? if yes then how?
Answer: Try to use this app
it allows to send received SMS to other device or slack
https://play.google.com/store/apps/details?id=com.sms.pipe


one example of LDA and max number of features

Question: as i read the following post:
Sources' seeming disagreement on linear, quadratic and Fisher's discriminant analysis
and see the following note:

any where on google we see number of reduction is number of classes minus one. but here how this value reached? i.e: $X-1$
Important: $X << P $ in this example.
Update 1: I think the answer is # of classes minus one but at most we can use as much as training samples in LDA (no restriction up to $X-1$).

Update 2: I see in this Strange Link In a nutshell, the goal of a
LDA is often to project a feature space (a dataset $n$-dimensional
samples) into a smaller subspace $k$ (where $k \leq n-1 $))...

Update 3:
In Page 27 of this book tell us $n$ classes and $k$ features we get $k-1$ features by LDA.
Comment: I believe that I have figured out a way to answer your question. I will post something later. You may reply on that answer regarding how it applies to your example.
Answer: About linear discriminant analysis
A classical example of least discriminant analysis is R.A. Fisher's 1936 article "The use of multiple measurements in taxonomic problems". This is based on the iris dataset and easily plotted.
<code>### load library
### with Edgar Anderson's Iris data set
### and the lda function
library(MASS)

### Perform lda
lda <- lda(Species ~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width  , data = iris)

### Compute the discriminant
predict(lda)

### Plot histogram with result from first discriminant
plot(lda, dimen=1, breaks = seq(-10,10,0.5))

### Plot histogram with only one variable
layout(matrix(1:3,3))
hist(iris$Sepal.Length[iris$Species == "setosa"], breaks = seq(3,9,0.25),
     main = "", xlab = "group setosa", freq = 0)
hist(iris$Sepal.Length[iris$Species == "versicolor"], breaks = seq(3,9,0.25),
     main = "", xlab = "group versicolor", freq = 0)
hist(iris$Sepal.Length[iris$Species == "virginica"], breaks = seq(3,9,0.25),
     main = "", xlab = "group virginica", freq = 0)
</code>
Result from first linear discriminant

Result from a single variable (sepal length)

The idea from Fisher was to use a linear combination of the variables such that the distance between the classes is larger. This distance is considered relative to the variance of the groups. (To see more about this, consider this question: When is MANOVA most useful )
When parameters > samples
So, the intuition behind LDA is to find a linear combination of parameters for which the in-between distance/variance of the groups is larger than the within distance/variance of the groups.
When you have more parameters than the sample size, then you will be able to find a perfect linear combination. One for which the within distance is zero.
This linear combination can be found by finding the linear combination of parameters for which the linear combination in one class equals zero and in the other class equals one.
This relates to solving a linear regression problem
$$Y = \beta X$$
Where $Y$ is a column with ones and zeros depending on the class, $X$ is a matrix with the features, and $\beta$ are coeffients to be found.
This problem is overdetermined when the number of features is larger than the number of samples. This means that you will be able to find many linear functions of the features for which the one class equals zero and the other class equals one (as long as there are no different class members with the exact same features).
The number of features that you need is similar to the number of features that you need to fit exactly a regression problem. Which is $X-1$. For example, if you have two data points then a straight line, a function of only one feature (and a function of two parameters, because besides the slope the intercept is included as well), will fit perfectly through the points.
So $x-1$ features will be sufficient to find a perfect solution to the LDA problem
Regularization
So, when the number of features is larger than the sample, then the problem is similar to a regression problem.
For this over-determined case, you can say that $X-1$ features are sufficient, but it is not the only solution. The exact answer will be dependent on how you weigh the different solutions. You can do this in several ways. Regularization is one way to do it. In the case that the problem is solved with Lasso regression or stepwise regression (which add regressors/features in steps, building up a solution starting with zero regressors), then I can imagine that the limit is $x-1$ features. In the case that the problem is solved with ridge regression (which uses all regressors/features from the start) then this is not the case.
Comment: The one (C-1) refers to the number of discriminants. Say you have two classes, then a single linear combination is sufficient to separate the two. The other (X-1) refers to the number of features that go into a discriminant (and as I argued this is actually a limit for the number that is *sufficient*. You can put in more features if you want, it depends on the situation).


Doesn't run errorLNK1120: 1 unresolved externals VS

Question: I have these 2 simple classes. I have made a win32 app, but when i run it it shows me this error :

Error 2   error LNK1120: 1 unresolved
  externals C:\Users\D\Documents\Visual Studio Projects\LR3
  SYSPROG\Debug\LR3 SYSPROG.exe 1   1   LR3 SYSPROG

I have tried it to run before it worked just fine how did i screw it up even with out touching it ?
<code>    class Liquid
{
private:
    char *name;
    int density;
public:
    void CLperenaznachenie();
    //virtual void spiling();
public:
    char* get_name() const;
    void set_name(char const* new_name);
    int get_density() const;
    void set_density(int new_density);
};
class Alcohol:public Liquid
{
private:
    int fortress;
public:
    void CAperenaznachenie();
    //void spiling(){
    //new stuff
    //};
public:
    int get_fortress() const;
    void set_fortress(int new_fortress);
};
</code>
Comment: Don't you get an error before the one you posted? From the doc:

Error LNK1120 gives you a count (number) of unresolved externals for this link. The conditions that cause unresolved externals are described with error LNK2001, which precedes this error message (once for each unresolved external).
Answer: I have solved it by making it a console app and adding a main() function and that is what i need.


Deploying a Spring Boot Application on AWS Using AWS Elastic Beanstalk

Question: I want to deploy a Spring Boot Application on AWS Using AWS Elastic Beanstalk, but I don't see the option to upload a jar file, only zip and war (?!)
and in this tutorial they are deploying a jar file:
https://aws.amazon.com/es/blogs/devops/deploying-a-spring-boot-application-on-aws-using-aws-elastic-beanstalk/
Comment: You can just upload the JAR file using the same uploader for the ZIP or WAR file.
Answer: Tutorial: How to deploy a Spring Boot application to Amazon AWS using Elastic Beanstalk
Youtube video tutorial: https://www.youtube.com/watch?v=JYVlzoRMa3U
Source Code Link: https://github.com/marcthomas2013/spring-boot-aws
Full tutorial link: https://mtdevuk.com/2015/02/10/how-to-deploy-a-spring-boot-application-to-amazon-aws-using-elastic-beanstalk/
Creating a Spring Boot War:

Start up eclipse IDE with the Spring Extensions installed. For Luna add this link to your update installer http://dist.springsource.com/release/TOOLS/update/e4.4/
You'll also need Tomcat server installed in Eclipse. If you don't have this setup then search Google for setup instructions before you continue.
Select File->New->Other->Spring->Spring Starter Project
Set the name and the artifact to spring-boot-aws
Change the packaging from jar to war (This does a couple of things that I'll explain later)
Select Actuator and Remote Shell so that we have some RESTful services to test the app with.
Click Finish

It has created a simple Spring Boot application with some REST services like /beans that will return a JSON object of all the beans in your application.
Deploy your application using Amazon Elastic Beanstalk

Login to Amazon AWS.
In the main control panel select Elastic Beanstalk under Deployment & Management.
Click on Create Application in the top right corner.
Enter the Application Name and click Next.
Environment Tier – Web Server
Predefined Configuration – Tomcat
Environment Type – Single instance
Click Next
Select Upload your own, click Browse and locate the war you created earlier.
When the application is uploaded you will see the next page where you select your URL.
Enter a name and click check availability to see if you can use it.
Click Next
We don't need a RDB in this example so click next here.
In this next step you are defining the EC2 instance that will be created, if you are using a free trial then stick to the free t1.micro instance type.
EC2 Key Pair, can be left unselected. You won't need it for now and most likely you won't have one configured yet. This will be covered in a later post.
Click Next.
In Environment Tags click next again because we don't care about this.
Review the configuration, and then click Launch.

Amazon AWS will now provision your server, install the Tomcat server and deploy the war file that you uploaded. It does take a good 5-10 minutes for this action to complete.
Another Full tutorial is available here: Step-by-Step Guide to Deploying a Full-Stack Spring Boot Application in AWS
If you want to deploy code in the official way using CLI, then you can go through this tutorial:
P.S If you had problem of 502 Bad GateWay nginx you have three options
i prefer changing the spring boot port to 5000
check here for more details Bad GatWay problem 3 options to solve it
Comment: The link to ***Step-by-Step guide*** is no longer available :(
Comment: the source code was useful, but youtube video unavailable
Comment: @BaDrAmer I have linked up to another youtube video. Please check


Pegar último post WordPress no CakePHP

Question: Ao carregar:
define('WP_USE_THEMES', false);
require(ROOT.'\blog\wp-blog-header.php');

Estou tendo o seguinte erro:

Fatal error: Cannot redeclare __()

Como posso carregar o último post do blog em um projeto em CakePHP?
Comment: Você não pode utilizar a função `require` mais de uma vez para um mesmo arquivo.
Answer: Não aconselho você tentar carregar todo o WordPress dentro do projeto em Cake, vai chamar um monte de funções que você não precisa, é muita coisa para apenas poder ter acesso a um post.
Enfim, é possível fazer uma consulta direto no banco de dados do WordPress ou então usar logo o Feed desta forma:
$feed_url = 'http://localhost/blog/feed/';
$content = file_get_contents($feed_url);
$feed = new SimpleXmlElement($content);

if (isset($feed->channel->item[0])) {
    $entry = $feed->channel->item[0];

    printf('%2$s', $entry->link, $entry->title);
}

Answer: Realmente, não tem a necessidade de carregar tudo isso, fiz dessa forma:
$post = $this->Post->query(
        "SELECT
            posts.id,
            posts.post_title AS title,
            posts.post_date,
            posts.guid,
            files.meta_value AS filepath
        FROM
            wp_posts posts
        INNER JOIN wp_posts attachments ON posts.ID = attachments.post_parent
        INNER JOIN wp_postmeta files ON attachments.ID = files.post_id
        WHERE files.meta_key = '_wp_attached_file' ORDER BY posts.post_date DESC LIMIT 1"
    );
    $this->set('post', $post);

Answer: Também se pode usar XML-RPC para consultar o WordPress. Usando um arquivo PHP simples, disparamos uma requisição cURL ao endereço http://example.com/wordpress-folder/xml-rpc.php chamando algum método específico. Isso retorna um arquivo XML com os resultados da query.
<?php
/**
 * Executa chamada de XML-RPC
 */
function query_last_posts( $methodName, $url, $parameters )
{
    $request = xmlrpc_encode_request( $methodName, $parameters );
    $ch = curl_init();
    curl_setopt( $ch, CURLOPT_POSTFIELDS, $request );
    curl_setopt( $ch, CURLOPT_URL, $url );
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt( $ch, CURLOPT_TIMEOUT, 1 );
    $results = curl_exec( $ch );
    curl_close( $ch );
    return $results;
}

$blog_id = '1';
$user = 'username';
$pass = 'password';
$post_type = 'post';
$number_posts = '2';
$args = array( $blog_id, $user, $pass, $post_type, $number_posts );
$response = query_last_posts( 'b5f.getRecents', 'http://plugins.dev/xmlrpc.php', $args );

Como não tive bons resultados usando os métodos padrão, criei um método customizado (b5f.getRecent). Mas antes de explicar essa customização, aqui vão umas funções auxiliares para ver o retorno do XML-RPC:
/**
 * Função auxiliar: converte XML em JSON
 */
function print_json( $string )
{
    # http://stackoverflow.com/a/20431742/1287812
    $xml = simplexml_load_string( $string );
    $json = json_encode( $xml );
    $array = json_decode( $json, TRUE );
    printf( '
%s
', print_r( $array, true ) );
}
/**
 * Função auxiliar: dá saída a XML no browser
 */
function print_xml( $string )
{
    header("Content-type: text/xml");
    echo $string;
}
/**
 * Função auxiliar: imprime o node principal do valor retornado
 */
function print_xml_node( $string )
{
    $xml = simplexml_load_string( $string );
    printf( '
%s
', print_r( $xml->params->param->value->array->data->value, true ) );
}

# print_json( $response );
# print_xml( $response );
print_xml_node( $response );

Para criar métodos personalizados, é só criar um plugin e usar o hook xmlrpc_methods (sugiro fazer um Must Use plugin):
<?php
/**
 * Plugin Name: Chamada personalizada ao XML-RPC
 * Description: Novos métodos para o http://example.com/xml-rpc.php do WordPress
 * Plugin URI:
 * Author: brasofilo
*/
add_filter( 'xmlrpc_methods', 'xmlrpc_methods_sopt_28962' );

function xmlrpc_methods_sopt_28962( $methods )
{
    $methods['b5f.getRecents'] = 'b5f_get_recent';
    return $methods;
}

function b5f_get_recent( $args )
{
        global $wp_xmlrpc_server;
        $wp_xmlrpc_server->escape( $args );

        $blog_ID     = (int) $args[0];
        $username  = $args[1];
        $password   = $args[2];
        $post_type  = $args[3];
        $numberposts = $args[4];
        $extra = $args[5];

        if ( !$user = $wp_xmlrpc_server->login( $username, $password ) )
            return $wp_xmlrpc_server->error;

        $category_int = (int) $category;
        $post_args = array(
                'numberposts' => $numberposts,
                'posts_per_page' => $numberposts,
                'post_type' => $post_type,
                'post_status' => 'publish'
            );

        if( is_array( $extra ) )
            $post_args = array_merge( $post_args, $extra );

        $posts_list = query_posts( $post_args );
        if ( !$posts_list ) {
            $wp_xmlrpc_server->error = new IXR_Error(500, __('Either there are no posts, or something went wrong.'));
            return $wp_xmlrpc_server->error;
        }
        return $posts_list;
}

Pegar último post WordPress no CakePHP


how to improve knowledge of html,css,javascript

Question: I know that my title can sound as strange but this is my actual situation.
I define my self as web developer but i'm in a frustrating situation, I know about html and css but i would like to improve and I'm searching for some course or tutorial but most of them are very simple and too basic, the same for css.
During this month I have also learn bootstrap.
About javascript more or less I'm in the same situation, I started from zero some month ago, I finish for example all course in codecademy page and some other tutorial. Now I have a basic knowledge but I want to improve, the problem is that there are course tutorial to easy just to have base of javascript or I found some pages too difficult, there is not something like medium level.
I know that one of the classic suggestion is just try to do something or practice but I would like to ask you if someone can give me some suggestion, some pages like https://www.codecademy.com/learn but more difficult.
thank you very much
Comment: Sorry, but these types of questions are off-topic for SO.
Comment: If you want to learn Node.js there's free/useful resource here http://nodeschool.io/
Comment: All those courses are supposed to be basic. If you really want to learn real stuff then start actually doing something which is too complex for you now. Then you will inevitably grow. Or give up. It's up to you.
Answer: Simple, lurk on Stackoverflow under the tag you want to learn for (javascript, html, css, etc.). Read the problem the poster is having and try to solve it without reading the given answers. After you have completed the task (or tried your best) read the given answers and compare code to see how you can improve.


Standardization for correlated observations

Question: I am interested in a paper by John Walsh (1947), which demonstrates the effect of intraclass correlation on significance testing. The full text is available here.
In outlining a proof, Walsh states "It is easily seen from elementary considerations that
$$ \frac{(\bar{x} - \mu)\sqrt{n}} {\sigma\sqrt{1 + (n - 1)\rho}}$$
has the distribution N(0 , 1)" Where $\rho$ is the intraclass correlation.
Unfortunately, this is not so elementary for me.
I would be grateful if someone can explain why this random variable comes from the standard normal distribution.
Comment: It is not possible to answer this until you define your terms!
Comment: @kjetilbhalvorsen It's not necessary to define the terms. It's obviously a standardised version of the average. JohnK has a simple but nice proof.
Answer: $$ \begin{align} Var(\bar{X}) = \frac{1}{n^2} Var( \sum_{i=1}^n X_i ) & = \frac{1}{n^2}\left( \sum_{i=1}^n var(X_i) + \sum _{i \neq j} cov\left(X_i , X_j \right) \right) \\ &= \frac{1}{n^2} \left( n \sigma^2 + n (n-1) \rho \sigma^2 \right) \\ & =\frac{\sigma^2 }{n} \left( 1 + \left(n-1 \right) \rho  \right) \end{align}$$
where we have used the fact that $cov\left(X_i, X_j \right) = \rho \sigma_i \sigma_j$ and the equal variances of your observations. So standardize by that in order to get the standard normal distribution!
On a side note, Walsh is a genius and his papers are always worth reading no matter how frustrating it can be at times.
Comment: or rather, standardize by dividing by the *square root* of that.
Comment: @Glen_b Yes, I thought that this was implied :)


Difference between "if (foo) bar();" and "foo && bar();"

Question: Is there any difference between the following two snippets, or any reason to use one over the other?
if (foo) {
    bar();
}

foo && bar();

Comment: The 1st is more traditional. Effectively, they're the same, though.
Comment: No difference but I prefer one line `if` statements. `if (foo) bar();`
Answer: The second form is known as short-circuit evaluation and results in exactly the same as the first form. However the first form is more readable and should be preferred for maintainability.
This type of short-cuircuit evaluation is often seen in if-statements, where the right hand is conditionally evaluated. See the example below; bar is only evaluated if foo evaluates to true.
if (foo && bar()) {
    // ...
}

Comment: It is not exactly the same, in the sense of grammar. (*expression* vs *statement*)
Answer: The version foo && bar() is an expression, and thus has a value:
var result = foo && bar();

When using the if version, the above might look like this:
var result;
if (foo) {
    result = bar();
}

which is more verbose.
Comment: Actually `foo && bar();` is a statement, not expression, `foo && bar()` is an expression.
Comment: @zch Correct. It is an [expression statement](http://es5.github.io/#x12.4).
Comment: the if-version is not correct; if foo is falsy, that falsy value is returned. Thus `else { result = foo; }`.
Answer: The answer of bouke with the short-cuircuit evaluation is really good. But I like to add that a good coding style is the use of the if-statement, if the call of bar() has no boolean-return-value and no further condition has to be satisfied using bar().


Como definir a ordem em que os componentes receberão foco através do TAB?

Question: Para organizar a ordem de seleção de foco dos componentes até a versão 1.4 do java, utilizávamos o método setNextFocusableComponent(). Porém ele foi descontinuado a partir da versão citada.
Gostaria de saber como faço nas versões mais recentes para poder controlar a ordem de foco de componentes na tela através da tecla TAB. Por exemplo, o código abaixo tem 4 componentes distintos, e eles recebem foco na ordem que foram adicionados na tela:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;

public class NextFocusTest extends JFrame {

    private static final long serialVersionUID = 1L;
    private JPanel contentPane;
    private JPanel panel;
    private JTextField firstComp;
    private JComboBox<String> thirdComp;
    private JTextField secondComp;
    private JButton fourthComp;

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            NextFocusTest frame = new NextFocusTest();
            frame.setVisible(true);
        });
    }

    public NextFocusTest() {
        initComponents();
    }

    private void initComponents() {

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setPreferredSize(new Dimension(350, 200));
        this.contentPane = new JPanel();
        this.contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        this.contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(this.contentPane);

        this.panel = new JPanel();
        this.panel.setBorder(new EmptyBorder(0, 20, 0, 20));
        this.panel.setLayout(new GridLayout(2, 2, 20, 5));
        this.contentPane.add(this.panel, BorderLayout.NORTH);

        this.firstComp = new JTextField();
        this.firstComp.setPreferredSize(new Dimension(100, 20));
        this.panel.add(this.firstComp);

        this.thirdComp = new JComboBox<String>();
        this.thirdComp.setModel(new DefaultComboBoxModel<String>(new String[] { "teste 1", "teste 2", "teste 3" }));
        this.thirdComp.setPreferredSize(new Dimension(100, 20));
        this.panel.add(this.thirdComp);

        this.secondComp = new JTextField();
        this.secondComp.setPreferredSize(new Dimension(100, 20));
        this.panel.add(this.secondComp);

        this.fourthComp = new JButton("OK");
        this.fourthComp.setPreferredSize(new Dimension(90, 23));
        this.panel.add(this.fourthComp);

        pack();
    }
}

Alternando o foco com TAB:

Como faço para definir manualmente a ordem de foco dos componentes, por exemplo, seguindo a ordem abaixo?

primeiro campo de texto
segundo campo de texto
combobox
botão
Comment: Já tentou usar o método `setNextFocusableComponent`. Veja um exemplo: `firstComp.setNextFocusableComponent(secondComp);`
Comment: haha... só li o título. mals xD
Comment: @acklay logo no começo da pergunta eu cito ele, está descontinuado.
Answer: Utilize a classe FocusTraversalPolicy para definir a ordem de foco dos componentes de um container. Para tanto, extenda a classe FocusTraversalPolicy, implemente a política de foco e atribua utilizando setFocusTraversalPolicy. O código baseado no seu exemplo ficaria mais ou menos assim:
import java.awt.*;
import java.util.LinkedList;
import javax.swing.*;
import javax.swing.border.EmptyBorder;

public class NextFocusTest extends JFrame {

  private static final long serialVersionUID = 1L;
  private JPanel contentPane;
  private JPanel panel;
  private JTextField firstComp;
  private JComboBox<String> thirdComp;
  private JTextField secondComp;
  private JButton fourthComp;

  public static void main(String[] args) {
    EventQueue.invokeLater(() -> {
      NextFocusTest frame = new NextFocusTest();
      frame.setVisible(true);
    });
  }

  public NextFocusTest() {
    initComponents();
  }

  private void initComponents() {

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setPreferredSize(new Dimension(350, 200));
    this.contentPane = new JPanel();
    this.contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    this.contentPane.setLayout(new BorderLayout(0, 0));
    setContentPane(this.contentPane);

    this.panel = new JPanel();
    this.panel.setBorder(new EmptyBorder(0, 20, 0, 20));
    this.panel.setLayout(new GridLayout(2, 2, 20, 5));
    this.contentPane.add(this.panel, BorderLayout.NORTH);

    this.firstComp = new JTextField();
    this.firstComp.setPreferredSize(new Dimension(100, 20));
    this.panel.add(this.firstComp);

    this.thirdComp = new JComboBox<>();
    this.thirdComp.setModel(new DefaultComboBoxModel<String>(new String[]{"teste 1", "teste 2", "teste 3"}));
    this.thirdComp.setPreferredSize(new Dimension(100, 20));
    this.panel.add(this.thirdComp);

    this.secondComp = new JTextField();
    this.secondComp.setPreferredSize(new Dimension(100, 20));
    this.panel.add(this.secondComp);

    this.fourthComp = new JButton("OK");
    this.fourthComp.setPreferredSize(new Dimension(90, 23));
    this.panel.add(this.fourthComp);

    pack();
    setFocusTraversalPolicy(new PoliticaFoco());
  }

  class PoliticaFoco extends FocusTraversalPolicy {

    private final java.util.List<Component> componentes;
    private int focado = 0;

    public PoliticaFoco() {
      this.componentes = new LinkedList<>();
      this.componentes.add(thirdComp);
      this.componentes.add(firstComp);
      this.componentes.add(fourthComp);
      this.componentes.add(secondComp);
    }

    @Override
    public Component getComponentAfter(Container focusCycleRoot, Component aComponent) {
      this.focado = (this.focado + 1) % this.componentes.size();

      return this.componentes.get(focado);
    }

    @Override
    public Component getComponentBefore(Container focusCycleRoot, Component aComponent) {
      this.focado = (this.componentes.size() + this.focado - 1) % this.componentes.size();

      return this.componentes.get(focado);
    }

    @Override
    public Component getDefaultComponent(Container focusCycleRoot) {
      return this.componentes.get(0);
    }

    @Override
    public Component getLastComponent(Container focusCycleRoot) {
      return this.componentes.get(this.componentes.size() - 1);
    }

    @Override
    public Component getFirstComponent(Container focusCycleRoot) {
      return this.componentes.get(0);
    }
  }
}

Na implementação do FocusTraversalPolicy, implementamos os métodos getComponentAfter, getComponentBefore, getDefaultComponent e getLastComponent que determinam o componente que receberá o foco em cada uma das situações. Para controlar a ordem utilizei um List que recebe os componentes em ordem para controlar o foco. A desvantagem é que, para cada componente adicionado, será necessário incluir também na classe implementada.

Você pode também criar a política de foco genérica, da seguinte forma:
import java.awt.Component;
import java.awt.Container;
import java.awt.FocusTraversalPolicy;
import java.util.LinkedList;

public class PoliticaFocoGenerica extends FocusTraversalPolicy {

  protected final java.util.List<Component> componentes = new LinkedList<>();
  private int focado = 0;

  @Override
  public Component getComponentAfter(Container focusCycleRoot, Component aComponent) {
    this.focado = (this.focado + 1) % this.componentes.size();

    return this.componentes.get(focado);
  }

  @Override
  public Component getComponentBefore(Container focusCycleRoot, Component aComponent) {
    this.focado = (this.componentes.size() + this.focado - 1) % this.componentes.size();

    return this.componentes.get(focado);
  }

  @Override
  public Component getDefaultComponent(Container focusCycleRoot) {
    return this.componentes.get(0);
  }

  @Override
  public Component getLastComponent(Container focusCycleRoot) {
    return this.componentes.get(this.componentes.size() - 1);
  }

  @Override
  public Component getFirstComponent(Container focusCycleRoot) {
    return this.componentes.get(0);
  }
}

Apenas definindo os componentes em suas respectivas ordens, da seguinte forma:
class PoliticaFoco extends PoliticaFocoGenerica {

  public PoliticaFoco() {
    this.componentes.add(thirdComp);
    this.componentes.add(firstComp);
    this.componentes.add(fourthComp);
    this.componentes.add(secondComp);
  }
}

E no seu container:
...
setFocusTraversalPolicy(new PoliticaFoco());
...

Comment: Deu certo! Preferi criar um construtor na classe de politica de foco, pra ela receber de cara uma lista de componentes. Obrigado :)
Comment: @Articuno negativo, depois da versão 1.4 este método foi descontinuado e substituído pelo `FocusTraversalPolicy`. Tem até um [tutorial](https://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html#intro) baseado nisso no site da `Oracle`
Comment: Eu preciso mesmo criar uma classe a parte? Não tem algum método de container que eu possa definir isso não? Ou ser baseado no gerenciador de layout?
Comment: Entendi. Sem abusar demais, mas é possivel "generalizar" essa classe? Assim eu poderia reaproveitar em qualquer lugar sem ter que ficar copiando e adicionando os componentes na mao.
Comment: @Articuno Sim, coloquei um exemplo. Mas na realidade o componente você sempre vai ter que definir, afinal o objetivo é alterar a ordem manualmente, não?
Comment: No exemplo, você utilizou LinkedList. Essa escolha é opcional(posso escolher a lista de Collection que eu quiser) ou há alguma necessidade em se utilizar esta especificamente?
Comment: @Articuno é opcional, inclusive no exemplo do tutorial da Oracle é utilizado um `array` simples. Utilizei o `List` por julgar a implementação mais fácil de compreender
Comment: @Articuno bem interessante fazer dessa forma, fica mais "fechado", evitando erros posteriores!


Proof involving edges in different trees

Question: In the proof of the Kruskal's algorithm given in class, we made this statement:
given two different trees $T$ and $T'$ on $n$ vertices, and given and edge $e \in E(T)\setminus E(T')$, consider the edge $e'$ such that $e' \in E(T')\setminus E(T)$ and $T\setminus \{e\} \cup \{e'\}$ is a tree on $n$ vertices ($E(T),E(T')$ denote the edge sets of $T$ and $T'$ respectively).
Now, intuitively I believe that such an $e'$ exists, but can I say that this always true?
Thank you
Answer: Deleting edge $e$ from $T$ gives two connected components (call their vertex sets $A$ and $B$). Since $T'$ is connected, it must contain some edge $e'$ from $A$ to $B$. Add that edge $e'$ to $T-e$, and it will be connected again; since this returns us to the minimum number of edges, the result is another spanning tree.
Answer: I am assuming you are talking about spanning trees. In Matroid theory (and specifically cycle matroids in your case) What you are referring to is called the "base exchange property".


Examples of mathematical Fields that don't revolve around numbers?

Question: I have heard of this which doesn't seem to be revolving around numbers:

Boolean Algebra: The set of Boolean values {0, 1} forms a field known as the Boolean field. The operations are logical AND and logical OR.

But most examples are the rational, real or complex numbers. Matrices, and functions revolving around numbers, also don't count. I am imagining possibilities like data models in software or something outside of numbers entirely. Not sure if anything like this exists.
What are some key examples of fields which help stretch your mind beyond thinking about numbers? Ideally an example which would help me gain stronger intuition for the concept of fields in a generalized way.
I mean field in the algebraic structure sense, not as in "field of knowledge."
Comment: To clarify... by fields do you mean the abstract algebra structure, or do you mean field as in "general topic of knowledge"?
Comment: Your example is not a field in the algebraic sense. It is easy to verify, as neither the AND nor the OR Cayley Table are a Latin Square. You can fix the problem by replacing OR with XOR (exclusive OR), in which case what you have is just the integers modulo $2$ under modular addition and multiplication (XOR corresponds to modular addition, AND to modular multiplication).
Comment: Maybe classical geometry would count.
Comment: @Aruralreader Can you go into more detail?
Comment: I mean https://en.wikipedia.org/wiki/Field_(mathematics) not a field of knowledge.
Answer: You seek intuition about fields by asking about areas of math that don't involve numbers, when it seems you are using the word "number" to mean "a complex number".  So I think you want fields that are not naturally viewed as subfields of the complex numbers, rather than something without a concept like numbers at all (such as basic topology). I don't see at all how studying something without any algebraic structure could give you intuition about general fields.
Look at finite fields and  fields of rational functions such as $\mathbf C(x_1,\ldots,x_n)$.  Note a field of prime size $p$ can be regarded as a quotient $\mathbf Z/p\mathbf Z$, so it comes from  integers even though it's not inside the integers. Do you consider that to mean the field doesn't "involve numbers"?
The subject of field theory, as a new branch of abstract algebra, was developed by Steinitz when he learned about $p$-adic numbers $\mathbf Q_p$ where $p$ is a prime number. The $p$-adic numbers are a lot more complicated and mind-bending then the fields I already mentioned, so you could look at those too. (Some people may tell you $\mathbf Q_p$ can be embedded into $\mathbf C$ by Zorn's lemma, but such an embedding can't be written down in any natural way, so for your purposes $\mathbf Q_p$ doesn't live inside $\mathbf C$.)


Como utilizar o FreeTDS com MAMP no Mac OS?

Question: Preciso utilizar os métodos mssql_ do PHP e sempre fiz isso utilizando o FreeTDS no Apache nativo do MAC OS.
O que acontece é que logo após fazer a atualização para o OS X 10.9 (Mavericks) passei a utilizar o pacote MAMP e não mais o Apache nativo por questões pessoais e pela facilidade na personalização do Apache/PHP.
Sei que preciso ativar a extensão no php.ini (no meu caso está em /Applications/MAMP/bin/php/php5.5.3/conf/php.ini) porém não tenho certeza se preciso compilar o PHP novamente.
Alguém teria ideia da melhor forma a proceder?
Answer: Instalando o Free TDS

Crie o diretório /usr/local/freetds

Faça download do freetds: ftp://ftp.freetds.org/pub/freetds/current/freetds-current.tgz

Abra uma janela de terminal e descompactar o arquivo que acabou de baixar

No terminalvá até a pasta criada após descompactar
cd ~/Downloads/freetds-current

Execute o seguinte comando em seguida
./configure --prefix=/usr/local/freetds --sysconfdir=/usr/local/freetds/conf/freetds --disable-libiconv --disable-odbc

Após concluir digite "make" e pressione enter

Digite sudo make install e enter novamente

Digite sua senha e espere concluir.

Compilando o PHP para obter o mssql.so

Faça download da versão que está utilizando (http://php.net/downloads.php)

No terminal entre no diretório descompactado do php que acabou de baixar.

Digite ./configure e pressione enter.

Depois "make" e enter

Vá até a pasta da extensão do mssql
cd ~/Downloads/php-<versão>/ext/mssql

Digite phpize e enter

Digite o comando abaixo após isso
./configure --with-mssql=/usr/local/freetds

Abra um Editor de texto e edite o arquivo:
~/Downloads/php-<versão>/ext/mssql/php_mssql.c

Altere a linha 181 trocando PHP_FE_END para {NULL, NULL, NULL}
// Antes
PHP_FE(mssql_guid_string, arginfo_mssql_guid_string)
    PHP_FE_END
};

// Depois
PHP_FE(mssql_guid_string, arginfo_mssql_guid_string)
    {NULL, NULL, NULL}
};

Volte para o terminal - verifique se ainda está na pasta ~/Downloads/php-<versao>/ext/mssql
Digite make e enter
Abra o finder e vá até a pasta do modulo do mssql (~/Downloads/php-<versão>/ext/mssql/modules/)
Copie mssql.so para a pasta de extensão do MAMP. Deve ser algo como Applications/MAMP/bin/php/php-<versão>/lib/php/extensions/no-debug-non-zts-20090626/
Edite o seu php.ini /Applications/MAMP/bin/php/php-<versão>/conf/php.ini
Procure por extension=
Cole extension=mssql.so logo abaixo as outras linhas de extensões e reinicie o MAMP