How to build up to playing an F chord?

Question:
Possible Duplicate:
How can I best learn to play barre chords?

I recently just got back into trying to learn to play guitar.  I'm going through and learning all of the major chords in the book I'm reading.  I've now come to the dreaded F chord.  I've tried playing it, but I'm having a lot of difficulty.  I've finally managed to get it to where I can stretch my hand out enough to fret all of the notes... mostly.  I still have an issue with getting enough pressure to properly fret the barré.
My question is, are there practices/warm ups/etc. that one can do to help with being able to play an F chord, besides the obvious of just trying to play it?
Comment: Learn the barred E major position, take it up and down the fret board as an exercise. This will make the F major chord a heck easier.
Comment: check out http://music.stackexchange.com/q/2298/104 - ideas for strengthening fingers when away from the guitar
Comment: Possible duplicates: http://music.stackexchange.com/questions/1767/tips-playing-f-barre-chord http://music.stackexchange.com/questions/1419/how-can-i-best-learn-to-play-barre-chords http://music.stackexchange.com/questions/6982/what-are-the-correct-mechanics-for-a-guitar-f-barre-chord At least some of their answers seem relevant to this question.
Answer: I you're learning on a steel-strung acoustic guitar, consider practising barres on a nylon-strung instrument, or on an electric with narrow gauge strings. These require less pressure so you can get used to the shapes and build up your strength.
Whatever instrument you are practising on, start high up the neck. Near the nut is the hardest place to play a barre. So play a C at the 8th fret, get comfortable with that, then work your way down the neck until you can play the F comfortably.
I would recommend practising moving between the "E shape barre" and the "A shape barre":
<code>%1/1.3/4.3/3.2/2.1/1.1/1
%1/1.1/1.3/2.3/3.3/4.1/1
</code>
... and the corresponding minor shapes:
<code>%1/1.3/4.3/3.1/1.1/1.1/1
%1/1.1/1.3/3.3/4.2/2.1/1
</code>
... because it's actually easier on the hand to practice a variety of shapes; you will encounter these together a lot, and having both available to you is very useful. Indeed with these four shapes you can play pretty much any progression of major/minor chords, entirely with movable barre chords.
Answer: There are lots of exercises you can do.  Remember this ability won't come overnight!  It took me a while to play that dreaded F chord too.  Most of my students have the same problem.  Try practicing Fmaj7 for a while and get used to it.  Gradually tip your first finger down to bar the two strings together.
Answer: I am trying to remember what I started with and I'm pretty certain I first learnt the following sequence using only the basic E and A shapes:
E A F# B G# C# A B E
This means that from the 3rd chord onwards they are all barre chords, you just keep moving up the neck from the nut to 2nd fret, 4th, 5th and 7th frets.
Playing this faster and faster helped me not only get the barre nice and strong, but helped the speed on my 2nd, 3rd and 4th finger changes.
Answer: What I did, was to simple use my picking hand to literally "place" my fingers of the other hand on the right frets and when they were positioned right and the chord sounded reasonable, I did it again.
Practice and patience is key in learning to play an instrument, better do it slow with a good sound, than rushed with a buzzing sound.
Answer: The other answers are good on how to exercise your barre.
Before you have built up enough strength for the barre, you can alternatively use a simpler version of the F where you skip the two lowest strings:
<code>%X/X.X/X.3/3.2/2.1/1.1/1
</code>
and it's still a valid F chord.
Answer: I agree with the above answers - it's probably the biggest mountain you'll climb whilst learning guitar chords - but bear in mind that eventually players hardly need to pull the fretting hand in to the fingerboard with the thumb, and will use the whole arm to pull in the fingers.In other words don't try to push your fingers onto the board, try pulling them in using arm strength. This will also avoid RSI when laying lots of barre chords, as you will when you crack the trick

How to build up to playing an F chord?


Propensity Score Analysis with continuous treatment

Question: I have an observational dataset of about two dozen observed variables (continuous or discrete), plus a continuous variable of which I would like to measure the causal impact of on my dependent variable. Most of the R packages deal with binary or tri-level treatments.
The continuous treatment variable is not exactly continuous. It takes integer values between 0 and 250. The dataset is large enough to get multiple observations with the same value of the treatment variable.
Is it possible to make multiple discrete treatment levels and compare them in pairs. For example, get a causal estimate using propensity score matching of $Tr = 0$ to $0 < Tr < 6$. Then another one for $0 < Tr < 6$ and $5 < Tr < 11$, and so on? Would this be meaningful?
Even better, is there a good method/package to calculate the causal impact of a continuous variable directly? It seems to me to be a very general problem, so I'll be surprised if there aren't any good solutions to this out there.
Answer: This has been asked on the Statalist too. The post here mentions the  user-written command doseresponse (a multivalued treatment effect evaluation method to assess the effect of a drug that participants could take in different levels of intensity) or the subroutine gpscore. The relevant reference is

Bia, M. and Mattei, A. (2008) "A STATA Package for the Estimation of the Dose-Response Function through Adjustment for the Generalized Propensity Score", Stata Journal Vol. 8 Nr. 3

where the authors introduce the algorithm and its computation. So even if it's not for R this will surely help you to program it.
For the theoretical background of continuous treatment evaluation methods see Kluve (2007) or Imbens and Hirano (2004).


Wix: Set semicolon to CustomActionData

Question: I have a problem with setting data that contains semicolons to CustomActionData property.
By default CustomActionData class uses semicolon as DataSeparator and it breaks my data, when it contains semicolons.
Is there any way to put semicolons to CustomActionData except of replacing them by come keyword?
Comment: Have you tried putting the data with semicolons inside into a property? In this case it will be look like `param1=[value1];param2=[value2]`, etc.
Comment: Yes. Actualy I have a semicolon inside one of my properties. In this case I have brocken data in CustomAction because CustomActionData separate my property value in two parts.
Comment: Try using backslash `(\)` to escape semicolon
Comment: Replace ";" with "\;"?
I don't know when actually semicolon will be, because this is password property populated by user.
P.S. Yes, I know that this is not secure. :(
Comment: Using "\;" didn't works for me.
Comment: Ok, I ran out of ideas... hope someone else can help...
Answer: to pass a semicolon in your CustomActionData you should add one more semicolon.
Example:
CustomActionData="key1=value1;key2=value2.1;;value2.2;;value2.3" - this will pass key1=value1 and key2=value2.1;value2.2;value2.3
If you don't know where the semicolons are then I guess you can create method that escapes them by replacing each semicolon with two semicolon.
If there are more symbols that you don't know how to escape you easily find out creating a simple app that creates a CustomActionData instance, adds a key-value pair and outputs the CustomActionData string representation using ToString().
Example:
CustomActionData data = new CustomActionData();
data.Add("key1", "value1");
data.Add("key2", "value2.1;value2.2;value2.3");

Console.WriteLine(data.ToString());

I hope the information is helpful.
Comment: Tnx. I created a additional CustomAction to replace semicolons by keyword.
Comment: You can also access the raw string via `session["CustomActionData"]` if you want to take control of how it is deserialized. That is all [session.CustomActionData](https://stackoverflow.com/a/46965464/521757) does.
Answer: Back in 2006 I wrote a blog article and sample project:
InstallScript, meet CustomActionData
Basically I used the pattern: /KEY1=VALUE1 /KEY2=VALUE2
The library worked by calling a lookup function passing it "/KEY1=".  It then returned all data until the end of until the next " /".
Regardless I don't really use this much any more since I've moved onto C# DTF which has a CustomActionData class handles the derialization/deserialization for me.
Comment: Added a quick answer with your JSON approach for CustomActionData.
Answer: JSON Strings: Chris Painter - who has also answered this question with an older approach - has a blog entry that revolutionizes CustomActionData handling by using JSON strings. Now there is no string parsing to do, so far as you use a proper JSON library. Built-in serialization / deserialization: http://blog.iswix.com/2011/10/beam-me-up-using-json-to-serialize.html.
Technically: The technical nitty-gritties would be different depending on language, but JSON strings themselves are simple:
Groups=[{"Name":"Rockers","Description":"People who rock!"}]

You can resurrect an object in deferred mode! Just by calling Serialize and Deserialize.
Comment: This would still break when the model contains a semicolon in one of the values ...
Comment: I haven't tested it, but here is a sample using the [DTF serialization approach](https://github.com/glytzhkof/WiXDeferredModeSampleDTF). [See the custom action code here for interesting part](https://github.com/glytzhkof/WiXDeferredModeSampleDTF/blob/main/CustomActionSample/CustomAction.cs#L16). Also [see this answer](https://stackoverflow.com/a/66326396/129130). Here is [a sample of the "manual way" to do CustomActionData](https://github.com/glytzhkof/WiXDeferredModeSample) (using custom actions yourself).

Wix: Set semicolon to CustomActionData


Case statement in databricks

Question: I am trying to run the case statement in databricks
salesforce_df = spark.sql("SELECT
  (CASE WHEN StartDate=date.now() THEN True ELSE False END)
  as conversion FROM Tablename;")

date.now() as to be the current date.
But this synatax is not working. Please advise me .
Regards
Rohit
Comment: What do you mean by syntax is not working
Comment: StartDate=date.now() is not working in azure databricks
Comment: The value has display YYYY-MM-DD HH:MM:SSSS
Answer: To get current date, you can use the inbuilt function current_date in Databricks SQL statement to get the desired result.

The following is the sample data I have taken:

%sql

select  *  from t1

I used the following query to get the desired results:

spark.sql("SELECT *,(CASE  WHEN dt=current_date() THEN True ELSE False END) as conversion FROM t1;").show()

Case statement in databricks


Find relation between Categorical dependent variable and continuous independent variable

Question: I have one sample group of data where I found the difference between two categorical data (this is my dependent variable) and continuous - numerical data (this is my independent variable).
I want to answer my hypothesis based on a statistical method.
I am trying to find this statistical method to find a relation (significance) between a categorical dependent variable (ordinal) with a continuous independent variable.
Any suggestions?
Comment: Does https://stats.stackexchange.com/questions/97/what-are-good-basic-statistics-to-use-for-ordinal-data help?
Comment: Hello @mdewey, unfortunately no it doesn't! My aim is to find the statistical approach to find the significance within one sample group for categorical dependent variable with continuous independent variable... Any suggestions?
Comment: Thank you for editing your question but I still find what you've written unclear. By "two categorical data" do you mean you have two different categorical variables, or that you have one categorical variable which has only two categories (i.e. it's binary)? Then right at the end you mention "ordinal" for the first time. In fact it isn't even clear to me how your first sentence relates to your third. Could you try explaining again more clearly? It's probably best to describe each aspect of your data only once, rather than explain it twice but in different ways. Some context may help too.
Comment: Or he should paste a sample of his data
Answer: Just to be clear you want significance not strength of the relationship/association?
strength of relationship/association would be measured with:

spearman-rank-correlation
kendalls-tau
point biserial (if your categorical is dichotomous)

But if you really care about the significance of your relationship, in the past, many used a t-test for checking this. Well i would advise to use a similar concept from ML where it is known as permutation importance, but here it is called permutation tests (its similar in terms of shuffling ;-))
https://towardsdatascience.com/how-to-assess-statistical-significance-in-your-data-with-permutation-tests-8bb925b2113d
https://www.jwilber.me/permutationtest/
Excerpt:

Ideally, we'd calculate a test statistic for every possible
permutation of treatment among our groups. This would create
an exact distribution of all possible test statistics under our null
hypothesis.

I would advise the latter source for explaining and the first one for coding.
Comment: https://medium.com/@outside2SDs/an-overview-of-correlation-measures-between-categorical-and-continuous-variables-4c7f85610365 , with this setup you dont need a t-test, you only have one group. In summary point biserial, multinomial Regression but believe my you have not enough samples for anything greater than point biserial.
Comment: Can you update your answer and give me a hint on the setup? if it is really a small sample size with group comparison, than maybe the welch test would be sufficnet, as a leven test for checking variances is mostly distorted towards t-test. I can also give you the paper source, as it is free in psychological journey.
Comment: Hi, I have one group sample data (less than 10 participants). I have a categorical data (dependent variable) and a numerical continuous data (independent variable). I am trying to test my hypothesis based on these two variables. Can you send me any resource that could help? Thank you so much for all your help!
Comment: Thank you for your answer.
However, I would like to clarify that it is a small sample within-group test.
I want to find the significance between them so what is the most recommended statistical method?
Answer: If your categorical variable is binary, you can use (binomial) logistic regression, if it has more than two levels, multinomial logistic regression.  Maybe you should spline the continuous independent variable. That, and other decisions, depend on context that you did not tell us. In all cases, plot your data! This answer assumes you have enough data, at least aroun 100 for logistic regression. Otherwise, simpler methods like in the answer from @Patrick Bormann
Your question is really a faq, so see some stored searches, also this one.
Comment: In his comments below my post: quote: Hi, I have one group sample data (less than 10 participants), thats the reason i still no longer recommend permutation tests and any other things ^^ only the point biserial
Comment: He has 10 data points, how should he perform logistic regression, he couldnt even interpret p-values nor odds?
Comment: @Patrick Bormann: Where does it say he has ten data points? If so, you ar clearly right!


Add a CSS basing on the author of the comment

Question: This node has a comment by the user #1, who is the node author, and a comment by an anonymous user. I want to add an extra CSS class to comments by the node author.
The variables in Bartik's comment.tpl.php include $author and $comment-by-node-author.
What is the correct syntax for an if statement saying if this comment is by the node author (or by user #1) apply the class example and just print the comment as usual when the author is somebody else?
Answer: If (what I'm not sure) understand your question correctly, you want to add an extra class if the comment was posted by the node author.
As explained in Bartik documentation:

 /*   - $classes: String of classes that can be used to style contextually through
  *   CSS. It can be manipulated through the variable $classes_array from
  *   preprocess functions. The default values can be one or more of the following:
  *   - comment: The current template type, i.e., "theming hook".
  *   - comment-by-anonymous: Comment by an unregistered user.
  *   - comment-by-node-author: Comment by the author of the parent node.
  */

There are already specific classes for comments posted :

by node author : .comment-by-node-author
by anonymous : .comment-by-anonymous

And you can see that in your node markup :

/* ... */

Comment: I missed this and yes this works fine for this use case, thank you, but I was also hoping to address more uses case, see my comment below.
Answer: Drupal applies a CSS class to comments created from the user who is the author of the node (comment-by-node-author), but since you want to add a custom CSS class when the user who created the comment is either the node author or the user #1, I would use the following code.
function mytheme_preprocess_comment(&$variables) {
  if (($variables['comment']->uid == $variables['node']->uid) || $variables['comment']->uid == 1) {
    $variables['classes_array'][] = 'example';
  }
}

Using that code in your theme, the comment will have your custom CSS class when the user who created the comment is the same user who created the node, or when the user who created the comment is the user #1.
Comment: I'm not sure but in the way the question was redacted before you edited it, I understood Juc1 wanted to put an extra class for node author, not either user #1 or author. Let him tell us. ;)
Comment: The first revision of the question says _if this comment is by the node author (or by user id 1) apply the class "example" but if the comment is by anyone else just print the comment as usual ie without the extra class_. After that, there is just my edit, which I think doesn't change the meaning of the question.
Comment: You're right. Both your english and your knowledge are much better than mine !
Comment: Oh no, neither of them are better. I just focused on a little part of the question, without being any better.
Comment: @Kojo yes I meant different cases eg website 1 if the comment author is the node author, website 2 if the comment author is uid 1 - but kiamlaluno's code is helpful in showing possibilities.
For another use case suppose I want to target comment authors with the role "editor" - I tried swapping uid for rid in kiamlaluno's code but rid does not seem to work. If rid does not work is there some other way to say "if the comment author has the role id 5"?


significant mean difference over time?

Question: I need help. I am looking at two data sets that come from two surveys asked of the same group with the same population over a year apart. Year one, the group was asked to rate 15 statements on a scale of 1-5 and year two the group was asked to rate the same statements on the same scale. I want to know if there is a way to figure out at what point is the score in year two significantly different from the score in year 1. (eg. if year 1 score was 3.7 and year 2 score was 3.9, is the .2 difference significantly different?)
I understand I can use the t-test to look at the mean of each question and compare it to the year before. But I want to know at what point overall, is it .1, .2, .3? I understand the population has a large effect on the answer, so if I asked another group with a higher population over two years, what will that number be for them?
Comment: do you have monthly data or daily data or what?
Comment: Yearly. The survey is conducted once every year.
Comment: You want to do power analysis.
Answer: You should use a linear mixed model for this. This is about statistical significance, which is estimated / inferred from the sample, so we cannot give you a fixed number. If you want more details you will have to provide some data.
Comment: Here is an example from 2017:
Comment: Here is an example from 2017:
Overall, I am very satisfied as an employee of this organization.
5
4
4
5
5
4
5
5
5
5
2
4
4

From 2018:
Overall, I am very satisfied as an employee of this organization.
3
5
5
5
5
4
3
5
4
5
3
4
4

This is one question, I have 14 more like these. I want to put the scores on a table with year one and year two and delta and highlight all the delta's that are statistically significant. At what point would I highlight the delta? .2, .3, .4, etc.
Comment: FYI, this is the whole population, 100% response rate and not a sample.
Comment: @Yahya Can you please edit your question with this new information? Also, if you could add an additional year that would be even better. Some clarifications, are these all from the same people every year? Are they in the right order? So the first measurement in year 1 is for the same individual for measurement 1 in year 2? Also, are you trying to compare each year with the previous year, too see if there are differences for each year? Delta for you would be the difference year 2 - year 1?
Comment: Almost the same people, not in the right order. you are correct in that delta would be year 2 - year 1.
Comment: @Yahya Wait, I missed the part about this being data for the whole population, not a sample. If that is true, then there is no statistics to be done. There are no estimates or p-values.

significant mean difference over time?


In R, what does it mean when a function argument name ends with a single dot?

Question: Some common R functions have argument names that end with a single dot.
For example, the warning() function shows the following in the usage section when looking at the documentation with ?warning:
 warning(..., call. = TRUE, immediate. = FALSE, noBreaks. = FALSE,
         domain = NULL)

With the exception of "domain", all of the arguments with names have names that end in dots.
Similarly, the default prcomp() function from the 'stats' library shows the following in its usage instructions:
 prcomp(x, retx = TRUE, center = TRUE, scale. = FALSE,
        tol = NULL, rank. = NULL, ...)

The arguments "scale." and "rank." end with a dot, and all of the others do not. It seems particularly weird that "scale." ends with a dot but "center" does not.
I know a dot is a permitted character in a variable name with R, and that I could name a variable this.variable.name.is.full.of.dots. if I wanted to - but since the dot being the last character in the names of certain function arguments seems to be a recurring theme in common R functions, does this have a special meaning?
Comment: To be clear: I am **not** asking about the triple dots, I know that question has been asked many, many times already. I am asking about the naming convention where the names of some function arguments end in a single dot.
Comment: Perhaps part of the *reason* for this convention is to exploit partial matching while making the code internally cleaner to avoid overloading. Here, I was surprised to discover that in `prcomp` you can call with `scale` (e.g., `prcomp(x, scale = TRUE)` and it will still scale your variables as if you had called `prcomp(x, scale. = TRUE)`. This is a consequence of R's [partial argument matching](https://cran.r-project.org/doc/manuals/r-release/R-lang.html#Argument-matching) (which I had forgotten about), so `scale` will match `scale.`
Answer: Unless we have commit messages or a naming convention, we can only guess. And I suspect this is very old code, possibly even preceding R.
Looking at the source code of warning we can notice three facts:

The code creates an object call but uses call. later on. So the trailing dot prevents a name collision and avoids having to come up with a fitting name other than call.

All parameters passed to the .Internal call to warning have the trailing dot, which makes it easier to keep track and distinguish them from other parameters.

It has ... as a parameter and it is not impossible that someone might want to do warning(message = "The call was: ", call = "f(x)") for clarity. (I don't think this was the main consideration.)

Looking at the source code of prcomp, I suspect naming is intended to make it easier to distinguish the parameters from the scale and rank functions or ensure that the functions are not used instead of the parameters if the parameters are missing.
Answer: Basically it means "nothing special". In the case of call. it's probably because the authors didn't want to have confusion of the parameter name with the name of a base R function by the name of call. In the case of the other it might be for consistency with the first  naming choice as well as trying to make them sufficiently unusual that they would not be confused with other. The "dot" is just a character. There no semmantic reason for choosing those names. The is a slightly semantic justification for a leading period. Functions whose name start with a period get handled differently by a few other functions, such as the ls function.


How do I link fields of a 'user content type' to the actual logged in user?

Question: I'm using the User Content Type module (Drupal 7) in order to store some fields for each user, such as "zip code."
Now, in this node_edit page, I made a variant for a Catalog node, for a specific role. (Let's say "salesman".)
How do I link the actual logged in user with their respective User node, to show and store the "zip code" field in the Catalog node?
Comment: Can you provide a link to the module? A better way to associate fields with a specific user is via Admin => Configuration => People => Account settings => Manage fields
Comment: @Craig Hyatt, many thanks for your answer, I think it's the right solution. Obviously I didn't see this via in my admin menu: https://drupal.org/project/admin_menu; best regards!
Comment: Glad to help. I added my comment as an answer below for future reference. Please consider marking it the accepted solution!
Answer: In Drupal 7, the simplest way to associate fields with a specific user is via Admin => Configuration => People => Account settings => Manage fields.
Because of its simplicity, I recommend this approach as a starting point. If it's not flexible enough, consider the contributed Profile 2 module.


How to add fixed buttons above a ListView android?

Question: I want to have two buttons top of a listview. If I scroll below the listview I want that the buttons stay at top. I searched through many solutions on stackoverflow however I could not find the exact one for my case.
My layout xml(mainlayout.xml):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/latest_news_button" />

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/tracked_news_button" />
    </LinearLayout>

    <ListView
        android:id="@+id/mylist"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

    </ListView>

</LinearLayout>

The graphical layout produced is just what I wanted:

Here is my code to use this layout, in case I might fail to bind the Java code to layout;
public class MainActivity extends ListActivity{

Button latestButton;
Button trackedButton;
ListView lv = null;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.mainlayout);

    latestButton = (Button)findViewById(R.id.button1);
    latestButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(MainActivity.this, "Latest Button!", Toast.LENGTH_LONG).show();
        }
    });

    trackedButton = (Button)findViewById(R.id.button2);
    trackedButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(MainActivity.this, "Tracked Button!", Toast.LENGTH_LONG).show();
        }
    });

    this.lv = getListView();
    String[] values = new String[]{"asdfa","qwerqwer","banbn"};
    lv.setAdapter(new ArrayAdapter<String>(BilTrackerMainActivity.this, android.R.layout.simple_expandable_list_item_1, values));

}

however when this activity is called from my other activity my app unfortunately closed. LogCat says:

Your content must have a ListView whose id attribute is 'android.R.id.list'

But I try adding lv = (ListView)findViewById(R.id.mylist); instead of this.lv = getListView();. I could not solve this issue.
I am aware of ListView#addHeaderView but I want to solve my particular problem with using this kind of layout.
Comment: Your problem is not with the buttons, but with the id you chose for your `ListView` see answers below regarding `@android:id/list`
Comment: Why you just use RelativeLayout?
Comment: Thank you all, just changing my bad line to android:id="@android:id/list" seem to work. If someone provide a source for these kind of knowledge lack, I will appreciate that also. Now my top buttons are ok, but my list items does not work. I am working on them.
Comment: Is there a reason you are using `android.R.layout.simple_expandable_list_item_1` when you aren't using an expandable list?
Comment: Yes you are right. I deleted the expandable part and changed the last 2 lines of my code to this: `ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, android.R.id.text1, values);
        setListAdapter(adapter);`
Answer: Just change your listview id to   android:id="@android:id/list"
Comment: There is also an explanation [here](http://www.vogella.com/articles/AndroidListView/article.html#listactivity_layout)
Answer: Use a RelativeLayout.  Place the second button to the right of the first button using layout_toRightOf then place the listview beneath button one using layout_below.  Something like this (I haven't tested it, apologies for any typos)
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="@string/latest_news_button" />

    <Button
        android:id="@+id/button2"
        android:layout_toRightOf="@id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="@string/tracked_news_button" />

    <ListView
        android:id="@+id/mylist"
        android:layout_below="@id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</RelativeLayout>

Comment: Thanks, I am new to android and for now i will stick with linear layout. I tested your code and when you change ListView's android:id like Dipak and stated before, it will work.
Answer: Here is the xml you are looking for
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:background="#FF394952">

 <LinearLayout
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    style="@android:style/ButtonBar">

 <Button
    android:id="@+id/btn_AddMore"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/newItem"
    android:textColor="#FF394952"/>
 </LinearLayout>

 <ListView
    android:id="@+id/game_list"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_weight="1.0" />
</LinearLayout>

And when you design Activity for this dont use List activity directly use Activity and set adapter on the ListView.
 ListView lv = (ListView) findViewById(R.id.game_list);
    ArrayAdapter<String> listItem = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, android.R.id.text1, ALBUM_NAME);

    lv.setAdapter(listItem);
    lv.setTextFilterEnabled(true);

Comment: This will work, but this is just a different way to achieve the same end result. When using ListActivity, use the correct id on the ListView.
Comment: What you want to say? What the problem now
Answer: Use below xml file for that
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:id="@+id/mLlayout1" >
        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/latest_news_button" />

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/tracked_news_button" />
    </LinearLayout>

    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/mLlayout1" >
    </ListView>

</RelativeLayout>

Comment: Now it works, but using a RelativeLayout is completely unnecessary.
Comment: I am using Relativelayout to solve the problem of this line "If I scroll below the listview I want that the buttons stay at top. "
Answer: Create FrameLayout with [your ListView] and [LinearLayout with your buttons].
Do once something like this within onCreate()
LinearLayout myButtons = ...;
myButtons.bringToFront();

So, your ContentView will have a FrameLayout with two child, one of those is in foreground.
That's all. Hope it helped))


Como remover itens de um array?

Question:     function converterBinario () {
       numero = document.getElementById("Valor-decimal").value;
       var vetor = [];
       var i =numero;
       var cont=0;
       while(i>0){

         var resto = Math.floor(numero % 2);

         if (resto == 0 | 1 ){
            vetor[i] = resto;
            console.log(resto);
         }

        numero= Math.floor(numero/2);
        console.log(numero);
        i--;
    }

document.getElementById("resultado").innerHTML =vetor;
console.log(vetor);

}

Quero retirar os zeros do array que aparecem antes do 1.
Comment: Poderia ser mais claro na sua pergunta, um exemplo de como o array está e como deveria estar
Comment: Quer tirar todos os zeros da array?
Comment: Tirar todos antes do primeiro 1.O array está 0,0,0,1,0,1.Quero deixar 101.
Answer: Pode usar filter():
vetor = vetor.filter(function(v,i){
   return i >= vetor.indexOf(1);
});

O i >= vetor.indexOf(1) irá retornar apenas os índices a partir da primeira ocorrência de 1 no vetor.
Exemplo:

function converterBinario () {
   //       numero = document.getElementById("Valor-decimal").value;
   numero = 10;
   var vetor = [];
   var i =numero;
   var cont=0;
   while(i>=0){

      var resto = Math.floor(numero % 2);

      if (resto == 0 | 1){
         vetor[i] = resto;
      }

      numero= Math.floor(numero/2);
      //        console.log(numero);
      i--;

   }

   console.log("vetor original => ",vetor.join());

   vetor = vetor.filter(function(v,i){
      return i >= vetor.indexOf(1);
   });

   //document.getElementById("resultado").innerHTML =vetor;
   console.log("vetor filtrado => ",vetor.join());

}

converterBinario();
Comment: Complementando, o filter só irá retornar os valores onde `i >= vetor.indexOf(1)` for `true`.
Comment: Não entendi como funciona o  (return i >= vetor.indexOf(1);)
Comment: A funçao possui 2 parametros: v e i. "v" é o valor e "i" o índice. O filter irá percorrer a array retornando alguma coisa. O indexOf sempre encontra a primeira ocorrência, logo o return só irá retornar os itens da array cujo índice for igual ou maior do que a posição do primeiro item de valor 1 dentro da array.

Como remover itens de um array?


Testing a property which is an observable without having to subscribe to it in the component

Question: Given there is this component which uses an async pipe to display content in a template via an observable property. In the following example this observable property is named showMe$: Observable<boolean>;
All works well when I run the application. However, when I'm running the test it does not emit anything via the observable. I guess because the subscription does not happen:
@Component({
  selector: 'my-component',
  template: `

Hello!

  `
})
export class MyComponent implements OnInit {

  @Select(MyStore.foo) public foo$: Observable<string>;

  public showMe$: Observable<boolean>;

  ngOnInit() {
    this.showMe$ = this.foo$.pipe(
      last(),
      map((someValue) => {
        return !!someValue
      })
    );
  }
}

And this is the test:
describe('MyComponent', () => {
  let component: MyComponent;
  let fixture: ComponentFixture<MyComponent>;
  let scheduler: TestScheduler;

  beforeEach(() => {
    stub.foo$: new Subject();

    stub.Store = {
      select: selector => {
        switch (selector) => {
          case MyStore.foo:
            return stub.foo$;
          default:
            return new Subject();
        }
      }
    }

    scheduler = new TestScheduler((actual, expected) => {
      expect(actual).toEqual(expected);
    });

    await TestBed.configureTestingModule({
      // ...
    }).compileComponents();

    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    fixture.detectChanges(); // OnInit
  });

  it('should return true when a value is provided in another observable', fakeAsync(() => {

    // this provide the store with a value
    stub.foo$.next('trivial string');

    // somehow nothing happens, this is not evaluated
    scheduler.run(({expectObservable}) => {
      expectObservable(component.showMe$).toBe('a', { a: true });
    });

    tick();
  }));
});

But that does not pass, and it will return the following error:

When I refactor the component to use a BehaviorSubject rather than an Observable, then it does work. Probably because then a subscription is done in the component:
@Component({
  selector: 'my-component',
  template: `

Hello!

  `
})
export class MyComponent implements OnInit, OnDestroy {

  @Select(MyStore.foo) public foo$: Observable<string>;

  public showMe$ = BehaviorSubject(false);

  private destroyed$ = new Subject<boolean>();

  ngOnInit() {

    // preferably no subscription
    this.foo$
      .pipe(takeUntil(this.destroyed$))
      .subscribe((value) => {
         this.showMe$.next(!!someValue);
      });
  }

  ngOnDestroy() {
    this.destroyed$.next(true);
    this.destroyed$.complete();
  }
}

This works!
But I'd rather not since as you can see I have to write another observable (this.destroyed$) and manage that subscription myself rather than let Angular take care of this all via the async pipe.
Comment: Hmm, it might not be possible to use fakeAsync with the async pipe: https://stackoverflow.com/questions/44821512/angular-testing-async-pipe-does-not-trigger-the-observable
Comment: Does this answer your question? [Angular testing async pipe does not trigger the observable](https://stackoverflow.com/questions/44821512/angular-testing-async-pipe-does-not-trigger-the-observable)
Comment: I've tried the examples in that post, but that's not working. The subscription needs to happen somehow.
Comment: Can't you subscribe to showMe$ in the test and put the expectation in the subscription?
Answer: I've always had trouble with fakeAsync, so when it comes to testing observables, I like to follow this pattern:
it('Observable should do something', (done) => {
  // Arrange
  const mockObservable = new Subject(); // you already have this part

  // Assert (weird huh? it's just to handle the async logic)
  mockObservable.subscribe(() => {
    expect(...);
    done();
  );

  // Act
  mockObservable.next('mockValue');
});

Of course you can add pipe(last())... and everything when you subscribe to your mock obsevable as well.
I hope it helps! And I agree, if your scenario does not require BehaviorSubject , don't force it. It will cause you more headaches than satisfactions.


Unit norm eigenvectors of a symmetric matrix

Question: I read the following in a paper and I have a hard time understanding it.

... unit norm eigenvector are at most defined upto a single sign flip and we have to choose the signs synchonously.

What does "unit norm eigenvectors are defined unto a single sign flip" mean?  Does it mean that "if $v_i$ is an eigenvector then $-v_i$ is also an eigenvector?
Answer: You're right: "if $v_i$ is an eigenvector then $−v_i$ is also an eigenvector".
Indeed, eigenvectors of a matrix $A$ are specified by
$$
A v_i = \lambda_i v_i
$$
with eigenvalues $\lambda_i$. So with any constant $c$, $c v_i$  also satisfies the equation.
It is usual to choose $c = d/|v_i|$ with $|d| = 1$ so you have unit norm eigenvectors. However, this still leaves you the choice of $d$  with $|d| = 1$. Not only can you choose $d = \pm 1$, but also complex values with norm 1, in case the solutions are not real.
Comment: There's something more. It is probably the case that all eigenvalues are distinct, so all eigenspaces are one dimensional. In a one dimensional real vector space there are only two vectors of norm $1$.


Defining a method for a struct only when a field is a certain enum variant?

Question: I have the following struct:
#[derive(Debug)]
pub struct Entry {
    pub index: usize,
    pub name: String,
    pub filename_offset: u64,
    pub entry_type: EntryType,
}

#[derive(Debug)]
pub enum EntryType {
    File {
        file_offset: u64,
        length: usize,
    },

    Directory {
        parent_index: usize,
        next_index: usize,
    },
}

Entry is an entry in a GameCube ROM file system table which describes a file or directory. I defined various methods for Entry such as Entry::read_filename and Entry::write_to_disk. However, I have some methods that don't make sense to be available to both regular files and directories. For example, Entry::iter_contents iterates over all of a directory's child entries.
I want to be able to define certain methods such as Entry::iter_contents only for entries where entry_type is a certain variant.
I tried turning EntryType into a trait and made a DirectoryEntryInfo and FileEntryInfo struct, which both implemented EntryType.
Sadly, there were some problems with this approach. I have a Vec<Entry> elsewhere and with this change it would become Vec<Entry<EntryType>>. Using a trait like this, I have no way to downcast Entry<EntryList> to Entry<DirectoryEntryInfo>. I also tried doing something with Any, as that is the only way I am aware of to downcast in Rust, but I was only able to cast entry_type, not the entire Entry itself.
Ultimately, I'd like to end up with something similar to this:
impl<T: EntryType> Entry<T> {
    pub fn as_dir(&self) -> Option<Entry<DirectoryEntryInfo>> { ... }
    pub fn as_file(&self) -> Option<Entry<FileEntryInfo>> { ... }
    ...
}

impl Entry<DirectoryEntryInfo> {
    ...
}

impl Entry<FileEntryInfo> {
    ...
}

This way, I could access all of the entries fields without knowing whether or not it's a directory or file, as well as be able to cast it to a type that would provide me with all of the Entry fields in addition to methods based on the type parameter like Entry::iter_contents.
Is there a good way to do this without something like RFC 1450?
I'm aware that enum variants are not their own types and cannot be used as type parameters. I am just looking for an alternate way to conditionally define a method for a struct and still be able to have a way to store any variant of this struct in something like a Vec. This article is extremely close to what I am trying to do. However, using the example from it, there is no way to store a MyEnum<Bool> without knowing whether that Bool is True or False at compile time. Being able to downcast something like MyEnum<Box<Bool>> to MyEnum<False> would fix this, but I'm not aware of anything like that in Rust.
Comment: No; enum variants are not their own types thus they cannot participate in the type system. See also [Can struct-like enums be used as types?](https://stackoverflow.com/q/29935878/155423)
Comment: @Shepmaster Is there another way without enums to accomplish what I've tried to do? I mentioned making `EntryType` a trait, and trying to use two structs which both implement `EntryType`. However I ran into issues there because I couldn't downcast `Entry` into `EntryType` or `EntryType`. I'm not set on using enums, I'm open to anything that'll get the kind of behavior I mentioned in the question.
Comment: @Shepmaster I'm aware enum variants are not their own type, I should have been more specific. I'm just looking for a way to do something similar as a workaround, regardless of whether it involves enums or not.
Comment: I wrote an answer based on `enum`, but there's a downcasting solution too, using `Box`, if you make `EntryType` require `Any`. [I wrote this too, which may help.](https://stackoverflow.com/a/47642317/3650362)
Comment: Thanks! I'm gonna try out both of those, but I have a feeling the `enum` based one will be best for my use case.
Comment: @trentcl it's probably worth putting that into your answer (or even a second answer if you feel they are different enough). Comments are ephemeral and useful solutions shouldn't be lost.
Comment: @Shepmaster well, I gave it a shot, but [the solution I came up with using `Box`](https://play.rust-lang.org/?gist=b5db46d5f8815d9d4bbcdde5a624905c&version=stable) is such an abomination that I think, on the whole, I'd rather not! (Anyone reading this may feel free to use it in their own answer, or as an example of what *not* to do.)
Comment: @trentcl sometimes an answer showing a poor solution and explaining why it is poor is useful too ;-)
Answer: Unfortunately, you can't do quite that, because (as mentioned in the question comments) enum variants are not types and information about the variant isn't available to the type system.
One possible approach is to "hoist" the enum to the outer layer and have each variant contain a struct that wraps the shared data:
struct EntryInfo {
    index: usize,
    name: String,
    filename_offset: u64,
}

pub struct FileEntry {
    info: EntryInfo,
    file_offset: u64,
    length: usize,
}

pub struct DirEntry {
    info: EntryInfo,
    parent_index: usize,
    next_index: usize,
}

pub enum Entry {
    File(FileEntry),
    Dir(DirEntry),
}

Then you can easily define as_file and as_dir along the following lines:
impl Entry {
    pub fn as_dir(&self) -> Option<&DirEntry> {
        match *self {
            Entry::Dir(ref d) => Some(d),
            _ => None,
        }
    }

    pub fn as_file(&self) -> Option<&FileEntry> {
        match *self {
            Entry::File(ref f) => Some(f),
            _ => None,
        }
    }
}

It's not ideal, because any code you would have written on Entry before now needs to defer to EntryInfo in the appropriate variant. One thing that can make things easier is writing a helper method to find the wrapped EntryInfo:
fn as_info(&self) -> &EntryInfo {
    match *self {
        Entry::Dir(ref d) => &d.info,
        Entry::File(ref f) => &f.info,
    }
}

Then you can use self.as_info() instead of self.info in the implementation of Entry.
Comment: Thanks, this worked great and is exactly what I needed!


Installing find spark in virtual environment

Question: I am using pyenv to create a virtual environment.
My pyenv packages are located under the project bio in /.pyenv/versions/bio/lib/python3.7/site-packages
I installed findspark using below
pip install findspark  #it was installed successfully.

I am able to see the below files in the packages directory.
findspark-1.4.2.dist-info
findspark.py

However, when I launch Jupyter notebook from the pyenv directory, I get an error message
import findspark
findspark.init()

ImportError: No module named findspark

Can you please help me understand why do we get this error despite the pip install being successful?
My which Jupyter returns the below path (both in terminal & in jupyter notebook)
`/home/abcd/.pyenv/shims/jupyter
Answer: Jupyter notebook does not get launched from within the virtualenv even though you activated the virtualenv in the terminal session.
If you import sys and print out sys.executable, you'll realise that the first value of the python executable isn't that of the virtualenv.
You need to add the python of the virtualenv as a kernel.
$ virtualenv -p python3 pysparkvenv
$ source pysparkvenv/bin/activate
(pysparkvenv) $ pip install findspark jupiter  # etc.

(pysparkvenv) $ python -m ipykernel install --user

(pysparkvenv) $ which python
/home/disciple/Desktop/sample/pysparkvenv/bin/python

# make the necessary change to the python path
(pysparkvenv) $ sudo /home/disciple/Desktop/sample/pysparkvenv/bin/python -m ipykernel install --name pysparkvenv

This will create a new kernel which will be available in the dropdown list.
You can check if the kernel was created like this
$ jupyter kernelspec list
Available kernels:
  python3        /home/disciple/.local/share/jupyter/kernels/python3
  pysparkvenv    /usr/local/share/jupyter/kernels/pysparkvenv

After this, you can launch jupyter notebook from anywhere and a new kernel will be available. Select this and you'll have all the modules you installed inside the virtualenv.
Comment: Hi, No, I am able to launch jupyter notebook that was installed in `virtualenv`
Comment: Because `findspark` is not installed in the global python. It is only installed in the environment.
Comment: The `python3` kernel is not the one from the env you created. So it won't have any of the modules you install inside the env
Comment: You can either install everything globally, which I don't think you want to do since you're using pipenv. Or install another kernel for that particular env.
Comment: Sorry, I have installed `pyspark`, `jupyter notebook`, `find spark` everything installed in virtual env and no am trying to use usual import command in `import findspark` in jupyter
Comment: You can give it a try and launch the notebook with the pyspark kernel and see if it solves your problem.


finding A using with restriction $1 \leq a \leq 20$ in GCD

Question: For what $1 \leq a \leq 20$ you are finding $a$ is it true that $a^m+a^n=x^2$ for positive integers $a,m,n,x.$
I did
$a^m+a^n=x^2.$
$=a^m(a^{n-m}+1)=x^2$
We know that since $(a,b)=1$ since the GCD is $1,$ we can say
$= (a^m,a^k+1)=1$
I know that $a^m$ is prime which is the only factor of $a.$ $a$ is not in the factor for $a^k+1.$
I am not sure how you would solve this problem with this. Can someone help me with this?
Comment: Since the $\gcd$ is 1, you can conclude that either $a$ is a square or $m$ is even; additionally, $a^k+1$ must be a square.
Comment: @rogerl I know that $a^m$ is prime which is the only factor of $a.$ $a$ is not in the factor for $a^k+1.$
Comment: @rogerl how would I write this out though. Can you show me?
Answer: Since $\gcd(a^m, a^k+1) = 1$, both $a^m$ and $a^k+1$ must be squares.
If $k=1$, then given $1\le a\le 20$ we must have $a\in\{3,8,15\}$. Since none of these possible values of $a$ is itself a square, we must have $m=2r$ even, so we get the three families of solutions

$3^{2r}+3^{2r+1} = (2\cdot 3^r)^2$
$15^{2r}+15^{2r+1} = (4\cdot 15^r)^2$.
$8^{2r}+8^{2r+1} = (3\cdot 8^r)^2$.

Alternatively, if $k>1$ then using Catalan's conjecture, we see that we must have $a=2$, $k=3$, and $a^k+1 = 9$. Since $a^m = 2^m$ must be a square, we must have $m$ even. So the only solutions in this case are given by $a=2$, $m=2r$ even, $n = m+3$:

$2^{2r} + 2^{2r+3} = (3\cdot 2^r)^2$.

Finally, note that the solutions for $a=8$ are a subset of those for $a=2$, so you end up with just three families of solutions, for $a=2$, $a=3$, and $a=15$.


How to edit MS Word .xsl style documents to remove parens

Question: I'm using Word 2017 and need to remove parentheses from my citations so instead of looking like "(Author, YYYY)" they look like "Author, YYYY". It's a book manuscript, so lots of citations, so I need something global. I don't want to do any of this manually.
My web search led me to these instructions which describe editing the APA.xsl file, which looks like exactly what I need. The Word 2017 equivalent appears to be APASixthEditionOfficeOnline.xsl. I made the edits in the link but my changes aren't having any affect. The file is in "..\Office16\Bibliography\Style" which I think is correct. As a test, I removed all of the .xsl files out of this folder and it didn't seem to have any affect, so I'm not surprised my edits aren't taking. I'm at a bit of a loss, so any advice is welcome.
Answer: Found my main problem. This site suggested I was editing the wrong files, and should be working in
 C:\Users\***\AppData\Roaming\Microsoft\Bibliography\Style\, where *** is your user name

The only other tweak was described here that MS Word 2013 onward uses StyleNameLocalized instead of StyleName (the original link I posted was great, but a bit out of date.)
Summarizing, the main steps for removing brackets in Word 2013+ is

Copy and rename the .xsl file (to preserve the original) in your C:\Users\ ... \Style folder
Search for the StyleNameLocalized tags and edit their values (there's lots, but you can just find the one you use).

E.g.,
<xsl:when test="b:StyleNameLocalized/b:Lcid='1033'">
    <xsl:text>APA</xsl:text>
</xsl:when>

becomes
<xsl:when test="b:StyleNameLocalized/b:Lcid='1033'">
    <xsl:text>APA No Brackets</xsl:text>
</xsl:when>

Per the original link, find and remove the two blocks that add the brackets:

open bracket block:
<xsl:if
test="msxsl:node-set($ListPopulatedWithMain)/b:Citation/b:FirstAuthor">
<xsl:call-template name="templ_prop_OpenBracket"/>
</xsl:if>

closed bracket block:
<xsl:if test="/b:Citation/b:LastAuthor">
<xsl:call-template name="templ_prop_CloseBracket"/>
</xsl:if>

You can then select the entire document and apply the new citation style


Let $f:\mathbb{R}\rightarrow\mathbb{R}$ be differentiable. If there is an $L < 1$ such that for any $ x\in \mathbb{R}$ we have...

Question: Let $f:\mathbb{R}\rightarrow\mathbb{R}$ be differentiable.
If there is an $L < 1$ such that for any $ x\in \mathbb{R}$ we have $f'(x) < L$, then there exists a unique $x$ such that $f(x) = x$
Attempt: Let $P(x) = f(x) - x$. we have $P'(x) = f'(x) - 1 < L - 1 < 0$. thus $P$ is strictly decreasing. this proves that if there is a point $x$ such that $P(x) = 0$, then it must be unique. And that's pretty much all I got.
If I could prove that $P$ is positive for some numbers and negative for others, then by the IVT, $P$  would have a zero, but after trying for a while, I think it's not the way to go because the hypothesis doesn't provide much information. So I tried proof by contradiction, but I couldn't find any contradiction. I have a feeling that there's something  i'm missing, maybe a theorem?.
Comment: @F. Conrad: No, because Banach's fixed-point theorem requires $|f'(x)|<L$; we may have $f'(x)$ very negative.
Comment: Its an application of the Banch fixed-point theorem. Note that $f'(x)<L<1$ implies the Lipschitz condition from the theorem by using the mean value theorem.
Comment: Oh, you are right! I was completely missing out on that detail.
Comment: Just to clarify the statement of the question, I assume "for any $x \in \Bbb R~f'(x) \lt L$" means that this condition holds for all $x \in \Bbb R$.  It could be read to mean as long as there is *any* $x \in \Bbb R$ satisfying the condition.
Answer: You're on the right track.  Here's a lemma you might find useful:
Suppose $\phi'(x)\leq-\alpha$ for all $x$.  Then: \begin{align*}
x>0&\Rightarrow\phi(x)\leq \phi(0)-\alpha x \\
x<0&\Rightarrow\phi(x)\geq \phi(0)-\alpha x
\end{align*}
This is proven by integration from $0$ to $x$.
Now note that if $-\alpha<0$, then $x\mapsto-\alpha x$ tends to $\pm\infty$ as $x\to\mp\infty$.  Can you show that $P$ does likewise?
Answer: Let $g(x)=x-f(x)$. Then $g'(x)=1-f'(x)>1-L$, so putting $K=1-L$, we have $K>0$ such that $g'(x)>K$ for all $x$. And we want to show that there exists a unique $x$ such that $g(x)=0$.
Uniqueness is a simple consequence of the Mean Value Theorem.
And for existence, we have $g(x)\to +\infty$ as $x\to +\infty$ and $g(x)\to-\infty$ as $x\to-\infty$, because if $x>0$ then $g(x)>g(0)+Kx$, and if $x<0$ then $g(x)<g(0)+Kx = g(0)-K|x|$.
So we can certainly find $u$ and $v$ such that $g(u)<0$ and $g(v)>0$. Then by the IVT there exists $x\in(u,v)$ such that $g(x)=0$.


Show that one column is a linear combination of the other two

Question: I have the following matrix B. I would like to show that column may be expressed as a linear combination of the other two.
The first step I did was row reduce, but I still do not see one column as a linear combination. Can anyone provide hints? Or is there is a systematic way to solve this kind of problem?
$$ \left[
\begin{array}{ccc}
  −1−3i&−8−10i&0−3i\\
  −7−3i&−4−9i&−3−2i\\
  11-3i& -16-12i&6-5i
\end{array}
\right] $$
In its RREF:
$$ \left[
\begin{array}{ccc}
  11−3i&16−12i&6-5i\\
  0&\frac{64}{13}-i\frac{190}{13}&\frac{96}{65}-i\frac{92}{65}\\
  0& 0&0
\end{array}
\right] $$
Comment: The fact that the matrix is rank-deficient already tells you that some column is a linear combination of the others. If you want to know specifics, you need to continue to RREF, as some answers explain.
Answer: Your reduced matrix is not in RREF yet.  If we really want the coefficients that give the third vector as a linear combination of the first two, we could continue your reduction to find that the RREF is
$$
\pmatrix{
1 & 0 & \frac{4001}{7730} - \frac{597}{7730}i\\
0 & 1 & \frac{218}{3865} + \frac{464}{3865}i\\
0&0&0
}.
$$
With that: if $x_1,x_2,x_3$ denote the columns of the original matrix, then we have
$$
x_3 = \left( \frac{4001}{7730} - \frac{597}{7730}i\right)x_1 +
\left( \frac{218}{3865} + \frac{464}{3865}i \right)x_2.
$$
Answer: Since $\det B=0$, one of the columns has to be a linear combination of the other two. This works for rows too.
Comment: But the problem was to prove that "one column is a linear combination of the other two" and my argument proves that. However, in this case, since no column is a multiple of another column, it happens that *any* column is a linear combination of the other two.
Comment: Right, I get that. I am unsure however as to which column is a linear combination of the other two.
Answer: Say $R_{jk}$ is the entry in tow $j$ and column $k$ of the RREF.
It's clear that there exists $a$ with $R_{23}=aR_{22}$. And this makes it clear that the third column is a linear combination of the first two; third coordinate is no problem, previous sentence does the second coordinate, and now since $R_{11}\ne0$ and the rest of the first column is zero you can subtract off a multiple of the first column to get $0$.
(Or, if $C_j$ is the $j$th column: We have $$C_3-aC_2=\begin{pmatrix}*\\0\\0\end{pmatrix},$$so the form of $C_1$ makes it clear that there exists  $b$ with $$C_3-aC_2-bC_1=0.)$$
Answer: Find out constants $c_1$ and $c_2$ such that
$a_{11}=c_1.a_{12}+c_2.a_{13}$
Now verify that the same constants are working for
$a_{i1}=c_1.a_{i2}+c_2.a_{i3}$, ($i=2,3$)


Azure function, Microsoft.WindowsAzure.Storage missing

Question: I had a working http triggered Azure function a year ago. Not anymore. I created new azure function (runtime ~4) and now I can not compile it in Azure editor. It says "[Error] run.csx(2,1): error CS0006: Metadata file 'Microsoft.WindowsAzure.Storage' could not be found".
It is simply geting list of files from my Azure BLOB storage. I am loosing my mind, I don't know what to cofigure, or how to change my code. Is Microsoft.WindowsAzure.Storage no loner supported?
I was wondering about lowering my runtime version, but it is grey-out (I can not change it).
I read this How to replace Microsoft.WindowsAzure.Storage with Microsoft.Azure.Storage.Blob But I trying #r "Azure.Storage.Blobs" have the same result
<code>#r "Newtonsoft.Json"
#r "Microsoft.WindowsAzure.Storage"

using System;
using System.Configuration;
using System.Net;
using System.Text;
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;

public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");

    string name = req.Query["name"];
    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
    dynamic data = JsonConvert.DeserializeObject(requestBody);
    name = name ?? data?.name;

string connectionString = "MY_CONNECTION_STRING";
var storageAccount = CloudStorageAccount.Parse(connectionString);

CloudBlobClient client = storageAccount.CreateCloudBlobClient();
string rootDirectoryName = name.Replace(" ", "");
CloudBlobContainer container = client.GetContainerReference("storage");
CloudBlobDirectory folder = container.GetDirectoryReference(rootDirectoryName);
CloudBlobDirectory modelFolder = folder.GetDirectoryReference("giftpics");

BlobResultSegment segment = await modelFolder.ListBlobsSegmentedAsync(null);
                    List<IListBlobItem> list = new List<IListBlobItem>();
                    list.AddRange(segment.Results);
                    while (segment.ContinuationToken != null)
                    {
                        segment = await container.ListBlobsSegmentedAsync(segment.ContinuationToken);
                        list.AddRange(segment.Results);
                    }
List<string> blobNames = list.OfType<CloudBlockBlob>().Select(b => b.Name.Replace(rootDirectoryName, "").Replace("giftpics", "").Replace("/", "")).ToList();

  string contents = JsonConvert.SerializeObject(blobNames);
     return new OkObjectResult(contents);
}
</code>
Answer: I struggled on this too.....I think I might have found a solution for it, not sure.  But try this, it might work:

Upload an empty function.proj in the Azure Portal (ie while in the 'Code + Test' view while editing your Azure Function)
Select the function.proj file (using the dropdown)
Manually enter (or copy/paste) your code into the function.proj.  You should have a screen that looks something like below at this point:

Save.  It should now be restoring packages and hopefully compile your code successfully.
Answer: Try changing your runtime to ~3.  This worked for me, but I am not a developer so I have no idea what any ramifications this might have.


In SQL Server I want to do a join only if a field meets a certain criteria

Question: I am not sure how to say this but say tbl1 is a large group of products and tbl2 has a bunch of accessories that will match up to the products. There are two id types: ID and PRODUCT. When tbl1.idtype=PRODUCT then there is usually another ID provided in tbl1 called subGroupID. I am trying to link them on ID, and if they happen to have a PRODUCT id, then link tbl2 id to tbl1 subGroup ID.
Select * from tbl1, tbl2
where tb1.idtype=tb2.idtype
and tbl1.id=tbl2.id

if tbl1.idtype=PRODUCT, then join on tbl1.subgroupID=tbl2.id, else don't try to do this join.

I suspect you should use a case when statement here, but I keep getting errors .
Comment: this might help https://stackoverflow.com/questions/10279116/conditional-join-different-tables
Comment: Thanks everyone, this is really what I am looking for. I apologize for my inability to pose my problem in a clearer way.
Answer: There are at least two ways to interpret this question. One way is that you want to see all PRODUCT types and you further want to join on the subgroupID field instead of the normal ID field.
select ...
from   tbl1
join   tbl2
  on   tbl2.idtype = tbl1.idtype
  and  tbl2.id = tbl1.subgroupID
where  tbl1.idtype = PRODUCT;

However, you could also be wanting to join in general and just use the alternate field for PRODUCTs.
select ...
from   tbl1
join   tbl2
  on   tbl2.idtype = tbl1.idtype
  and  tbl2.id = case when tbl1.idtype = PRODUCT
         then tbl1.subgroupID
         else tbl1.id
         end
where  ...;

Answer: What you describe looks like a N:M relationship or if you prefer a many to many relationship.  That means a product can have zero or many accessories and an accessory can fit zero or many products.  If so, you should use 3 tables : Product ProductsAccessories and Accessory.  Something like :
Product
  ProductId  PK
  Name
  ...

ProductsAccessories
  ProductsAccessoriesID  PK
  ProductId  FK
  AccessoryId FK

Accessory
  AccessoryId PK
  Name
  ...

That would be the best way to do it.
As for your question it is very hard to answer the way you asked it but I think you are looking for something like this :
SELECT * FROM
  tbl1
LEFT JOIN tbl2 ON
  tbl1.subgroupID = tbl2.subgroupID AND
  tbl1.idType = 'PRODUCT'

The key word you are probably looking for is LEFT JOIN.  It will keep in the result set the products that do not have accessories.


How do you create a test Stripe standard account that is in the "Complete" status?

Question: This is all in Test mode:
I've successfully created a standard connect account but it's restricted until the standard account accepts the TOS. The problem is that I created the account via the API and I don't have access (password) to login to the dashboard to accept the TOS. The account is in the rejected status until that happens. Further, I can't use oauth to connect my app because I can't login to the standard account.
I'm using this link to create an account link to link my connect platform.
Answer: Usually you don't need to do anything specific to that account and it just works in Test mode for all transactions. So trying to force it to be in a "complete" state is not really something you should try to do.
Overall though, you can create a new Standard Account, then use AccountLink to onboard that account as if you were an end user. You can do this in a separate browser or private browsing mode and sign up for the account, choose an email/password and provide all the information you would be expected to provide if you were really onboarding. You could do the same thing in Live mode with Live API keys too if you wanted to get a real account fully onboarded.
As a developer, I have my own Stripe account for my platform and I have multiple separate Stripe accounts connected to my platform (either via OAuth or onboarded as described above). That allows me to test various situations such as having connected accounts in different countries or with different settings. And each account has its own email pattern like email@example.com versus firstname.lastname@example.com and such for me to easily switch between various situations.


How to automatically insert factoryid and categoryid into a table when submitting form - codeigniter

Question: I am using 3 tables for joining.
I have a form where i can add a factory. I also can choose a category for that specific factory.
i use the following tables:
factorycategories
-----------------
idfactorycategories
idfactories
idcategories
(in this table i use a join to show the categories and factories on one page)

factories
---------
idfactories
factoryname
address
country
telephone
...
...

categories
----------
idcategories
category

I want to insert the last inserted idcategories and idfactories in my factorycategories table.
How can i do this?
My model for inserting the form values:
function addbedrijf()
{
    $data1 = array(
       'Bedrijfsnaam' => $this->input->post('Bedrijfsnaam'),
       'Postcode' => $this->input->post('Postcode'),
       'Plaats' => $this->input->post('Plaats'),
       'Telefoonnummer' => $this->input->post('Telefoonnummer'),
       'Email' => $this->input->post('Email'),
       'Website' => $this->input->post('Website'),
       'Profiel' => $this->input->post('Profiel'),
       'Adres' => $this->input->post('Adres'),
       'logo' => $this->input->post('logo')
    );
    $this->db->insert('bedrijven', $data1);
}

My model function for showing categories and factories on the same page:
function get_result($idbedrijven)
{
    $this->db->where('bedrijven.idbedrijven', $idbedrijven);
    $this->db->join('bedrijven', 'bedrijfcategorieen.idbedrijven = bedrijven.idbedrijven');
    $this->db->join('categorieen', 'bedrijfcategorieen.idcategorieen = categorieen.idcategorieen');
    $this->db->group_by('Categorie', 'idbedrijven', 'idcategorieen');
    $result = $this->db->get('bedrijfcategorieen', 1);
    return $result->result();
}

Hope i provided enough code for you guys.
Edit:
the code that i have so far using the example below:
function addbedrijf()
{
    $data1 = array(
       'Bedrijfsnaam' => $this->input->post('Bedrijfsnaam'),
       'Postcode' => $this->input->post('Postcode'),
       'Plaats' => $this->input->post('Plaats'),
       'Telefoonnummer' => $this->input->post('Telefoonnummer'),
       'Email' => $this->input->post('Email'),
       'Website' => $this->input->post('Website'),
       'Profiel' => $this->input->post('Profiel'),
       'Adres' => $this->input->post('Adres'),
       'logo' => $this->input->post('logo')
    );
    $this->db->insert('bedrijven',$data1);

    if($this->db->affected_rows() >= 1)
    {
    $this->insert_bedrijfcat($this->db->insert_id);
    }else{
    return FALSE
    }
}

function insert_bedrijfcat($id)
{
    $this->db->insert('bedrijfcategorieen',array('idbedrijven'=>$id));

    return $this->db->affected_rows() ?= 1 ? TRUE : FALSE;
}

Answer: You are inserting data to the bedrijven table
and you want to get the last inserted id of
categories and factories table then insert it to factorycategories table also?
THe question is when inserting data to bedrijven table do you insert data to the
categories and factories table ? Because if you do you can use $this->db->insert_id to get the last input id of your categories and factories table, if not you need to query a different sql to get both last input id.
EDIT
here so i modified a some code example
class Some_model Extends CI_Model
{
   public function insert_factory($data)
   {
      $this->db->insert('factory_table',$data);

      //if has affected rows
      if($this->db->affected_rows() >= 1)
      {
        // the insert was successfull send the last insert id to another method
        $this->insert_to_factorycateg($this->db->insert_id);
      }else{
         return FALSE
     }
   }

   //method to insert to factorycateg
   public function insert_to_factorycateg($id)
   {
       //insert
      $this->db->insert('factorycategories',array('factoryid'=>$id));

      //if affected rows return true else false
      return $this->db->affected_rows() >= 1 ? TRUE : FALSE;
   }
}

Comment: yes i have a form where i add factories to the database. i still need to make the function for choosing a category. but i just want to, when i add a factory. that the id of that factory is automatically added to the factorycategories table.
Comment: you can use `this->db->insert_id` as stated a while ago, you can also use it when inserting to the category just by creating another variable to hold it or array.
Comment: could you give an example? i'm still a bit new to codeigntier and i searched on google fort insert_id but could not figure out.
Comment: do i have to specify this in my controller too? because i am getting a server error.
Comment: i just get an server error. so that's likely an fatal php error. i can't see what the error is.
Comment: added my code i have so far (note: i've changed some names to match my tables)
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/28959/discussion-between-tomexsans-and-kees-sonnema)


Transferir todos os arquivos de um diretório

Question: Tenho uma aplicação que transferi arquivos via socket, porém de um em um.
Preciso que essa aplicação transfira um diretório inteiro.
Devo fornecer um diretório, EX: "c:\users\Servidor\PASTA_DOWNLOAD"
e então o programa deve transferir via socket todos os arquivos contidos nesse diretório, alguém pode me dar algumas informações sobre como eu devo proceder?
Comment: Assumindo que o teu código está estruturado, uma ideia para resolver o problema passa por: 1) Ler os nomes dos ficheiros nesse directorio; 2) executar o codigo que já tens num ciclo para processar cada um dos ficheiros lido no passo 1)
Answer: Tenho um projeto com algo parecido com o que você quer, da uma olhada
<code>  int HYPNOS_Remote_Manip::HYPNOS_FOLDER_DOWNLOAD(std::string dir_remote, Socket_Setup &socket_setup)
{
    HANDLE dir;
    WIN32_FIND_DATA file_data;

    if ((dir = FindFirstFile((dir_remote + "\\*").c_str(), &file_data)) == INVALID_HANDLE_VALUE)
        return 1; /* No files found */

    do
    {
        std::string file_name = file_data.cFileName;
        std::string full_file_name = dir_remote + "\\" + file_name;
        const bool is_directory = (file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;

        if (file_name[0] == '.')
            continue;

        if (is_directory)
            continue;

        if (file_name == "desktop.ini")
            continue;

        int iResult = send(socket_setup.ConnectSocket, file_name.c_str(), strlen(file_name.c_str()), 0);  // Meio obvio, aqui você envia o nome do arquivo para o servidor
        if (iResult == SOCKET_ERROR)
            break;
        else
            HYPNOS_FILE_DOWNLOAD(full_file_name, socket_setup); // aqui é a função onde você passa o diretório do arquivo em que será enviado para o servidor
    } while (FindNextFile(dir, &file_data));

    FindClose(dir);
    return 0;
}
</code>
Answer: De acordo com o formato do endereço do teu diretório, creio que você esta num sistema Windows. As bibliotecas para C++ para procura em diretório são: FindFirstFile e FindNextFile
Veja aqui um exemplo simplório de uma busca em um diretório:
<code>HANDLE hArquivo;
WIN32_FIND_DATA arquivo;

hArquivo = FindFirstFile("c:\\users\\Servidor\\PASTA_DOWNLOAD\\*", &arquivo);

if ( hFile )
{
    do
    {
        String strNomeDoArquivo = arquivo.cFileName

        //Lance teu código de cópia aqui

    }while (FindNextFile(hArquivo, &arquivo) != 0)

    CloseHandle(hArquivo)
}
</code>
Vale lembrar que este código não seria portável para outros tipos de SO.
Fonte: Microsoft


How to export Unity to Android Studio with ARM v8 support?

Question: I tried setting IL2CPP as the builder and exporting but it only exports the x86 and ARM v7 native libs. Is it possible to export a Unity 5.3 project as an Android Studio project with ARM v8 jni libs bundled?
Answer: No, it is not possible for export a Unity project for ARMv8 on Android now. This is something that will be added in the future, but we're not sure when yet. For now, only 32-bit is supported.
Comment: Expanding a bit: Unity does not provide armv8 native libraries at the moment, that's why they don't get exported :)
Comment: Is it not possible even with the new IL2CPP compiler?
Comment: Yes, it is possible, as IL2CPP generates C++ code that can be compiled for any architecture. However, there are a number of other considerations. ARMv8 will likely be supported for Android at some point though.


Proving two random variables are uncorrelated but not independent

Question: I'm trying to find two random variables that are not independent -
there exist $a$ and $b$ such that $P(X=a \land Y=b)\neq P(X=a)P(Y=b)$
but, $\mathbb{E}[XY]=\mathbb{E}[X] \mathbb{E}[Y]$
I'm trying to understand some of the examples of this that I have seen, but they almost always define two random variables $X$ and $Y$ either in terms of each other, or in terms of a third random variable. This seems to be at odds with the formal definition of a random variable that I am accustomed to. That is, if we have a probability space $(\Omega,P)$, then a random variable $X$ is a mapping $X:\Omega \rightarrow \mathbb{R}$ (or some other space, but let's use $\mathbb{R}$ for simplicity).
So to say something like $\Omega=\{-1,0,1\}$ $P$ is uniform, $X(a)=a$ for all  $a\in\Omega$ and $Y=X^{2}$ doesn't seem like an example, since $Y$ does not formally meet the definition of a random variable.
I'm also unsure of what values I would even sum over in computing $\mathbb{E}[XY]$ for this case. any help would be great.
Comment: Why is $Y^2$ not a random variable? Also, when you write $\mathbb{E}[X,Y]$ do you mean $\mathbb{E}[XY]$, i.e. the expectation of the product? Because that is how one would usually state uncorrelation: $\mathbb{E}[XY]=\mathbb{E}[X]\mathbb{E}[Y]$.
Comment: @Furrer yes, I fixed the expectation I had... I am asking why $Y$ is a random variable. Why is it okay to define random variables in terms of one another?
Comment: I have given the answer to that question below.
Comment: @Furrer, Right, I guess what I am asking is whether or not the value of $Y$ is determined by $X$ i.e. is $P(X=0,Y=1)=0$? If so, then how does$Y(\omega)$ as a function make any sense?
Comment: You are absolutely right. Thinking about $Y$ as a function in this manner is not very useful. If you learn about continuous random variables based on measure theory, you will notice that one usually does not consider the structure of $\Omega$ itself. It is in a sense given by the goddess of fortune. What we need to know is not which $\omega$'s result in a certain outcome of $X$, i.e. we do not need to know the exact structure of the mapping, we only need to know the probabilities of the outcome occurring i.e. the distribution of $X$.
Comment: @Furrer That makes a ton more sense. It helps a lot to think of it that way
Answer: Your example is fine. $Y$ is a random variable, because $Y$ is a mapping from the probability space to $\mathbb{R}$ given by $Y(\omega)=X^2(\omega)=\omega^2$ for $\omega\in\Omega$. Thus most of the examples you have seen hold.
Comment: One usually says that the correlation only is able to detect linear dependency between random variables. In this case $Y$ clearly depends on $X$ - but not in a linear way.

Also: A random variable is not just a mapping from $\Omega$ to say $\mathbb{R}$. It is a mapping from the probability space to say $\mathbb{R}$. As such it is not central to specify the mapping itself but the probabilities of the events attached to the random variable.  E.g. the example works the exactly same way if I use $\Omega = \{-2,0,2\}$.
Comment: But in this case, why would these two random variables not be independent? Can $X=1$ and $Y=0$? or must $Y$ also be 1?
Comment: Let us first assume in your example that $X$ is uniform on $\Omega$, i.e. each event is equally likely, that is $P(X=-1)=P(X=0)=P(X=1)$. Then  $\mathbb{E}[X]=0$ and $\mathbb{E}[XY]=\mathbb{E}[X^3] = 0$, such that the variables are uncorrelated (we don't even have to consider $\mathbb{E}[Y]$ - nice).
But they are not independent. As you suggest, take the events $(X=0)$ and $(Y=1)$. Then $P(X=0, Y=1)=P(X=0,X^2=1)=0$ while $P(X=0)P(Y=1)=1/3 \cdot P(X^2 = 1) = 1/3 \cdot 2/3 = 2/9$.
Comment: I appreciate the help.
Comment: I hope it helps. I messed up the communication by typing answers in two threads. Hope you can add it up - else keep asking.


How to play facebook in iframe using javascript?

Question: I tried to use javascript play facebook video from iframe but not work.
How can i do ?

click here to play

Comment: Please check this link https://stackoverflow.com/questions/26479957/facebook-embeded-video-with-iframe-not-working
Comment: @webmentor.com -  i not see any answer ?
Answer: You cant directly run a facebook video on the site you need to do an API request
Go through
https://developers.facebook.com/docs/plugins/embedded-video-player/


Draw abline outside of plot margins on one side only

Question: I'm working on an R plot that will be separated into two parts by a vertical line I'm creating with abline().I would like that abline to go over the boundaries of my plot on one side only.
I found this helpful post about setting par(xpd=). However, I could not figure out how to get this command make the line go over the plot border on one side only, as outlined in the screenshot below.

Is there a way to do this in base R? (Or do I have to rebuild the
whole thing in ggplot etc?)
I feel that the key might the differences between figure region,
device region, etc. but was unable to really determine the difference
between those. I looked at this
source
but at least for my plot those settings seem to amount to the same
thing - it would be cool if anyone had some help here as well!

Here's my approach:
plot(100, 100)
par(xpd=TRUE)
abline(v=70, lty=3)

And what I get / want:

Any  help is appreciated!
Answer: Use lines. Set limits of y as you want.
plot(100, 100)
par(xpd = TRUE)
lines(x = c(70,70), y = c(45, par('usr')[4]), lty = 2)
# par('usr') gives the 4 extremes of plot
# par('usr')[4] gives the extreme on top

Another option is to not mess with xpd and use axis instead. Use tck to define the length of line beyond the plot. tck = -0.25 means the length is one fourth of the plot height towards bottom.
plot(100, 100)
par(xpd = FALSE) #Only because we made TRUE above
abline(v = 70, lty = 2)
axis(1, at = 70, labels = NA, tck = -0.25, lty = 2)

Comment: this is a beautiful answer, thank you for your help!


flow from setup to teardown in robotium

Question: what is the flow of the program in robotium.I mean are  setup() and teardown() called for every testcase separately ??
option 1
setup()
TC01
teardown()
setup()
TC02
teardown()
or option2
setup()
TC01
TC02
TC03
teardown()
Answer: Setup is called before every test method and teardown is called after every test method.
So the answer is option 1.

flow from setup to teardown in robotium


How to fix this eloquent database query

Question: The codes below needs a lot of rework. I wanted to DRY things up and add only paginate and sort if it is set in options. Do you have any recommendations to fix this?
I have tried doing a manual pagination, but it returns an array instead of an object so my index page breaks.
UserController:
// Search term

$src = Request::get('src');

$sort_by = Request::get('sort_by');
$sort_type = Request::get('sort');
$limit = Request::get('limit');

$users = $this->users->search(['email','username','status'], $src, ['paginate' => ['limit' => 5], 'sort' => ['by' => $sort_by, 'type' => $sort_type]]);

UserRepository:
public function search($fields, $search_term, $options = array())
{
    $users = NULL;

    if (is_array($fields))
    {
        // Check if the user wants to paginate it
        if (isset($options['paginate']))
        {
            $this->pagination_limit = $options['paginate']['limit'];

            $users = User::orWhere(function($query) use ($fields, $search_term) {
                foreach($fields as $field)
                {
                    $query->orWhere($field, 'LIKE', "%$search_term%");
                }
            })->paginate($this->pagination_limit);
        }
        // Return un-paginated result
        else
        {
            $users = User::orWhere(function($query) use ($fields, $search_term) {
                foreach($fields as $field)
                {
                    $query->orWhere($field, 'LIKE', "%$search_term%");
                }
            })->get();
        }
    }
    else
    {
        throw new \Exception('Fields must be an in the form of array.');
    }
}

Comment: What is $src ? Can you indent your code properly ?
Answer: The first thing I'd do is make a scopeSearch method on the User model which lets you just call $query->search($searchFor) anywhere - that'll save you a lot of lines of code. Read about scope method here. You could also do the same for sorting if you wanted.
The second thing I'd do, but this is just my opinion, is implement search, sort, paginate etc as chainable methods by making the repository a fluent interface. I found a good SO answer here explaining in depth how to make a fluent interface in PHP.
You don't have to implement a fluent interface, but I find it's good for achieving DRY, and the alternative of passing huge arrays (or even an object) of data with search terms, filters and sort parameters quickly gets messy.

How to fix this eloquent database query


Use of linear regression or logistic regression when testing conditioned group differences

Question: Background
I have a colleague interested in a particular disease and specifically if the continuous variable $X$ is different between controls and patients. Preliminary results suggest that patients have higher values of $X$ than controls.
The straightforward approach would be a unpaired t-test to test if there is a difference in mean values between patients and controls.
However, the literature suggests that age and sex are correlated with $X$ so my colleague wanted to control for this when testing. Hence, she decided to use regression to solve the problem.
Problem
My colleague's supervisor reasons that since they do not know if it is the disease that causes raised $X$ or if raised $X$ causes the disease they could use either linear regression or logistic regression to solve the problem. The supervisor also argued that logistic regression was the preferable approach.
If $d$ is a categorical variable with levels {control, disease} then the first model could be written
$$X = \beta_0 + \beta_1 d + \beta_2 \text{age} + \beta_2\text{sex} + \epsilon$$
Where the interpretation was that there is a correlation between disease and $X$ if $\beta_1$ was found significant.
and the second model
$$\log(\text{Odds}(d=\text{disease})) = \beta_0 + \beta_1 X  + \beta_2\text{age} + \beta_2\text{sex} + \epsilon$$
where the interpretation was that there is a correlation between disease and $X$ if $\beta_1$ was found significant.
What is the opinion among the experts on cross validated? Are there other methods?
comments
The patient and control groups were not perfectly matched and my colleague wants to make sure that she has controlled for both sex and age to avoid upsetting the reviewers.
I do not know if there were any significant differences between the sex and age distributions between patients and controls.
There were also indications that the variance in $X$ was different in the two groups and questions were asked if this would influence the regression models.
My personal opinion is that because my colleague is interested in the conditional expected value $E(X|d,\text{age},\text{sex})$ she should use the ordinary regression model or just a t-test (if there are no age or sex differences between groups).
Answer: I say you are right.  You should use OLS regression here, not logistic regression.
The question of causality is a red herring.  Causality is not required for either linear regression or logistic regression, and it is fine to model a cause as a (e.g., linear) function of an effect.  In fact, there are predictive models that do so.  As an example, researchers studying the collapse of the Mayan civilization have hypothesized that drought may have initiated its decline.  Predictive models have been built that allow researchers to make an educated guess about rainfall levels (i.e., causes) from traces that remain (i.e., effects; e.g., analyses of core samples from lake beds), to clarify this possibility.
Which variable should be made the response variable, and which the explanatory variable should be decided based on the question you want to answer.  It is clear from your setup that you are wondering about possible differences in the level of $X$ given the disease state.  Thus, $X$ should be the response variable, and disease state should be the explanatory variable.
Comment: In addition, given the covariates are covarying with X it's best that's it's the response variable and not a predictor.
Answer: I agree with your supervisor, logistic regression is the better choice. The continuous predictor allows you to make a more nuanced probabilistic statement about the disease relationship rather than the more blunt categorization statement of the relationship resulting from using disease as the predictor.
You did word your initial question about whether X was different between controls and patients but it isn't clear that future use of the information might better be served by being able to make statements about the probability of disease given the value of X. I'm trusting that your supervisor has better knowledge of the more general use of the findings and therefore would offer more appropriate advice than any of us can here.
It gets a bit tricky looking at your covariates of age and sex when they're primarily supposed to be related to X. My guess is they're related to both X and disease, in which case you really need to treat them not as covariates, that are generally ignored, but as fully analyzed predictors. You'll need to know the correlations among your predictors and how they influence your model.


GraphQL mutator with required args

Question: I am writing a mutation for a GraphQL schema:
const Schema = new GraphQLSchema({
  mutation: new GraphQLObjectType({
    name: 'Mutation',
    fields: () => ({
      person: {
        type: GraphQLString,
        args: {
          name: {type: GraphQLString},
          school: {type: GraphQLString},
        },
        resolve: mutatePerson,
      },
    }),
  }),
});

I want to ensure that mutatePerson will only work if both name and school arguments are present. How can I check that?
Answer: The GraphQLNonNull type wrapper is used to specify both fields and arguments as non-null. For fields, that means the value of the field in the query results cannot be null. For arguments, that means that the argument cannot be left out or have a value of null. So your code just needs to look more like this:
args: {
  name: {
    type: new GraphQLNonNull(GraphQLString),
  },
  school: {
    type: new GraphQLNonNull(GraphQLString),
  },
},

Comment: When I do this and then leave out the argument `name` I get an exception `Field "person" argument "name" of type "String!" is required but not provided`
Comment: Is that not the behavior you were trying to implement? If not, please clarify in your question what exact behavior you're trying to implement
Comment: I'd like an error response sent to the client, not just an error printed out to the console on the server side
Comment: That error will be returned to the client as part of the `errors` array in the response.  If you're not seeing that, we'd need to see more of your server-side code and know what kind of response the client *is* receiving when making the request
Comment: Ah, it was a problem with my error handling. Thank you!
Answer: it is better to do it as follow (in the model) if you want to reject empty Strings like "", it is different from Null, this way you can reject both Null and empty "".
const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const buinessSchema = new Schema({
  name: { type: String, required: true, unique: true },
  address: { type: String, required: true },
  phone: { type: String, required: true },
  email: { type: String, required: true },
  website: { type: String, required: true },
  currency: { type: String, required: true },
  aboutus: { type: String, required: true },
  terms: String,
  slogan: String,
  logo: { type: String, required: true }
});

module.exports = mongoose.model("Buiness", buinessSchema);

GraphQL mutator with required args


Capybara: fill_in: unable to find field

Question: Code: https://github.com/jmopr/job-hunter/blob/master/scraper.rb
So i'm running a scraper on indeed.com but it seems to be unable to find the field q, which is the first field on the left. I'm 100% certain that the code is correct but i'm not sure why it isn't able to view the form. save_and_open_page CONFIRMS that it was able to view indeed.com successfully... yet is unable to locate the form.
Code:
def perform_search
# For indeed0
save_and_open_page
fill_in 'q', :with => @skillset
fill_in 'l', :with => @region
find('#fj').click
sleep(1)
end

Indeed.com HTML:
<input class="input_text" maxlength="512" size="31" aria-labelledby="what_label_top hidden_colon what_label_bot" name="q" autocomplete="off" id="what">

Answer: Required portions/redirects of the page are loaded from 'indeed.com' rather than 'www.indeed.com' - Change your capybara-webkit configuration to allow indeed.com.
Additionally, if you want to know what the driver is actually seeing, you're generally better off using save_and_open_screenshot rather that save_and_open_page (The latter will show you the html structure but not how capybara-webkit has rendered it)
Comment: thank you. I figured it out on my own but stackoverflow doesn't let me post as often as I would like.

since you are here, i would like to ask you something. I've been getting inconsistent errors running the script, which makes debugging a real pain. Any idea why this happens? In one instance for example, the script fails to find the #fj (Find Jobs) button... but re-executing the script fixes the problem. Any idea what is happening? There are other inconsistent errors as well that are too long to fit in this comment section.
Comment: @AlannaMueller Glad you solved it, once you build up a small amount of reputation the rules relax.

Capybara: fill_in: unable to find field


Focus EditText Android

Question: Como faço para obter o foco num EditText mas continuo com problemas?
Estou fazendo um sistema de pedidos, tenho 3 EditText (produto, quantidade e desconto) e um botão Adicionar.
Eu preciso que quando o usuário clique no botão adicionar, o foco volte para o campo produto, hoje o foco esta indo para um editText do listView (itens do pedido) que acabou de ser adicionado.
Então se o usuário adiciona 30 produtos ele tem que ficar rolando a tela pra cima e colocar o foco no produto.
Estou usando Android 4.1
Código (no onclick do botão adicionar)
try{
    validaProdutoLista(item, pedido.getListaItemPedido());

    pedido.adicionaItens(item);

    listViewItensPedidos.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, pedido.getListaItemPedido().size() * 50));

    TabelaItensPedidoAdapter adapter = new TabelaItensPedidoAdapter(PedidoActivity.this, pedido.getListaItemPedido());
    listViewItensPedidos.setAdapter(adapter);
    adapter.notifyDataSetChanged();
    Log.i(TAG, "Itens add "+pedido.getListaItemPedido().size());

    codProduto.setText("");
    codProduto.requestFocus(); //voltar o foco para o produto
}catch (MyException e){
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Comment: @JorgeB. isso que é o ruim do Android, o que deveria funcionar as vezes não funciona dependendo da versão e do dispositivo... Talvez tenha que ver outra solução
Comment: tenta usar o request focus no xml
Comment: Se eu usar o requestFocus no xml, o foco ja vai para o campo logo que abre a tela, mas não é isso que eu preciso, preciso que só quando for adicionado um produto que o foco volte para o EditText produto.
Comment: Assim como estas a fazer deveria funcionar...
Comment: Alves tenta fazer `codProduto.clearFocus();` antes do `codProduto.requestFocus();`
Comment: então Jorge, não mudou nada, o foco sempre vai para o editText do listView que foi adicionado.
Comment: Se alguém tiver alguma outra ideia, será muito bem vinda..rs
Comment: Qual é o nome do *editText* da *listView* que está a receber o *focus*?
Comment: @AlvesFelipe Na linha com `codProduto.requestFocus();` mude para  `codProduto.requestFocus(FOCUS_UP, null);` e veja o que acontece. e tambem crie uma var do tipo boolean para ver se o codProduto.requestFocus esta retornando true ou false.
Comment: ramaral, o nome é itbProduto.
Comment: Olimon, não adiantou, o foco continua indo para o próximo campo, mas retorna true no codProduto.requestFocus
Answer: Acredito que não esteja funcionando porque você está setando o foco no momento em que você ainda está apertando o botão (você está mudando o foco dentro do on click).
Uma possível solução é usar um Handler. Você adiciona um atributo do tipo Handler na sua classe e no onclick você manda uma mensagem para o Handler.
Veja esse exemplo:
import android.os.Handler;
import android.os.Message;
...
final Handler myHandler = new Handler() {
    public void handleMessage(Message msg) {
        Log.i("HANDLER", "handleMessage::recebendo msg " + msg.what);
        codProduto.setText("");
        codProduto.requestFocus(); //voltar o foco para o produto
    }
};

Aí no onClick você faz, no lugar onde está a requisição do foco você manda uma mensagem para o Handler:
myHandler.sendEmptyMessage(0);

Comment: Seria interessante incluir a alternativa sem `Handler` usando  apenas `postRunnable` no próprio `EditText`.
Comment: Derzu, realmente é isso que acontece, eu criei um Handler e funcionou certinho.
Comment: Wakim, fiz como você sugeriu e também funcionou. Muito obrigado a todos pela ajuda!!

Focus EditText Android