Inverse of $2x + \cos{x}$

Question: Let $f(x) = 2x + \cos{x}$.

Calculate $f^{-1}(1)$;
Supposing that $f^{-1}$ is differentiable, show that $(f^{-1})^{\prime}(1) = \dfrac{1}{2}$.

Thanks for the help :]
Comment: Draw the graph on a graphic calculator to find $f^{-1}(1)$. For the derivative, use the formula for derivative of $f^{-1}$.
Comment: @MaadhavGupta It's not a duplicate. He's not asking for an explicit formula for the inverse.
Comment: see here i hope this will help you https://en.wikipedia.org/wiki/Inverse_functions_and_differentiation
Answer: We first need to confirm whether $f^{-1}(x)$ exists. To do so, we need to show it's a bijection. Let $x_1,x_2$ be such that
$$f(x_1)=f(x_2) , x_1 \ne x_2$$
Hence,
$$2x_1 + \cos x_1 = 2x_2 + \cos x_2$$
$$\implies \frac{\cos x_1 - \cos x_2}{x_1 - x_2} = -2$$
From LMVT, this is not possible , as the LHS must be $-\sin x$ for some point $x$, which must have absolute value less than $1$.
Hence, $f(x_1) = f(x_2) \implies x_1 = x_2$
Hence, function is invertible. Now that $f^{-1}(x)$ exists, we calculate it for x = 1. This is equivalent to solving the equation
$$2x + \cos x = 1$$
With a bit of rearrangement, we have
$$x = \sin ^{2} \frac{x}{2}$$
One solution is $x = 0$. Since it is a bijection, this must be the only solution. Hence, $f^{-1}(1) = 0$
For the second part, we use the fact that
$$f(f^{-1}(x)) = x$$
Differentiating both sides, and given that all required functions are differentiable, we have
$$f'(f^{-1}(x)) * (f^{-1})'(x) = 1$$
For $x = 1$, this returns
$$f'(0) * (f^{-1})'(1) = 1$$
$$\implies (f^{-1})'(1) = \frac{1}{2}$$

Inverse of $2x + \cos{x}$


Add exposed filter for user roles

Question: In Ubercart, the uc_order view (admin/structure/views/view/uc_orders) uses exposed filters for status and order ID.
I can add another filter, for example username, email and so on by clicking on Add filter criteria and selecting the criteria (user:username, user:email).
I need to add a filter to filter orders by the roles assigned to customers. There is no option such as user:roles in the filter criteria list to select.
How can I achieve this?
Answer: By configuring the Access: section on the Page settings, we can manage Page: Access restrictions.
Choose the Roles  and assign the required user role.
Comment: No, I don't want to restrict access to this page. I want to allow the administrator to filter orders by the selected customer roles. I need to add an exposed filter.
Comment: Using hooks you can alter the views.
Answer: The solution is to open "advanced" section, add new "relationship" marked as "order:customer". After this new options in "add filter" will be available. So click at "add filter" and select "user:role" and set it as "exposed to users".

Add exposed filter for user roles


adding Virtual PC 2007 to host network

Question: I am using Virtual PC 2007 with Windows xp Pro as the Guest.
Is it possible to add the Virtual PC to the network of the guest PC and to the domain of the Guest PC?
I enabled NAT shared networking but that only allows internet access on the guest..
Thanks
Answer: This shouldn't be a problem when you add the guest to host's physical adapter:
In the settings for your VM, go to Networking and instead of "Shared networking (NAT)", select the NIC that's connected to the network on your host (e.g. "Realtek RTL8116 Gigabit Ethernet", or whatever your NIC is; this is equivalent to VMWare's Bridged Mode). That way, the guest will appear as a real computer on your network, and will work like a physical box on the network.
IIRC, MS VPC bypasses the default Windows firewall on the host, so only the guest's firewall applies; for other FW products, you may need to enable something like "permit packets not destined for this host".
Comment: In settings-Networking, I can see only three options in the drop-down lists of options provided.
-Not Connected
-Local only
-NAT
The VirtualPC help file (.chm) also discusses such as option as mentioned by you,it is given in the help file under the heading -
"Managing network adapter availability for virtual machines"
but the "NIC-of-the-host" option isnt available somehow.

Thanks
Answer: Just to add to the above answer-
1.

Inside the Local Area Connection
  Properties- VM Network Services Driver
  wasnt installed without which the NIC
  option wont appear in the Virtual
  machine Network Adapter Configuration.
I reinstalled the Virtual PC and that
  entry Virtual Machine Network
  Driver appeared.

2.

Another helpful resource-

http://blogs.msdn.com/virtual_pc_guy/archive/2007/01/15/fixing-broken-virtual-networking.aspx
Answer: Shouldn't be a problem as long as you can connect to a domain controller from the virtual computer.
If you know the IP address of a domain controller, try to ping it. Then try to ping it using the computer name, to see if name resolution is working correctly. What happens when you join a domain using Control Panel | System. Do you receive an error message?
I have not used Virtual PC, only VMWare workstation on Linux, so I do not know how the networking setup is on Virtual PC. On VMWare, you can choose between bridged and NAT networking for a virtual machine. I have been able to set up Windows guest computers as members of a windows domain using both kinds of network setup.
Comment: trying to joing domain using My Computer - Computer Name - Change Name gives. Access is Denied.
This is the same process I followed to join my xp host to Domain but unable to join windows server 2003 guest (virtual pc2007).
Comment: Are you logged in as a user with administrative rights on the guest computer?

adding Virtual PC 2007 to host network


Matching new lines

Question: I have the following regexp:
pattern = re.compile(r"HESAID:|SHESAID:")

It's working correctly. I use it to split by multiple delimiters like this:
result = pattern.split(content)

What I want to add is verification so that the split does NOT happend unless HESAID: or SHESAID: are placed on new lines. This is not working:
pattern = re.compile(r"\nHESAID:\n|\nSHESAID:\n")

Please help.
Comment: You need to use multiline regex.
Answer: It would be helpful if you elaborated on how exactly it is not working, but I am guessing that the issue is that it does not match consecutive lines of HESAID/SHESAID.  You can fix this by using beginning and end of line anchors instead of actually putting \n in your regex:
pattern = re.compile(r'^HESAID:$|^SHESAID:$', re.MULTILINE)

The re.MULTILINE flag is necessary so that ^ and $ match at beginning and end of lines, instead of just the beginning and end of the string.
I would probably rewrite the regex as follows, the ? after the S makes it optional:
pattern = re.compile(r'^S?HESAID:$', re.MULTILINE)

Comment: @Droogans Yep! The hat looked ugly on the auto-generated box.

Matching new lines


Valence Role Settings

Question: I'm trying to retrieve the Course Access Options ("Access inactive courses", "Access past courses" and "Access future courses" specifically) of the roles within my instance of BrightSpace using Valence, and I haven't been able to figure out how.
I've looked at /d2l/api/lp/(version)/roles/, to no avail, and no other API called jumps out at me as being useful for this.
Is this just something that isn't currently possible to do with Valence?
Answer: Take a look at the Permissions routes. Since permissions are assigned to roles, there is a  route you can use to query permissions claims by tool, as well as a route that you can pass roles as parameters to limit to permissions available to that role. I haven't experimented with these myself yet, so I cannot
Comment: So unfortunately those only allow you to deal with permissions of the various roles.  The three values I'm looking for are settings, not permissions, and so none of those routes work (also they are listed as unstable so I'd rahter not sure them evne if they did provide me with what I needed).
Answer: Currently, the Brightspace APIs don't provide access to course-access settings for roles, as far as I know.

Valence Role Settings


Get the size of all .gz files in directory and subdirectories - python

Question: I am trying to loop over all the zipped files in a directory and keep it's size. I saw that I can do that without extracting it, but when I try to do so, I get an ERROR:
 " IOError: [Errno 2] No such file or directory:'first_gz_file.*.gz' "
When I am looking for it,I can find it, so I don't understand why do I get the error.
this is my code:
for directories in chosen_dirs:
    for root,dir,file in os.walk(directories):
        for o in file:
            if o.endswith('.gz'):
                print (o)
                input_file = gzip.open(o, 'rb')
                try:
                    print(input_file.size)
                finally:
                    input_file.close()

it does print the o files correctly (if I delete the lines below it)
What goes wrong there?
thank you
Comment: See the glob library http://docs.python.org/3/library/glob.html
Comment: `glob.glob` only looks in the specified directory, not its sub-directories.
Answer: Don't open the file use os.path.getsize(path)
As for what goes wrong a quick check shows that a gzip object doesn't have a size method:
>>> g = gzip.open('temp.gz', 'wb')
>>> dir(g)
['__abstractmethods__', '__class__', '__delattr__', '__doc__', '__enter__',
'__exit__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__',
'__metaclass__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_abc_cache',
'_abc_negative_cache', '_abc_negative_cache_version', '_abc_registry',
'_add_read_data', '_checkClosed', '_checkReadable', '_checkSeekable',
'_checkWritable', '_check_closed', '_init_read', '_init_write', '_read',
'_read_eof', '_read_gzip_header', '_unread', '_write_gzip_header', 'close',
'closed', 'detach', 'filename', 'fileno', 'flush', 'isatty', 'max_read_chunk',
'myfileobj', 'next', 'read', 'read1', 'readable', 'readinto', 'readline',
'readlines', 'rewind', 'seek', 'seekable', 'tell', 'truncate', 'writable',
'write', 'writelines']
>>>

I would add don't use file and dir as variable names as they are both reserved words in python that you might need to use in the original context they are both also lists in the context you are using them so use root, dirs, files or root, dir_list file_list for clarity.


Density of sum of two random variable

Question: I have a problem with a derivation of the density of the sum of nonnegative two random variables.
Suppose the joint density of nonnegative random variables $X,Y$ is $f_{X,Y}(x,y)$, a brutal force way to compute the density of $X+Y$ would be
$$  f_{X+Y}(a) = \frac{d}{da} \int_{x+y\leq a} f_{X,Y}(x,y) dy dx =  \frac{d}{da} \int_{\mathbb{R}_+} \int_{0}^{a-x} f_{X,Y}(x,y) dy dx .$$
If we allowed to exchange the sign of the  differentiation sign and the integral sign, we obtain
$$f_{X+Y} (a) = \int_{0}^{\infty} f_{X,Y}(x,a-x)dx.$$
So my question is why we can exchange the differentiation sign and the integral sign here. I did not see a simple dominant function so that we could apply the dominant convergence theorem. However, the last expression seems to be always correct by Fubini's  theorem.
Did I miss something obvious?
Answer: Moving the differentiation operator inside the integral is an application of the fundamental theorem of calculus.
$$\begin{align}\dfrac{\operatorname d ~~}{\operatorname d a}\int_b^c \dfrac{\operatorname d G(x,a)}{\operatorname d x\qquad\;}\operatorname d x ~=~& \dfrac{\operatorname d (G(c,a)-G(b,a))}{\operatorname d a\qquad\qquad\qquad\quad}\\[1ex] =~& \int_b^c \dfrac{\operatorname d^2 G(x,a)}{\operatorname d a~\operatorname d x\quad}\operatorname d x
\\[3ex] \dfrac{\operatorname d ~~}{\operatorname d a}\int_b^c g(x,a)\operatorname d x ~=~& \int_b^c \dfrac{\operatorname d g(x,a)}{\operatorname d a\qquad}\operatorname d x
\\[4ex]\therefore\qquad \dfrac{\operatorname d ~~}{\operatorname d a}\int_{0}^{\infty}\color{silver}{\left(\color{black}{ \int_{0}^{a-x} f(x,y)\operatorname d y}\right)}\operatorname d x~=~& \int_{0}^{\infty} \dfrac{\operatorname d ~~}{\operatorname d a}\color{silver}{\left(\color{black}{ \int_{0}^{a-x} f(x,y)\operatorname d y}\right)}\operatorname d x\end{align}$$
The next step follows from similar reasoning, except this time the derivation variable occurs in the bounds of the (inner) integral.
Comment: Hi Graham, thank you for your post. I think another issue on the last line is that what if $c = \infty$. There is still an exchange of limit that needs to be justified which is $\frac{d}{da}(\lim_{c \rightarrow \infty} G(c,a)) = \lim_{c\rightarrow \infty} \frac{d G(c,a)}{da}$.

Density of sum of two random variable


How do I modify the CSS in webform?

Question: I made a booking form using Webform. How do I modify the CSS?
Where do I find the CSS file of the webform?
The CSS files in Drupal look nothing like in Vanilla CSS. I'm bit lost there.
I would just like to reduce the width of my rows or change how the date-picker looks like. Or to display my rows in two columns.
I don't want to touch the PHP files too much either, hence why I found the answers about this topic on this forum not satisfying.
Comment: It's best practice not to edit module CSS files, such as webform's css. Instead just override the same CSS selector in your theme's CSS file.
Answer: You'll find the .css files in your theme directory, usually sites/all/themes/THEME_NAME/css.
To see easily in which line of which css file is the rule you'd like to change, you can go to admin/config/development/performance and un-tick Aggregate and compress css files checkbox.
Then with Firebug or similar development tool you'll be able to explore the css.
Check also if there's a sass or less folder in the same directory. In that case, you would have to edit the relevant scss/less files instead of the css ones, and make sure your editor is well configured to compile them to css.
You can explore scss files with the help of FireCompass addd-on and less ones with FireLESS.
EDIT
As underlined by Beebee comment, if the css you'd like to override are into a module css file, such as webform's css, don't edit that file, but override it in your own theme's css file.
Comment: Thanks. What's the usual path for the theme's css file?
Comment: It depends on your setup, but usually as said in the answer : `sites/all/themes/THEME_NAME/css`. Or maybe `sites/all/themes/contrib/THEME_NAME/css` , `sites/all/themes/custom/THEME_NAME/css` or if you installed a distribution `profiles/DISTRO_NAME/themes/contrib/THEME_NAME/css` and so on ... Just check the site folders, or using Firebug in Firefox, when you hover the css file name on the right of each rule, you can see its full path

How do I modify the CSS in webform?


Test for significance with multivariate, highly-skewed, discrete data

Question: The data
The dataset comprises 10 variables: waiting times (rounded to minutes) for questions to be answered on Stack Overflow by programming language. Each is discrete, none is normally distributed and all are different in size. The conditional means and variances indicate significant over-dispersion.
The aim
Following some survival analysis around probabilities I want to determine if the differences in waiting times between the languages are significant. Having researched the non-applicability of $t$-tests and Wilcoxon-Mann-Whitney tests for discrete data, and explored some of the sensitivities around sample sizes and degrees of skew, I'm at a loss trying to find the most appropriate method.
I experimented with a Negative Binomial regression using the language with the quickest answer time, c++, as the dependent variable. Results below. The idea came from this paper which advises using Poisson or Negative Binomial regression  with discrete and/or highly skewed data. However, as I have 9 independent variables I'm unsure of the appropriateness of these results as measures of significance.
Positively, the coefficients match the intuition I developed through EDA.
<code>                         Generalized Linear Model Regression Results
==============================================================================
Dep. Variable:             c_plusplus   No. Observations:                25021
Model:                            GLM   Df Residuals:                    25011
Model Family:        NegativeBinomial   Df Model:                            9
Link Function:                    log   Scale:                  0.129917576134
Method:                          IRLS   Log-Likelihood:                    nan
Date:                Mon, 12 Oct 2015   Deviance:                          nan
Time:                        20:13:29   Pearson chi2:                 3.25e+03
No. Iterations:                    20
==============================================================================
                 coef    std err          z      P>|z|      [95.0% Conf. Int.]
------------------------------------------------------------------------------
Intercept      2.0341      0.008    265.033      0.000         2.019     2.049
aspunet      -13.8595      6.856     -2.022      0.043       -27.296    -0.423
c_sharp      -14.7241      5.542     -2.657      0.008       -25.586    -3.863
iphone       -12.0858      7.266     -1.663      0.096       -26.327     2.155
java         -14.0126      6.347     -2.208      0.027       -26.452    -1.573
javascript   -14.4314      9.903     -1.457      0.145       -33.842     4.979
jquery       -13.8768      9.744     -1.424      0.154       -32.975     5.221
php          -14.3465      8.592     -1.670      0.095       -31.187     2.494
python       -13.7037      7.712     -1.777      0.076       -28.818     1.411
unet         -14.4260      9.268     -1.556      0.120       -32.591     3.739
==============================================================================
</code>
The questions:

Can I use the coefficients and p-values from this regression model as measures of significance between the language answer times?
If not, what would be a better approach?
Answer: Waiting time should not be discrete. It's time, how can it be discrete? Even in quantum physics time is continuous. My first choice in modeling the waiting time would be exponential distribution. It's the same underlying process as Poisson. The latter gets number of occurrences in a given time period (discrete), the former is the time between occurrences (continuous) at given rate $\lambda$ of occurrences per unit of time.
What to do? I'd suggest instead of fixating on variances, to go after the distributions. Look at Kruskall-Wallis test, for instance. You could plug your data sets into the test, and it'll test whether they come from the same distribution. Kolmogorov-Smirnov test can do a similar analysis.
Also, look at Mood's Median Test, which has different assumptions from KW test, particularly, it works better when variances are very different between samples.
Comment: @Jonathan, you're right that data is discrete, but it doesn't make it suitable for discrete distribution modeling. Your underlying process is not discrete, it's just the data precision makes it look discrete. However, this can be said about anything represented in computers or on paper. If you round to N digits, anything will become discrete, yet the underlying process is still continuous.
Comment: @Jonathan, I hope you'll share the results of your study somewhere. I'm curious to know if C++ questions are longer to answer than Java.
Comment: You're right, and I'm sorry, I should have explained the following in the question. The data are are rounded to minutes. The data can be counted and listed; thereby I think I'm right in saying the data are discrete. I've updated the question to reflect this.
Comment: I've read around the Kruskall-Wallis and Mood's Median tests. Pleasingly, both work perfectly. Thanks. You have taught me a lot today.


Get Element by Name/ID

Question: I am trying to automate logging into a website to run a report for our ticking system.
I am able to login and get into the system. However I am having an issue clicking the report button.
I have tried many many many variations however no success.
This is the HTML Code for the report button.

Report Bananna
I have tried
$ie.document.getElementsByName("tab_view4").submit()
$ie.document.getElementsByName("tab_view4").submit()
$ie.document.getElementsByName("tab_view4").click()
$ie.document.getElementsByID("tab_view4").click()

Answer: id and name are different attributes. To get an element with the id="tab_view4" use $ie.document.getElementById("tab_view4") (without "s" as IDs are supposed to be unique in an HTML document).
Comment: Nogo doing this..   Method invocation failed because [mshtml.HTMLDocumentClass] does not contain a method named 'getElementByName'.
At C:\Building EXE\In Dev\TechXL report\TECCHXL.PS1:46 char:1
+ $ie.document.getElementByName("tab_view4").click()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound
Comment: @JayCee360 Read again. Pay particular attention to the method name in my answer.
Comment: I am sorry I didnt clear the powershell ISE. It threw an error again. I am a newbie learning. :)    You cannot call a method on a null-valued expression.
At C:\Building EXE\In Dev\TechXL report\TECCHXL.PS1:46 char:1
+ $ie.document.getElementById("tab_view4").click()
Comment: @JayCee360 Then the document apparently doesn't contain an element with the ID `tab_view4`. Does the page consist of frames or contain iframes?
Comment: @JayCee360 That doesn't say anything about whether the *page* has frames/iframes or not. Also, please don't post code in comments. It becomes unreadable. Edit your question if you need to provide additional information. Also, it seems like it's the `` element having the ID `tab_view4`, but you need to click the nested anchor element.
Comment: @JayCee360 Addendum: it might be a good idea to check the output of `$ie.Document.body.innerHtml`. That should give you more information about the page structure.
Comment: I tweaked it to have the entire span. If you need the entire source then let me know.
Comment: @JayCee360 Like I said: check the value of `$ie.Document.body.innerHtml`.

Get Element by Name/ID


Prove that a linear operator $T$ on a finite-dimensional vector space is invertible if and only if zero is not an eigenvalue of $T$.

Question: (a) Prove that a linear operator $T$ on a finite-dimensional vector space is invertible if and only if zero is not an eigenvalue of $T$.
(b) Let $T$ be an invertible linear operator. Prove that a scalar $\lambda$ is an eigenvalue of $T$ if and only if $\lambda^{-1}$ is an eigenvalue of $T^{-1}$.
MY ATTEMPT
(a) Let us suppose that $\lambda = 0$ is an eigenvalue of $T$. Thus $\det([T]_{\mathcal{B}}) =\det([T]_{\mathcal{B}} - 0 I_{n}) = 0$, and $T$ is not invertible.
Conversely, let us suppose that $T$ is not invertible. Then $0 = \det([T]_{\mathcal{B}}) = \det([T]_{\mathcal{B}} - 0I_{n})$, and $0$ is an eigenvalue of $T$.
(b) Indeed, provided that $\lambda \neq 0$, one has
\begin{align*}
Tv = \lambda v \Rightarrow T^{-1}(Tv) = T^{-1}(\lambda v) \Rightarrow (T^{-1}T)v = \lambda(T^{-1}v) \Rightarrow T^{-1}v = \lambda^{-1}v
\end{align*}
Once again, I am mainly interested in the wording of my proof. Any comments or contributions are appreciated.
Comment: Looks good to me.
Comment: For part a) you can notice that the eigenspace relative to 0$0$ is nothing else that the kernel of your linear mapping $T$. So $T$ is invertibile iff $0$ is not an eigenvalue.
Answer: Your proofs are correct.
I would edit the second assertion to put the equations on separate lines separated by the implications, rather than running them all together.
I think that a proof that relies more directly on the concepts and avoids determinants would be better. If $0$ is an eigenvalue then there is a nonzero $v$ with $Tv=0$ so T is not injective, so it's not invertible. Conversely, if $T$ is not invertible then it's not bijective. For a linear transformation from a finite dimensional space to itself, bijective is equivalent to injective. But an noninjective linear transformation has a kernel, so has $0$ for an eigenvalue.


Using local variables with "apply" in Javascript

Question: Why "show" method is not able to access "text" variable here ?
// @constructor A
var A = function(){

    //alerts some text variable
    this.show = function(){
       alert("Hello")
       alert(text);
  }

}

//@constructor B
var B = function(){

  //local text variable
  var text = "World";
  A.apply(this); // "show" method will get attached to B
}

var obj = new B();

//now calling show of B's object.
obj.show(); //returns error.

//Expected output
alerts "Hello"
alerts "World"

//Actual output
alerts "Hello"
ReferenceError: text is not defined

Am I missing something here ?
Shouldn't the "text" variable be accessible to B's "show" method?
Answer: Unlike C++ or Java, Javascript doesn't have an implicit this.
If a function (like show) refers to this.foo, then only the value of this depends on how the function was called.
However, if show refers to a variable directly (like foo), then it can mean either:

a local variable, if it's defined using var at the function scope;
a variable from a closure, if the function is being defined inside another function that happens to define it with var (closure gets created at the moment of function definition),
a global variable otherwise.

In your case, the third case applies. show can't access text because it is defined in a totally unrelated scope.
Comment: Thanks for this .."show can't access text because it is defined in a totally unrelated scope."
Answer: You need to declare the text as property of B constructor  this.text = "World"; something like this.
var A = function(){

    //alerts some text variable
    this.show = function(){
       alert("Hello")
       alert(this.text);
  }

}

//@constructor B
var B = function(){

  //local text variable
   this.text = "World";
  A.apply(this); // "show" method will get attached to B
}

var obj = new B();

//now calling show of B's object.
obj.show(); //returns error.

Comment: Thanks Suman Bogati. But I know what the solution is, I was just willing to know why(this particular behavior) it was happening.


Alpha-numeric Telephone Keypad with Arduino

Question: I'm trying to make a capacitive touch keypad to take input from a user, and output a string of characters generated by this input. Each pad returns its value, with the first being 1, the second being 2, the third 4, 8, 16 up until 2^12. (If multiple keys are touched, their ids are added up, but this won't happen.)
Imagine you're using your old Nokia phone and typing a message to a friend, you press 2 twice for 'b' and 9 three times for 'y'. I need code for something like this.
My biggest hurdle is that I have very limited knowledge of C, and what I have done so far has gone well, with the occasional hiccup, however this is far beyond my knowledge.
Here's my current code, it's not pretty, but it's my current attempt at this.
//import all packages
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1351.h>
#include <Adafruit_MPR121.h>
#include <Adafruit_NeoPixel.h>
#include <SPI.h>
//define pins for OLED display
#define sclk SCK
#define mosi MOSI
#define dc   A1
#define cs   A2
#define rst  A3
//define pins for indicator lights
#define neo_pin A4
//define basic colours
#define BLACK           0x0000
#define BLUE            0x001F
#define RED             0xF800
#define GREEN           0x07E0
#define CYAN            0x07FF
#define MAGENTA         0xF81F
#define YELLOW          0xFFE0
#define WHITE           0xFFFF
//create the screen
Adafruit_SSD1351 screen = Adafruit_SSD1351(cs, dc, mosi, sclk, rst);
//create the cap. sensor
Adafruit_MPR121 cap = Adafruit_MPR121();
//initialize the variables used by the cap. sensor
uint16_t lastTouched = 0;
uint16_t currTouched = 0;
int delayPress = -1;
int buttonIndex = 0;
int padTouched = 0;
//create the neopixel indicator light
Adafruit_NeoPixel indicator = Adafruit_NeoPixel(1, neo_pin, NEO_GRB + NEO_KHZ800);
//initialize functional variables
char string[32];
//level 0 functions
void flash(int dly = 100)
{
  digitalWrite(13,HIGH);
  delay(dly);
  digitalWrite(13,LOW);
  delay(dly);
}
void flashIndicator(int dly = 100)
{
  setColour(255,255,255);
  delay(dly);
  setColour(0,0,0);
  delay(dly);
}
void setColour(int r, int g, int b)
{
  indicator.setPixelColor(0,r,g,b);
  indicator.show();
}
void resetDrawText(char *text,uint16_t textColour = WHITE, uint16_t backColour = BLACK)
{
  screen.fillScreen(backColour);
  screen.setCursor(0,0);
  screen.setTextColor(textColour);
  screen.print(text);
}
void drawText(char *text,uint16_t textColour = WHITE)
{
  screen.setCursor(0,0);
  screen.setTextColor(textColour);
  screen.print(text);
}

//component startup functions (level 1)
void startIndicator()
{
  indicator.begin();
  indicator.setBrightness(64);
  setColour(0,0,0);
  setColour(0,255,0);
}
void startCap()
{
  cap.begin(0x5A);
}
void startScreen()
{
  screen.begin();
  screen.fillScreen(BLACK);
}

void setup() {
  // start all components
  startIndicator();
  startCap();
  startScreen();
  Serial.begin(9600);
  Serial.println("init");
  setColour(255,0,255);
}

void keyIn()
{
  flashIndicator(100);
  flashIndicator(100);

  char catChar[] = " ";
  Serial.println("pad index");
  Serial.println(currTouched);
  switch (currTouched)
  {
    case 1:
    catChar[1] = "A";
    break;

    case 2:
    catChar[1] = "B";
    break;

    case 4:
    catChar[1] = "C";
    break;
  }
  //Serial.println("char group");
  //Serial.println(catGroup);

  //strcpy(catChar, catGroup);
  //char catChar = catGroup[buttonIndex];
  Serial.println("new char");
  Serial.println(catChar);

  strcat(string, catChar);
  drawText(string);
  Serial.println("draw text");
  Serial.println(string);
  delayPress = -1;
  buttonIndex = 0;
  padTouched = 0;
}

void loop() {
  currTouched = cap.touched();

  if ((currTouched > 0) and (not currTouched == lastTouched))
  {
    Serial.println("pad touched");
    Serial.println(currTouched);
    flashIndicator(200);
    if ((padTouched == currTouched) or (padTouched == 0))
    {
    delayPress = 50;

    buttonIndex++;
    if (buttonIndex > 2)
    {
        buttonIndex = 0;
    }
    Serial.println("button index");
    Serial.println(buttonIndex);
    }
    else if (not currTouched == 0)
    {
    keyIn();
    }
    padTouched = currTouched;
  }
  if (delayPress > 0)
  {
    delayPress--;
  }
  else if (delayPress == 0)
  {
    keyIn();
  }
  lastTouched = currTouched;

  flash(50);//delay(100);
}

Please feel free to ask for clarity, and if you do know the solution, please explain what each line and statement is doing so that I can gain some insight into the language.
Answer: This demonstrates the concept of alphanumeric keypad typing:
const int max_delay_between_keys = 300; // Time in milliseconds to allow between keypresses

String text = "";
char current_char = '\0';
int last_pressed = -1;
int times_pressed = 0;
int time_last_pressed = 0;

char lookup_value(int key, int count) {
    const char* const characters[12] = {"1", "abc2", "def3", "ghi4", "jkl5", "mno6", "pqrs7", "tuv8", "wxyz9", "*", "0 ", "#"}; //Change this to match the characters on your keypad.
    const char* sequence = characters[key];
    return sequence[count % strlen(sequence)];
}

String process_keystream(int key_code) {
    int new_time = millis();
    bool time_over = (new_time - time_last_pressed > max_delay_between_keys);

    time_last_pressed = new_time;

    key_code = log((float)key_code) / log(2.0) - 1;
    if (key_code == last_pressed && !time_over) {
        times_pressed += 1;
    }
    else {
        if (last_pressed != -1) {
            text += current_char;
        }

        last_pressed = key_code;
        times_pressed = 0;
    }
    current_char = lookup_value(key_code, times_pressed);

    return text + current_char;
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);

  // Serial.println() is what you'd send to your screen.
  Serial.println(process_keystream(16)); // Pressed the 4 key
  Serial.println(process_keystream(16)); // Pressed the 4 key
  Serial.println(process_keystream(8));  // Pressed the 3 key
  Serial.println(process_keystream(8));  // Pressed the 3 key
  Serial.println(process_keystream(32)); // Pressed the 5 key
  Serial.println(process_keystream(32)); // Pressed the 5 key
  Serial.println(process_keystream(32)); // Pressed the 5 key
  delay(500);                            // Wait a while so the current letter is set.
  Serial.println(process_keystream(32)); // Pressed the 5 key
  Serial.println(process_keystream(32)); // Pressed the 5 key
  Serial.println(process_keystream(32)); // Pressed the 5 key
  Serial.println(process_keystream(64)); // Pressed the 6 key
  Serial.println(process_keystream(64)); // Pressed the 6 key
  Serial.println(process_keystream(64)); // Pressed the 6 key
}

void loop() {
  // put your main code here, to run repeatedly:

}

Result:
g
h
hd
he
hej
hek
hel
helj
helk
hell
hellm
helln
hello

Comment: Thank you! just looked over the code and it makes much more sense than my mess xD.


Empirical variance of simulation estimate

Question: Consider the following quantity of interest:
$$I[a,b]=\int_{a}^{b}g(\theta)h(\theta), \ldots (1)$$
that is, the expected value of some function $h(\theta)$, of $\theta$ distributed $g(\theta)$.
Suppose the probability function $g(\theta)$ is difficult to express. A substitute for analytically calculating equation $(1)$ is to randomly generate $n$ values of $\theta$ from  $g(\theta)$ and calculate:
$$\hat I[a,b]=\frac{1}{n}\sum_{i=1}^{n}h(\theta_i).$$
The empirical variance of the Monte Carlo simulation estimate is
$$Var(\hat I[a,b])=\frac{1}{n(n-1)}\sum_{i=1}^{n}(h(\theta_i)-\hat I[a,b])^2 \ldots (2)$$
I am not understanding  why there is the factor $n(n-1)$ in the denominator of the empirical variance of equation $(2)$ rather than simply $(n-1)$? Why there is $n$ multiplied with $(n-1)$?
Comment: $I[a, b]$ is the expected value only if $supp(g)\subseteq [a,b]$.
Answer: You are probably confusing the estimator $\widehat{var(h)}$ for the variance with the variance $Var(\hat I)$ of the estimator $\hat I$ of the mean.
One popular estimator of the variance
$$
\widehat{var(h)} = \frac{1}{n-1} \sum_{i=1}^n(h_i - \hat I)^2
$$
contains, indeed, the factor $(n-1)$ in the denominator.
But, in general, the variance of the estimator of the mean $\mu_h$ of any random variable $h$ is $\frac{\sigma^2_h}{n}$. Thus, the source of your formula has chosen to take as estimator of the variance the estimator of the variance divided by $n$:
$$
\begin{align}
Var(\hat I) &= \frac{1}{n} \widehat{var(h)}\\
            &= \frac{1}{n(n-1)} \sum_{i=1}^n(h_i - \hat I)^2.
\end{align}
$$


Contour integrals and Cauchy's theorem

Question: 1) Let $C$ be a contour beginning and ending at 1. Suppose that $f(z)$ is analytic on $C$. Then is it true that the contour integral of $f$ around $C$ is 0?
This looks to be true by Cauchy's theorem but I'm not sure about the interior points part of the hypothesis
2) Let $C$ be a contour beginning and ending at 1 and containing numbers whose real part is positive. Then is it true that the integral of $\frac{1}{z^2+z}$ around $C$ is zero.
Answer: If all you have is that $f$ is differentiable on $C$, then $f$ could have singularities elsewhere, each of which would affect the integral of $f$ around $C$ if the winding number of $C$ around it is non-zero. Have you integrated $z \mapsto z^{-1}$ around the unit circle before? That is the most important integral because it tells you essentially what happens at any singularity since the integral is $0$ for all other integral powers.
Also, as you might have noticed, the conditions for Cauchy-Goursat theorem to hold is that the curve must be closed and rectifiable, and the function must be differentiable on a simply connected set that includes the curve. Can you see whether any of the conditions fail to hold for (2)?
Comment: So 1/z around the contour $e^{it}$ $(0{\geq}t{\leq}2{\pi})$ would be a counter example to the first?         As to the second, I'm not sure except there may be a probelm at zero.
Comment: Yes you're done with (1). Real part being positive means that $C$ cannot pass through $0$.
Comment: I think then all conditions hold and it is zero
Comment: @user137090: Yup correct. Note that you just need to make sure the denominator is non-zero on the open right-half plane (which is simply connected).

Contour integrals and Cauchy's theorem


Which statistical test : Anova or T-Test for between subject experiment (repeated measures ) with one IV with two levels( control and treatment)

Question: It's a between-subject design with a control group and a treatment group with 50 people each. Each participant undergoes 100 trails. (repeated measures). So the only within-subject factor is the number of trails. The independent variable is dummy coded (0 & 1). The dependent variable is continuous, it varies between [3.00 to 6.00]. I want to compare the means between the two. Should I use a repeated-measures ANOVA / mixed model / T-test/manova?
Which is a good approach and why?
I understand that, I can have a mixed model and find anova for that. Is this right?
Answer: Both an ANOVA and mixed modeling approach will work for your data. I am more familiar with mixed models, and can speak better to that. However, you are correct that you can run your analysis as a mixed model and then get an ANOVA table afterward. If you are using R, then you can use lmer to first estimate the mixed model:
require(lme4)
m <- lmer(outcome ~ trtmt + (1|Subject), data=df)

The above model will give you the mean outcome difference between treatment and non-treatment individuals while properly accounting for the correlated outcome scores from the same individual. If you wanted the ANOVA table based on this model, you can use anova(m) to get that.
It is worth noting that the mixed model, as with any statistical model, is only valid under certain assumptions, many of which are the same assumptions as regression. Among these are the normality of the residuals, which can be examined as such:
residm <- resid(m) #grab L1 residuals
qqnorm(residm) #graphing to check normality assumption

Also important with the residuals is the homogeneity of variance assumption, which you can inspect visually, looking for the absence of any pattern in the residual vs. fitted plot using plot(m).
Mixed models impose a normal distribution on the random intercepts, i.e., (1|Subject) in the lmer syntax above. You can look to see whether the predicted intercepts do a decent enough job of following a normal distribution using the following code: plot(ranef(m)).


Is it possible to add disks to an existing RAID 5 array?

Question: Suppose I have a RAID 5 array consisting of 4 disks. If I buy two new disks later, can I add them non-destructively to the existing RAID 5 array?
It could be a hardware RAID controller or Windows Server 2003 software RAID.
Comment: Per the [ServerFault FAQ](http://serverfault.com/faq#dontask), hypothetical questions are off-topic here.
Answer: Hardware RAID controller: Depends on the controller. Read the manual or check with the vendor. It's certainly possible.
Windows Software RAID: No
Answer: Well, here we go - it depends. "Could be a car or a truck" is not specific, and this dependes on specific models. Most PROPER hardware raid controllers allow that - some cheap ones do not.


Como faço para conseguir gerar o "apk" da minha aplicação IONIC

Question: Seguindo a documentação, deveria ser dois comandos simples:

Para incluir a plataforma: ionic platform ios android
Para compilar: ionic build android

Porém, estou recebendo um monte de erro em vermelho no terminal,
conforme a imagem abaixo:

Editado até aqui: Eu resolvi parte do problema, porém, estou com novos erros:

Seguindo as dicas, descompactei o Android JDK na pasta /usr/local.
E inclui no final do arquivo ~/.profile as linhas abaixo:
export ANDROID_HOME=/usr/local/android-sdk-linux
export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools

Depois, executei o comando: source ~/.profile
E depois executei os comandos abaixo:
 echo >> /.profile
    echo "export ANDROID_HOME=/usr/local/android-sdk-linux" >> /.profile
    echo "export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools" >> /.profile
    . /.profile

Segui alguns passos através desta referência:
E agora está exibindo o seguinte erro:
➜  TesteApp  ionic build android
Running command: /var/www/html/apps/TesteApp/hooks/after_prepare/010_add_platform_class.js /var/www/html/apps/TesteApp
add to body class: platform-android
Running command: /var/www/html/apps/TesteApp/platforms/android/cordova/build
[Error: Please install Android target: "android-22".

Hint: Open the SDK manager by running:
You will require:
1. "SDK Platform" for android-22
2. "Android SDK Platform-tools (latest)
3. "Android SDK Build-tools" (latest)]
ERROR building one of the platforms: Error: /var/www/html/apps/TesteApp/platforms/android/cordova/build: Command failed with exit code 2
You may not have the required environment or OS to build this project
Error: /var/www/html/apps/TesteApp/platforms/android/cordova/build: Command failed with exit code 2
    at ChildProcess.whenDone (/usr/local/lib/node_modules/cordova/node_modules/cordova-lib/src/cordova/superspawn.js:139:23)
    at ChildProcess.emit (events.js:110:17)
    at maybeClose (child_process.js:1015:16)
    at Process.ChildProcess._handle.onexit (child_process.js:1087:5)

Também executei os comandos para instalar o android-22:
cordova platforms remove android
cordova platforms add email@example.com

E recebi a seguinte mensagem:
Adding android project...
Creating Cordova project for the Android platform:
    Path: platforms/android
    Package: com.ionicframework.ionicgooglemap340659
    Name: TesteApp
    Activity: MainActivity
    Android target: android-22
Copying template files...
Android project created with email@example.com
Running command: /var/www/html/apps/TesteApp/hooks/after_prepare/010_add_platform_class.js /var/www/html/apps/TesteApp
add to body class: platform-android

Porém quando executo o comando ionic build android, ainda apresenta o mesmo erro.
O que é preciso fazer para que funcione sem erros, eu já tenho o  Java JDK instalado, precisa fazer mais alguma configuração do JAVA?
Comment: Eu recebo os mesmos erros. Tem que ver isso aí.
Comment: Vocês instalaram o Android SDK ?
Comment: Não, precisa instalar?
Comment: Eu não testei com Android ainda. Só iOS.
Comment: Sem dúvida precisa instalar e não tem que definir nenhum path para aplicação, tem que definir o path para sdk.
Comment: Como o @devgaspa disse, precisa do SDK do android e do java.
Comment: Neste [Tutorial em inglês](https://evothings.com/doc/build/cordova-install-linux.html) ele ensina a montar o ambiente no linux para somente o cordova então comece a partir do **Install Java** ele ensina a instalar todas as dependências para gerar APK android(**Java**, **Ant** e **Android SDK**). Preste muita atenção e tenha certeza de que está fazendo certo, erros na hora de gerar ambiente de desenvolvimento são terrivelmente terríveis rs.
Comment: @IvanFerrer você instalou estes 3 itens ?
1. "SDK Platform" for android-22
2. "Android SDK Platform-tools (latest)
3. "Android SDK Build-tools" (latest)
Comment: digita android no console, procura API 22 e baixa, ou se preferir pode mudar a versão no arquivo de manifesto na pasta android da aplicação.
Comment: Bom, eu baixei a partir desse link: http://dl.google.com/android/android-sdk_r24.4.1-linux.tgz e descompactei.
Comment: esse é o site principal do JDK do Android: http://developer.android.com/sdk/installing/index.html
Answer: Eu estava usando zsh ao invés do batch.
Consegui resolver fazendo o seguinte, digitei no console:
cd ~/

ls -lha

vi .zshrc

Incluí a seguinte linhas:
export ANDROID_HOME="/usr/local/android-sdk-linux"
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/android-sdk-linux/tools:/usr/local/android-sdk-linux/platform-tools"

Instalei o Android SDK, e todas as dependências do Java JDK.
No terminal digitei apenas "android" e abriu o Android SDK Manager:
Lá selecionei somente os itens da versão do Android que eu precisava e mandei instalar.
Depois executei a linha de comando:
 ionic build android

E funcionou! ele criou o apk em:
/var/www/html/apps/TesteApp/platforms/android/build/outputs/apk/test-app.apk


php & pdo & mysql countrows returning 0

Question: I have now spent several hours without getting anywhere.
I want to display number of rows in my query and here here is my code:
 <?php

        $user_id = 1;

        $statement = $dbConn->query("select badoo_interest.*, badoo_category.icon_class from badoo_interest, badoo_user_interest, badoo_category where badoo_user_interest.interest_id = badoo_interest.id and badoo_user_interest.user_id = :id_user_profile and badoo_category.id = badoo_interest.category_id");
        $statement->execute(array(':id_user_profile'=> $id_user_profile));

        $rResult = $statement->fetchAll();
        echo count($rResult);
        echo "
Interesi
";
        while( $row = $statement->fetch(PDO::FETCH_ASSOC) ){

            ?>
                <div class="interest" id = "int<?php echo $row['id'];?>">
                    <span class = "intr-ico <?php echo $row['icon_class'];?>">
                    <?php echo $row['name'];?>

            <?php
        }

    ?>

And i getting number 10 but now im not getting any interests displayed.
If you use this code now:
<?php

    //$user_id = 1;

        $statement = $dbConn->query("select badoo_interest.*, badoo_category.icon_class from badoo_interest, badoo_user_interest, badoo_category where badoo_user_interest.interest_id = badoo_interest.id and badoo_user_interest.user_id = :id_user_profile and badoo_category.id = badoo_interest.category_id");
        $statement->execute(array(':id_user_profile'=> $id_user_profile));
        echo "
"  . $statement->rowCount(). " interests:
";

        while( $row = $statement->fetch(PDO::FETCH_ASSOC) ){

            ?>
                <div class="interest" id = "int<?php echo $row['id'];?>">
                    <span class = "intr-ico <?php echo $row['icon_class'];?>">
                    <?php echo $row['name'];?>

            <?php
        }

    ?>

And now im getting all the interests displayed but it counts: 0 interests.
Any ideas who i can count number of interests?
Answer: If you read the documentation for PDOStatement::rowCount you will see this line

If the last SQL statement executed by the associated PDOStatement was
  a SELECT statement, some databases may return the number of rows
  returned by that statement. However, this behaviour is not
  guaranteed for all databases and should not be relied on for portable
  applications.

The work around is to count() function from php like you did. If that did not work then use  COUNT(*) as result_count. then when you fetch read that value.

And i getting number 10 but now im not getting any interests displayed

problem
The reason why the result aren't displaying is because you fetched all the row already so you cannot use fetch() again.
solution
Use the array returned by fetchAll() instead and use a foreach instead
$rows = $statement->fetchAll();
echo "
"  . count($rows). " interests:
";

foreach ($rows as $row){
//echo $row['name']
}

Answer: <?php

    //$user_id = 1;

        $statement = $dbConn->query("select badoo_interest.*, badoo_category.icon_class from badoo_interest, badoo_user_interest, badoo_category where badoo_user_interest.interest_id = badoo_interest.id and badoo_user_interest.user_id = :id_user_profile and badoo_category.id = badoo_interest.category_id");
        $statement->execute(array(':id_user_profile'=> $id_user_profile));
        echo "
"  . $statement->rowCount(). " interests:
";
        $counter = 0; //declare counter

        while( $row = $statement->fetch(PDO::FETCH_ASSOC) ){
                 $counter++; //increment counter
            ?>
                <div class="interest" id = "int<?php echo $row['id'];?>">
                    <span class = "intr-ico <?php echo $row['icon_class'];?>">
                    <?php echo $row['name'];?>

            <?php
        }

    ?>

[NOTE: Edit by @DinoAmino removed the emphasis characters around the two uses of $counter, which caused the code to not compile for the question asker]
Answer: I solved my problem like this:
Here is the updated solving version. Thank you all for the input:
<?php

    $user_id = 1;

    $statement = $dbConn->query("select badoo_interest.*, badoo_category.icon_class from badoo_interest, badoo_user_interest, badoo_category where badoo_user_interest.interest_id = badoo_interest.id and badoo_user_interest.user_id = :id_user_profile and badoo_category.id = badoo_interest.category_id");
    $statement->execute(array(':id_user_profile'=> $id_user_profile));

    $rows = $statement->fetchAll();
    if(count($rows) >= '1') {

    ?>

            <?php

            echo "
"  . count($rows). " interests:
";
            foreach ($rows as $row){

                ?>
                    <div class="interest" id = "int<?php echo $row['id'];?>">
                        <span class = "intr-ico <?php echo $row['icon_class'];?>">
                        <?php echo $row['name'];?>

                <?php
            }

            ?>

    <?php } ?>

php & pdo & mysql countrows returning 0


ASP / C# Session Variable - Object reference not set to an instance of an object

Question: I'm somewhat new to ASP / C# and I'm having an issue (probably simple) with sessions variables. My project has a Site.Master in which session variables are set under the Page_Load method like so:
    protected void Page_Load(object sender, EventArgs e)
    {

        if ((Session)["UserID"]==null || (Session)["UserID"].ToString() == "")
        {
            (Session)["UserID"] = HttpContext.Current.User.Identity.Name.ToString();
            SqlDataReader dr = Sprocs.GetPermissionGroups();

            string groupList = "";

            while (dr.Read())
            {
            if (groupList != "")
                    {
                        groupList = groupList + "|" + dr["WG_Group"].ToString();
                    }
                    else
                    {
                        groupList = dr["WG_Group"].ToString();
                    }
            }
            dr.Close();

            if (groupList != "")
            {
                (Session)["UserGroups"] = groupList;
            }
        }

This does work. If I dump out the session variable 'UserGroups' to a label or something within this method, it does display the variable contents correctly.
So, my problem lies within another page (say default.aspx) when I try to access that same session variable. In the Page_Load method of the other page I attempt to do this:
    protected void Page_Load(object sender, EventArgs e)
    {
            string GroupList = HttpContext.Current.Session["UserGroups"].ToString();
            //some code with the variables here
    }

This always fails with an "Object reference not set to an instance of an object." error. Am I trying to get the Session variable wrong? I've tried
string GroupList = Session["UserGroups"].ToString();

this also errors with the same error.
string GroupList = (string)(Session["UserGroups"]);

This always returns an empty string.
What am I doing wrong?
Thanks!
Comment: do you hit the first page before going to the second page?
Comment: what do you have your session state set to in the web.config?
Comment: The first page should be loading first. The way I understand the site.master and any pages that use it is that the site.master loads first, then the page using it.

as for web.config, under  I've got
Answer: The syntax you are using in your Page_Load method I wouldn't have even expected to compile. Regardless, the issue is that you have not set the Session with that key, so it will return null. When you call ToString() on that null, you get the exception. In your second example:
string groupList = (string)(Session["UserGroups"])

That is doing a conversion of null to string, which results in a null string (thus not causing the exception).
You should be able to rewrite your Page_Load implementation like so:
string sessionUserId = Session["UserId"] as string;

if(string.IsNullOrEmpty(sessionUserId))
{
    Session["UserId"] = HttpContext.Current.User.Identity.Name.ToString();

    SqlDataReader dr = Sprocs.GetPermissionGroups();

    string groupList = "";

    while (dr.Read())
    {
        if (groupList != "")
        {
            groupList = groupList + "|" + dr["WG_Group"].ToString();
        }
        else
        {
            groupList = dr["WG_Group"].ToString();
        }
    }
    dr.Close();

    Session["UserGroups"] = groupList;
}

Then, when accessing the session variable later, do it like so:
 string userGroup = Session["UserGroups"] as string;

This is a safe way to attempt the conversion of whatever bucket that is in session into a string. If the key doesnt exist, or the value is not a string, you will get null. Otherwise, you will get the string from that hash.
Comment: Alright, that does make sense on why I was getting the error and casting that 'as string' does prevent it from happening.

Though that does raise another question. Not sure how the best way to word it is. So this code above is in say default.aspx which uses Site.Master and it's Page_load to set the variables. If I start on default.aspx then for some reason when I check the session variables in the page_load of default.aspx they are blank. If I navigate to another page and then back they are populated. Does Site.Master load after page_load of default.aspx?
Comment: The master page will execute it's `Page_Load` event before the child page. I'd verify that you are not doing something odd in your master page that would be affecting things. In addition, your child `Page_Load` invokes `HttpContext.Current.Session` instead of `this.Session` - while it should be irrelevant, make sure you are consistent.
Comment: Alright I got things figured out. After doing some testing and reading it does appear that the page_load for the site.master DOES occur AFTER the page_load of default.aspx, which explains what I'm seeing. Moved my session variable code to the Session_Start method in Global.asax and it seems to be working like I want it to. Thanks again for the help!


Filter entities in a view by referenced entity

Question: I am creating a website in Drupal 8 that shows info about team members of a business.
I've created two new content types:
- Department
- Team Member
I've created an entity reference field in team member that refers to the department he/she works for. The relation is many to many so I allowed multiple values.
Now I want to create a menu item for each department and when clicked a page shows with the team members working for that department.
I am totally new to Drupal so please explain steps in details :)
I've tried creating a view and add "Entity Reference" but I don't know how to proceed after that.
I also tried to add a filter criteria but didn't work as well.
Answer: Phase1:
You would need to construct a view using contextual filters, relationships and dynamic path (url) to display team members for a department.

First create a view with Content type of Department. Also enable Create a page and add path like for example, /department/%. Here % is used to make your path dynamic (to pass arguments such as nid using contextual filters). Then click continue & edit.
Now in your view under the advanced section, add a reverse relationship to your team member content type. You should select something like A bridge to the content entity that is referencing content via field_teammember. The field_teammember is an entity reference field from team member content type.
Next under fields, add all the required fields you need. If you add any of your team member content type fields, do not  forget to add relationship in those fields settings.
Again under the advanced section, add contextual filters. Select Content:Nid and in the settings do not add relationship because this Nid will be of the department content type (base table of your view).
In the same contextual filter configuration, under When the filter value is NOT available section, select provide default value and then select type as Raw value from URL. The path component value will be the position of % in your url. In the path you specified /department/%, its in the second position. Select 2 for your path component value and click apply.

This should have already generated a view as you required.
Now to preview your view, find an Nid of any department node and paste it in the Preview with contextual filters and click update preview. This will display the team members of that department.
Phase2:
Now create a view of departments list for menu items.

Create a view and select Content type of Department. You do not require a page for this view. Click Continue & edit.
Under fields, if you already have a Title field as your department name then add only an Nid field. And in the Nid field settings enable Exclude from display.
Note: If you don't have title field as your department name, then remove the title field and add a department name field.
Now if you are using title field, disable Link this field to the original piece of content option. Then expand Rewrite results section and enable Output this field as a link. In the link path, add your dynamic url created for previous view like www.xyz.com/department/[nid].
Note: In the link, Nid is replaced with %. This could be some other value in your view, so you need to get this from Replacement Patterns in the field settings.

This will create another view for your departments list.
Now install and enable Menu views module if you don't have it. Next in the Administrator/Structure/Menus, create a menu and in the settings select departments list view to display the list as menu items.
Hope this helps.
Comment: Thanks for the detailed answer, I've been trying phase1 so far and something is not right.
Here are some settings that are not listed in your answer:
- The view format is 'Unformatted list'
- The Format:Show is 'fields'
- The fields are: title field from department, and all fields from members with the reference from advanced listed as the used reference for each field.
Comment: - When creating the reference, I got two choices: Content referenced from, and content using. I chose the first one I actually don't know the difference.

The status now is that the filter is working fine, I write the node id for the department in URL and it shows its title, but no members info is shown on the page, only the department title and an empty page


C#: Upper cast - List to List - cast obejct of internal class

Question: I have an interface defined as
public interface INamedReader
{
     string DisplayInfoLine { get; }
     string DisplayName { get; }
}

and a class which implements that interface but it is an internal class
internal class NamedReader : INamedReader, INotifyPropertyChanged
    {
        public NamedReader();

        public string DisplayInfoLine { get; set; }
        public string DisplayName { get; set; }

        public event PropertyChangedEventHandler PropertyChanged;

        public override string ToString();
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = "");
        protected virtual bool Set<TField>(ref TField field, TField value, [CallerMemberName] string propertyName = "");
    }

and a class which implements the above NamedReader class
internal class NamedReaderDevice : NamedReader
{
    public NamedReaderDevice();

    public string Id { get; set; }
}

and now i defined class which implements INamedReader
public class ReaderDetails: INamedReader
{
     public string DisplayInfoLine { get; }

     public string DisplayName { get; }
}

I then created a function which return List.
public List<ReaderDetails> GetReaders
{
     var readers = new List<ReaderDetails>();
     var Ireaders = someobject.Getreaders();// Returns the list of NameReaderDevice (which is an internal class).
     // Now i would like cast Ireaders as readers and return.
}

can someone please help me out in this, that would be great.
Comment: Didn't you just ask this already? `..GetReaders().OfType().ToList()`
Comment: Possible duplicate of [How do i convert a List to List in c#](https://stackoverflow.com/questions/44668956/how-do-i-convert-a-listinterface-to-listclass-in-c-sharp)
Comment: Like `var Ireaders = someobject.Getreaders().Cast();` using linq?
Comment: Like `var Ireaders = someobject.Getreaders().OfType();` ?
Comment: if it's a list of 'NamedReaderDevice' you cannot cast them to 'ReaderDetails'
Comment: What do you mean with the type `Ireaders`? Would you like it to be `IList` or `List` or something else? Or does the list have to be a List (which is, as you say, internal?)
Comment: Ireaders is just variable Name.
Comment: My bad... I did not read it well. Still the question remains always the same: What type do you want it to be?
Comment: List - list of ReaderDetails objects
Answer: You are basically trying to convert one class into an entirely different one, like in this picture, trying to convert Class2 to Class3:

In this scenario, even if they share an interface, you cannot cast between one and the other.
You have a few options:

use a method (extension or otherwise) to convert between classes, using Reflection or serialization (not very efficient)
use a conversion operator (more details here)
return an interface instead of an explicitly implemented class in your Getreaders() method and then use an interface in your application instead of an explicitly implemented class;

In case of (3) if you need or want to further decouple your class implementation, then you may use dependency injection for it (eg. SimpleInjector, accessible through nuget). In that scenario you can for example create objects of said interface in code that does not have acces to the internal class implementing it,


Trigonometric ratio question..

Question:
If $3\sin B+5\cos B=5$, show that $3\cos B- 5\sin B=\pm 3$

I tried this:
\begin{align*}
3\sin B + 5\cos B & = 5\\
\text{or}, \dfrac{3p}{h} + \dfrac{5b}{h}& = 5\\
\text{or}, 3p+5b& = 5h\\
\text{or}, 9p^2+30pb+25b^2 & =25(p^2+b^2)\\
\text{or}, 16p^2& =30pb\\
\text{or}, \dfrac{p}{b}& =\dfrac{15}{8}
\end{align*}
$h= \sqrt{15^2+8^2} = 17$
\begin{align*}
LHS & = 3\cos B-5\sin B\\
    & = \frac{3b}{h}-\frac{5p}{h}\\
    & = \frac{3 \cdot 8-5 \cdot 15}{-17}\\
    & = -3
\end{align*}
But how do I get plus $3$?
Comment: Welcome to MathSE.  This [tutorial](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) explains how to typeset mathematics on this site.
Comment: Thanks I will learn it
Comment: What in the world are $ p $, $ b $, and $ h $?
Answer: Note
$$25 = (3\sin B+5\cos B)^2= 9\sin^2B + 25\cos^2 B +15\sin2B \tag 1$$
and
$$(3\cos B- 5\sin B)^2= 9\cos^2B + 25\sin^2B -15\sin2B \tag 2$$
Substitute $\sin2B$ of (1) into (2) to get
$$(3\cos B- 5\sin B)^2= 9\cos^2B + 25\sin^2B -(25 - 9\sin^2B - 25\cos^2 B ) = 9$$
Thus,
$$3\cos B- 5\sin B=\pm 3$$

Trigonometric ratio question..


Are multiple coexistent instances of MockRepository possible? If yes under which conditions?

Question: Hippomocks' MockRepository supports multiple instances as far as the compiler is concerned. Some use cases are not possible, though, as they lead to unit test executable crash. Let's consider the following example.
void MyCall()
{
}

void MyCall2()
{
}

void MySubTest()
{
    MockRepository mockRep2;
    mockRep2.ExpectCallFunc(MyCall2);

    MyCall2();
}

void MyTest()
{
    MockRepository mockRep1;
    mockRep1.ExpectCallFunc(MyCall);

    MySubTest();

    MyCall();
}

This example leads (in Visual C++ 2010) to an unhandled exception (access violation reading location 0x00000048).

Analyzing the Hippomocks header shows that this use case doesn't seem to be foreseen (cf. MockRepoInstanceHolder). What is the reason behind allowing only one instance?
I can understand that for example different ExpectCallFunc in the MockRepository instances can contradict. Is it the reason behind it?
We could solve the problem in our example by moving the mockRep1 instantiation to after the MySubTest() call, but we had a hard time understanding the problem in a first place. Is there a compile-time or run-time possibility to identify such multiple instances explicitly?
Answer: I came across the same problem.
Using cppunit as test framework, I made the MockRepository a member of the test frame class.
If there are several test cases, cppunit instantiates a new object of the test frame class for each test case. This overwrites the MockRepositoryHolder. I got the exception when trying to mock an Windows API function in the first test case, but HippoMocks referenced the last written MockRepository, which if the one of the last test case.
For me, a workaround is to either make the MockRepository local to each test case or add a new, local MockRepository only for mocking static functions
Answer: The root problem is that the (compile-time generated) function does not have a place to 'tag' it with a certain mock repository and unlike mock objects it cannot be grown to carry it as well. That's what the holder is for - to find the mock repository from the generated stub function.
It sounds like a solvable problem if there's a good use case for it, by making the generated code in that function a bit more complex. I must admit that I don't see a direct immediate advantage, especially as mocking the same function twice in two separate repos wouldn't work anyway (because you're hard-overwriting the same function) and it would lead to very difficult to debug problems if you mix them up at some point. I don't think the added complexity and debugging difficulties weigh up against the feature added by this.
Comment: Thanks for the answer. I marked it as the right answer as I was rather asking for background information rather than a "bug" fix (which is rather a design decision than a bug).


Can any iSCSI NAS appliance replicate / clone a LUN to an external drive?

Question: I would like to backup using Windows Imaging to some kind of NAS appliance.  I believe this will require the NAS to support iSCSI.  I would then like the appliance to support the replication of the iSCSI LUN to an external eSATA or USB disk connected directly to the appliance.
I've found plenty of NAS appliances that can do iSCSI and replicate to an external drive, but none that I've found thus far can do both at once.  That is, the devices can do iSCSI, but then the replication feature doesn't work.
The idea here is to backup to an appliance located in a secure office far away from the server room.  Offsite backups to external hard drive could be managed from the appliance.  The benefits of such a setup would be: 1) very unlikely that fire or random theft would affect both server-room backup and "remote" backup appliance 2) offsite backups could be managed by multiple trusted people without granting access to server room 3) Windows imaging provides poor man's deduplication, so each backup volume can contain a decent backup history.
I understand why this would be a non-trivial thing to implement, but I'm wondering if such a thing exists?  Preferably a tabletop, low to medium cost device.
Alternative solutions welcome.  NOTE: I'm backing up very few but very large files, so file replication is not a good option.
Answer: Depending on the target and initiator, you could always mount the drive on another server (at the same location as the iSCSI target) and then do the replication from that server.
This assumes that the filesystem will support this, and as there's no mention of that in your post I can't make any suggestions on whether or not it will work in your environment.
Windows Storage Server 2008 (which is neither tabletop, nor cheap) can also do this by mounting the iSCSI disk locally as well as on the remote machine, and you could then replicate (Mirror or whatnot) this way.
Comment: Actually the Tandberg Data AccuVault DPS3005 RDX *is* desktop, it doesn't even have rack fittings AFAIK, *and* it runs Windows Storage Server 2008.  Not cheap though, alternatively if the poster has MSDN licenses...
Answer: Tandberg ship a edesktop product called Tandberg Data AccuVault DPS3005 RDX which is perfect for your scenario but perhaps not for your budget.  It runs Windows Storage Server so provides you with an iSCSI target and deuplication.  The unit incorporates a removable RDX cartridge, you can buy several of these and rotate them offsite.  RDX cartridges are as portable as USB drives, and a bit nore robust and easier to catalogue (I've bought them cheaply on Ebay).  Also Accuvault is reputedly a good backup software solution.  I'm suggesting this as a 'conceptual' perfect solution rather than a practical one, because the unit is quite pricey.
Answer: iOmega's NAS appliances can do both: iSCSI and local replication. There are models for desktop (2 to 6 drives) and for rack mounting (4 or 12 drives). Also all models supports replication via rsync.


Is it possible to learn theory without sight reading?

Question: I'm learning music theory by myself with online books and video lessons. I don't have much trouble understanding the basics of theory, such as intervals, basic scales and modes, but I have a huge issue with sight reading.
I know that sight reading is important, but I find it hard to read notes in a music sheet on an acceptable speed and transpose the notes to my instrument of choice (which is a guitar).
I want to understand the concepts behind music and apply that knowledge to a guitar, but I feel that I may be missing something if I skip sight reading. Should I stop this bad behavior of mine if I want to become a better musician?
Important notes: Music is a hobby for me and I do not plan to play in any kind of band or such. I have a keyboard and I know that it is easier to learn sight reading on an instrument such as piano/keyboard due to how the notes on the instrument are placed, so if I have to change instruments to learn it I am able to do so.
Comment: It's absolutely possible to know a lot of theory and not be able to sight read.  Standard music notation is about being a team player, yet obscures theory that is obvious in alternate notations.

It is easier to number notes 0..11 in some situations, or to use frequencies and pitch ratios in other situations.  Heavy Metal shredders with much scale/chord skill use tablature. It has unambiguous fingering.  Microtonal (fretless) musicians are obnoxiously theoretical, and have little use for standard notations.
Comment: They are two different things. *sight* reading ie the ability to pick up sheet music and play it without preparation - is a separate area of knowledge from music theory. . . which is just that - theory. You can be an expert in music theory without being able to play a note.
Personally my theory knowledge is way more than my playing ability - and I so much wish it were the other way round.
Comment: I'm reminded of a remark made by a classmate who majored in music: he said that our college's music department believed that "music should be seen and not heard."
Comment: Yes, it is possible. _I did_. But that's probably because I play guitar the most, where transposing a song a semitone up is a whole lot easier than on a piano. However, I still can't sight read guitar tabs, although, [it is possible](http://music.stackexchange.com/questions/3068/as-a-guitarist-how-can-i-learn-to-sight-read-music).
Comment: Most, if not all, guitarist can't sight read even average songs perfectly the first time. Even my classical guitar instructor, who had a master's degree, had to spend around an hour to master a song with 2 voices. Unrelated, but if you're interested check this out http://www.woodpecker.com/writing/essays/guitarnotation.html
Comment: C'mon brah. I spent 10 years of my life teaching this to 9 year olds. What is the problem?
Answer: I would say that since

Music is a hobby for me and I do not plan to play in any kind of band or such

learning to sight read isn't really important. It depends on you. I prefer reading normal music sheets rather than tabs or whatever, but this is just me. If you have time and energy to learn how to sight read,it most certainly won't be wasted.

but I find it hard to read notes in a music sheet on an acceptable speed and transpose the notes to my instrument of choice

This just takes practice. You need to practice sight reading in order to be able to sight read a piece and play it at the same time. It doesn't happen overnight. So, just keep practicing if you want to have satisfactory results.
I, personally, don't think that you would miss out on music theory if you don't sight read. You would miss out on music theory if you don't understand what you are playing on your guitar.
Let's say that for instance you play the 3rd fret on the E string and then the 2nd fret on the A string. If you know that these notes are G and B respectively, (and since you know about intervals -- thus you know that this is a major 3rd) you won't be missing out, no matter if you sight read them or read a tab.

it is easier to learn sight reading on an instrument such as piano/keyboard

I wouldn't say that this is necessarily true. Every instrument takes some practice to play while sight reading. Some instruments (like the ones you mentioned) might actually be a bit easier, but that doesn't make an instrument like the guitar that much harder to learn to sight read.
Answer: I would actually say that the opposite is true, namely, that study of music theory is what matters, and that even if you don't practice sight reading (though you probably should), it's the study of theory that will make the biggest improvement in your sight reading compared to anything else.
Sight reading is a tricky thing to do, there is quite a lot of information, and unlike the arabic letters of the alphabet, there is very little in the way of unique characteristic that helps to differentiate between notes of a different pitch.
Rhythm is actually far easier to read because there is far more that characteristically distinguishes each individual note, namely the stems, flags and fill of the circle.
The primary functions one must understand when reading music relate to theory, namely the key signature in which the piece is written and intended. When one observes which sharps and flats the key signature has, this illuminates almost immediately which notes are viable and which notes are not. In other words, the key signature eliminates a lot of possibilities and potential confusion because, to sound correct, there is only now a limited subset of notes to choose from, e.g. only the notes in an Eb scale perhaps, which means that you know several black notes and several white notes are out of the question.
This then means that one may focus less on the absolute note names and positions of each note on the staff, and may then refer to the relative distances between successive notes, combined with the scale which is being used, to determine which notes the music is probably referring to.
I for one, personally, have been almost always horrible at sight reading, but over the years of e.g. reading chord charts on both guitar and piano, and over the years of haphazardly attempting to solo, in an improvisational manner over chord changes, I have found that my sight reading ability has actually dramatically increased with pretty much no actual practice in actually spending time reading standard written musical staff based notation. This is because I have studied each of the 12 keys so in depth, and have learned so many songs, and have practiced my circle of 4ths, 5ths, 3rds, half steps, whole steps etc, that I just have a familiarity with each key and the territory and relationships across which music most often progresses.
This means that when I try to read music, so much of it is so much more immediately obvious to me that I don't need to actually "read" every single individual note, and this ability to read without reading is something most good teachers I've had have confirmed as being the general appropriate way to read music.
So, you really probably should practice reading music in its own right, but realize too, that study of theory and composition, of key and of modulation, are critically important to actually increasing your ability to read music as you practice that skill.
Answer: Whilst agreeing with most of Shev's answer, I feel that sight reading is a lot more straightforward on a keyboard type instrument.For each note on the stave, there is only one place to play it. Thus it makes more sense, and the 'geography' of a melody is simpler to translate onto the keys. With a guitar, there are sevceral different places to play the same note, so it can confuse quite easily. There would be no need to use anything but the treble clef initially on keys, but if you're into theory, then the bass clef would start to make sense with keys, not guitar. (Unless you're on bass!)
If you do go for guitar, the accompanying tab may or may not help. It's usually one person's idea of where the notes get played. It's not usually the only place, though, and this in itself may mess up your learning process.
Being able to read will only be an advantage to you, so go for it - it'll also put some of that theory into practice, with timing, etc.
Answer: It is important to be able to read music to some extent. But the ability to sight read, which means to be able to pick up the music and just play it, is not all that essential. I can sight read a single vocal line, but in theory classes, we used complex scores that there was no way I could ever sight read them.
In fact, sight reading was part of a different class, called ear training. And that class was pretty much everyone's worst class. Yet all of them were not only good enough with theory to pass, but also actually played written music in concert. They just learned the music slowly over time.
So, no, I would say that sight reading is not all that important for learning music theory. What's important is that you know what the notes mean. Sight reading is a skill that can open up possibilities for playing your instrument, but it has little to do with actually understanding how music works.
Comment: @TonySniper Just note that I don't mean that you don't need to know how to read music. That's a different skill, and it's pretty important. But reading and playing are different things.
Comment: "but it has little to do with actually understanding how music works" That was exactly my doubt. I was concerned if I would not be able to understand how music works in theory if my sight reading is undeveloped.
Comment: I understand that. I am able to read simple music sheets, but as I said, my problem is that I read them slowly and that I have trouble playing what I read. I'm working on my reading skills nonetheless, hehe.
Answer:
I feel that I may be missing something if I skip sight reading

I think so. Understanding (and being confortable with) traditional music notation is very useful, and specially in combination with the understanding of the theory (scales, chords, etc). For example, you can detect at first sight the tonality of a piece, and spot quickly the chromatic notes, etc. Not only that, but most classical guitar works and study books are writen in that way. Furthermore, it's much detailed (well specified) notation than a tab (you can play a piece without having ever heard it). And, even more: you can even read some music sheet for other instrument (eg, piano) and sight-play it almost instantaneously on your guitar (even with trasposition, just by mentally moving the notes up or down visually, in the staves). I play classical guitar, I'm totally amateur, (you can check my profile) and I value all this inmensely.
Answer: Learning music theory without sight reading is like learning poetry without reading.  Sight reading is not essential to music theory, but scores are the written language in which the music theory has been laid down.
Now with a guitar, "sight reading" mostly describes a reproductive skill, like being able to recite a text you did not know before.  It is not necessary to read out loud in order to understand a text.  In a similar way, it is not necessary to actually play some material in order to understand underlying music theory.
Playing from tablature is sort of like reading from a phonetic transcription: you only get what is necessary for basic mechanical reproduction (and it may work even in languages you don't know), but the underlying structure and sense is harder to see and that may reflect the quality of the reproduction.
So being able to work with scores tends to give you more of a story about the music (including more theoretic stuff like voicing and leading) than working with tablature.
With regard to music theory, sightreading skills just are a skill making scores more familiar, and those are the language that music theory employs for pinning down things.
It's like knowing physics when doing math.  Just a different threshold of entry and a different level of preexisting basic familiarity.  But not the same story quite.
Answer: There's only one way you can learn theory without knowing how to read music: a teacher explains and shows you. So you can get this either with in-person lesson (teacher sitting next to you) or online video lesson. That's it.
Comment: I think the question is about whether or not it's necessary to learn sight-reading, not how to go about learning it.
Comment: I guess I answered the question in a roundabout way. The short answer is: it's *not* necessary to learn how to sight read music.
Comment: I see now--it's not necessary because a teacher is an adequate substitute.
Comment: Correct. If you don't know how to read music then someone has to physically show you where to put your fingers on the keys and what it all means.
Answer: Sight reading is an extremely rare skill which is mostly used by high level performers auditioning a piece they have never seen for a part in a musical or band. For nearly all other players, it is unrealistic to attempt to play a piece you cannot easily sing or with which you are unfamiliar. The main value of reading music is NOT to play it the first time (or even the 10th time) you see it. The value of the written music is to help you get the feel of it, and to be used as a reference, not as an exact procedure.
  Music doesn't come from what is written. Instead, it comes from the feeling of it, the rhythm, the flow.  Notation usually gets in the way of listening and letting it flow. Don't get trapped by the written music. Play it from your feeling, and let your ear guide you.
 Thanks,
Mark Tennenhouse
Comment: Thing is, if you've ever taken typical piano lessons or school concert band lessons, you *are* trapped by the written music. Unless there are clear typos or approved errata, your teacher will often force you to fully follow all musical directions on the score by the time you need to memorize or publicly perform the piece. Also, sight reading is not "extremely rare". Sight reading at full speed can be, but if you want to continue your school concert band lessons without being disruptive, you need to be able to sight read at the speed of the conductor's baton (which can be half speed or less).
Answer: Absolutely.
I speak as someone who over the years has studied theory without learning to read sheet music. For 2 reasons:

I made music using a DAW for many years without a keyboard/piano
I'm a software developer who writes music related software. Theory knowledge was required for a number of projects I've worked on

As a musician I regret not learning to read music early on. Reading and playing music from a sheet is a valuable skill. It really helps when studying other musicians/composers work.
If, like me, you work in a DAW you can apply your theory knowledge on the piano roll. It's also very useful when tuning samples, vocals etc.
There's a great selection of books by Michael Hewitt that teaches theory from a "computer musicians" perspective. It's called Music Theory for Computer Musicians. He has other books too that discuss composition and harmony.
Without being able to read music though you will struggle when it comes to reading something like ABRSM's "Harmony in Practice".
Take your time, grab some good books, and study. In time you will likely want to learn how to read music. I suggest you grab this book and go through it in your own time.
I hope that helps.
Answer: Bro, when I was a kid I took 4 years of grueling music lessons from a piano teacher who went to Juilliard. We did the whole sight reading thing. Just rote sight reading, different classical pieces. I would go to her house and she'd pull up some random classical piece, and I would spend weeks learning it. Mozart, Bach, Chopin, etc. It was pure torture and it caused me to hate piano. I know about 0.5 classical songs from that time, and I can't even sight read anymore because I forgot everything. I look back at those 4 years as the biggest waste of time musically in my life. She didn't teach me anything about theory, just sight reading. It was almost like I had missed the entire point to music during that time.
Fast forward 10 years, I picked up guitar. And unlike piano the guitar is all about "hacking" music. So just theory (scales, modes, chords, etc) and not a big emphasis on sheet music. rather tabs and music theory and modern music rock/pop/etc as opposed to classical music. I loved it. I played guitar for alot of years. Now I'm back to piano. But with a guitar mindset. And I couldn't be happier. To me now, it's all about playing by ear and music theory. and I believe that music theory (scales, chords, etc) works better with playing by EAR than it does with learning sheet music. sheet music just teaches you to become a robot that plays to the T something, that somebody else wrote hundreds of years ago.
If you "must" get notation because you get desperate then there's always tabs for guitar or synthesia for piano. They're both easier than sheet music. The only reason I'd think someone would go for sheet music is if they played in an orchestra or played classical music for a living. For all those using sheet music because they're trying to learn music as a hobby. Frankly, I think it's a total waste of time. It's difficult and unintuitive. ESPECIALLY for guitar. the only reason you'd use sheet music on guitar is if you're a guitarist that plays classical music. And even then tabs are more effective. I took a course on guitar sheet music for a semester in college, and just like my experience as a kid, I hated it.
The most important skill as a musician is the ability to play by ear. Period. It takes just as much practice to play by ear as it is to sight read. So say it takes 3 years to be an accomplished sight reader, then it's 3 years to be an accomplished ear trained musician. And what I mean is, by being good at playing by ear, you can listen to ANYTHING on the radio or in your head and quickly play it on your instrument. If you can get to the point where you can play what you hear in your head, and understand the theory behind it to boot. Then myyyy man, that's what it's all about. You can play anything, and you can improvise too.
p.s I know what I said might sound biased, but hey, this is MY experience and my opinion.
Answer: Yes it is possible.  As a guitar player, I have never developed a good skill sight reading. I read lead sheets, which mostly guitar players use. In a sheet music situation. Guitar players are mostly called on to sight read chords on sheet music in a group situation.
However,my music theory is highly developed. And ear training goes hand in hand with that. I wish I could be better at gaining the reading the staff though but I just didn't learn that way and it doesn't come easy. So to answer, yes i can play with musicians who read better than me but I am ahead on ear training and music theory. It's a difficult skill to develop, many guitar players have highly advanced theory and devoloped ears but lack sight reading. However, can still read the lead sheets. I feel learning disabled in that way..It's a source of many good guitar player jokes though on the bright side ..
Answer: Yes - I compose orchestral music as a hobby, but I don't play any instruments. So, yes, technically you can learn theory without knowing how to sight read
Answer: I know that most people think reading is important. But I've found there is a much easier way to proceed.
There is plenty of proof that knowing how to play an instrument has almost NOTHING to do with being able to sight read. They are two SEPARATE skills just like speaking and reading. For example, the Beatles couldn't sight read music at all. Neither could Stevie Wonder. Neither could a ton of famous musicians including Eric Clapton and Lionel Richie to name just a few. But, they could play A LOT of songs by ear and they knew how to play chords VERY well.
I honestly think that learning chords and songs is the shortest and most natural way to learn to play piano and guitar. For beginners, it's MUCH better to just learn songs. Then, after you can play a dozen or more songs on your instrument, it will be time to return to learn to read.
So, first learn to play a dozen songs. Then you will find that learning to read and play at the same time is MUCH easier because your hands and mind will be able to easily play the chords. BUT, if you try to learn how to play WHILE reading from sheet music, it's going to take you a VERY long time to learn even basic songs. That's why so many people quit learning music. They didn't realize that learning to read should come AFTER learning to play.
Comment: You haven't mentioned theory in your answer, and the question is "is it possible to learn **theory** without sight reading?" Could you add a discussion of where learning theory fits into the sequence? Without that additional bit, I think you haven't answered the question.
Comment: At the moment this hasn't answered the question in hand. It's answered a different one! The relationship between theory and sight reading needs to be in your answer to give it credence.


entity_autocomplete field thats added by ajax is not working

Question: I have a field im adding to a node-edit form by ajax. the field is a simple taxonomy auto-complete field.
when I add it directly in my form_alter it works, but when it's added by ajax, The autocomplete is not there - the field looks and behaves as a simple text field.
I have edited my question and added my code.
 use \Drupal\Component\Utility\NestedArray;

function MM_field_widget_MW_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context){
        $element['display_id']['#ajax'] = [
          'callback' => 'getAjaxArgumentsFields',
          'wrapper' => $id . 'arguments',
          'method' => 'replace',
          'event' => 'change',
        ];
        $display_id = $element['display_id']['#default_value'];
        $element['options']['arguments'] = get_argument_fields($display_id); //Works, with entity_autocomplete working

}

function getAjaxArgumentsFields(&$form,  \Drupal\Core\Form\FormStateInterface $form_state){
      $display_id = $form_state->getTriggeringElement()['#value'];
      $fields = get_argument_fields($display_id);
      NestedArray::setValue($form, $array_parents, $fields);
      return  NestedArray::getValue($form, $array_parents); //Returns the exact same fields, but no autocomplete functionality- they appeare and behave like a regular text field
}

function get_argument_fields($display_id){
      $args_field = [];
      $argument_definition = get_argument_definitions($display_id);
      $args_field = [
              '#type' => 'entity_autocomplete',
              '#title' => $argument_definition['title'],//Taxonomy term
              '#target_type' => $argument_definition['type'],//taxonomy_term
              '#default_value' => '',
              '#selection_settings' = [
                     'target_bundles' => $argument_definition['bundles'],//voc_name
               ],
      ];
     $args_field['#prefix'] = '
';
     $args_field['#suffix'] = '
';
     return $args_field;
}

What do you guys think could be the reason?
Thank you!
Comment: The reason is that [EntityAutocomplete::processEntityAutocomplete](https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21Element%21EntityAutocomplete.php/function/EntityAutocomplete%3A%3AprocessEntityAutocomplete/8.7.x) is not executed. Probably because you mean by "added by ajax" it was added in an ajax callback, which is not allowed. Keep the form element in the form alter hook and then only deliver it from the ajax callback.
Comment: In the ajax callback you overwrite the fields again with the unprocessed version of the form element.
Comment: yes it is it added in an ajax callback.  I have really spent the day trying to figure out what "only deliver it from the ajax callback" means. Can you give me a hint? My ajax in invoked by a change of a select field.
Comment: The ajax callback you invoke receives $form as argument. This contains the form element you put into the form build in the form alter hook, but it should look different now, because it is processed by then. This processed $form is what you can deliver to the client, either by returning parts of $form or by building an ajax command.
Comment: I have edited my question to add more code. because I feel that what you describe is what im doing. but I am sure im missing something.
Answer: Ok, So thanks to 4k4 I now understand what i was doing wrong, and for the favour of everyone that will meet this issue again:
The form_alter is invoked as well when ajax callback is invoked.
by the time the execution got to my ajax callback (getAjaxArgumentsFields) the form_alter has already altered my form, so all i had to do was return the fields without changing them.
Here is the code that worked for me:
use \Drupal\Component\Utility\NestedArray;

function MM_field_widget_MW_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context){
    $element['display_id']['#ajax'] = [
      'callback' => 'getAjaxArgumentsFields',
      'wrapper' => $id . 'arguments',
      'method' => 'replace',
      'event' => 'change',
    ];
    $display_id = $element['display_id']['#default_value'];
    $element['options']['arguments'] = get_argument_fields($display_id); //here I change my field, both on load of the page and also before ajax
}

function getAjaxArgumentsFields(&$form,  \Drupal\Core\Form\FormStateInterface $form_state){
    $array_parents =  clac the path to the wanted field
    return  NestedArray::getValue($form, $array_parents);
}

function get_argument_fields($display_id){
      $args_field = [];
      $argument_definition = get_argument_definitions($display_id);
      $args_field = [
          '#type' => 'entity_autocomplete',
          '#title' => $argument_definition['title'],//Taxonomy term
          '#target_type' => $argument_definition['type'],//taxonomy_term
          '#default_value' => '',
          '#selection_settings' = [
                 'target_bundles' =>
           $argument_definition['bundles'],//voc_name
           ],
           ];
      $args_field['#prefix'] = '
';
      $args_field['#suffix'] = '
';
      return $args_field;
}