IPTables masquerading with one NIC

Question: I am running an OpenVPN server with only one NIC.
This is my current layout:
public.ip > Cisco firewall > lan.ip > OpenVPN server

lan.ip = 192.168.22.70

The Cisco firewall forwards the requests to the oVPN server, thus so far everything works and clients are able to connect.
However, all clients connected should be able to access 3 networks:
lan1: 192.168.200.0 (vpn lan)    > tun0
lan2: 192.168.110.0 (office lan) > eth1 (gw 192.168.22.1)
lan3: 192.168.22.0  (server lan) > eth1 (broadcast network)

So tun0 is mapped to eth1.
Iptables output:
# iptables-save
# Generated by iptables-save v1.4.2 on Wed Feb 16 14:14:20 2011
*filter
:INPUT ACCEPT [327:26098]
:FORWARD DROP [305:31700]
:OUTPUT ACCEPT [291:27378]
-A INPUT -i lo -j ACCEPT
-A INPUT -i tun0 -j ACCEPT
-A INPUT -i ! tun0 -p udp -m udp --dport 67 -j REJECT --reject-with icmp-port-unreachable
-A INPUT -i ! tun0 -p udp -m udp --dport 53 -j REJECT --reject-with icmp-port-unreachable
-A FORWARD -d 192.168.200.0/24 -i tun0 -j DROP
-A FORWARD -s 192.168.200.0/24 -i tun0 -j ACCEPT
-A FORWARD -d 192.168.200.0/24 -i eth1 -j ACCEPT
COMMIT
# Completed on Wed Feb 16 14:14:20 2011
# Generated by iptables-save v1.4.2 on Wed Feb 16 14:14:20 2011
*nat
:PREROUTING ACCEPT [302:26000]
:POSTROUTING ACCEPT [3:377]
:OUTPUT ACCEPT [49:3885]
-A POSTROUTING -o eth1 -j MASQUERADE
COMMIT
# Completed on Wed Feb 16 14:14:20 2011

Yet, clients are unable to ping any ip (including 192.168.200.1, which is the oVPN's IP)
When the machine was directly connected to the internet, with 2 NICs, it was quite simply solved with masquerading and adding static routes in the oVPN client's config.
However, as masquerading won't accept virtual interfaces (eth0:0, etc) I am unable to get masquerading to work again (and I'm not even sure whether I need virtual interfaces).
Thanks.
Edit:
OpenVPN server:
# ifconfig
eth1      Link encap:Ethernet  HWaddr ba:e6:64:ec:57:ac
          inet addr:192.168.22.70  Bcast:192.168.22.255  Mask:255.255.255.0
          inet6 addr: fe80::b8e6:64ff:feec:57ac/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:6857 errors:0 dropped:0 overruns:0 frame:0
          TX packets:4044 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:584046 (570.3 KiB)  TX bytes:473691 (462.5 KiB)
          Interrupt:14

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:334 errors:0 dropped:0 overruns:0 frame:0
          TX packets:334 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:33773 (32.9 KiB)  TX bytes:33773 (32.9 KiB)

tun0      Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
          inet addr:192.168.200.1  P-t-P:192.168.200.2  Mask:255.255.255.255
          UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:100
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

ifconfig on a client:
# ifconfig
eth0      Link encap:Ethernet  HWaddr 00:22:64:71:11:56
          inet addr:192.168.110.94  Bcast:192.168.110.255  Mask:255.255.255.0
          inet6 addr: fe80::222:64ff:fe71:1156/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:3466 errors:0 dropped:0 overruns:0 frame:0
          TX packets:1838 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:997924 (974.5 KiB)  TX bytes:332406 (324.6 KiB)
          Interrupt:17

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:37847 errors:0 dropped:0 overruns:0 frame:0
          TX packets:37847 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:2922444 (2.7 MiB)  TX bytes:2922444 (2.7 MiB)

tun0      Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
          inet addr:192.168.200.30  P-t-P:192.168.200.29  Mask:255.255.255.255
          UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:689 errors:0 dropped:18 overruns:0 carrier:0
          collisions:0 txqueuelen:100
          RX bytes:0 (0.0 B)  TX bytes:468778 (457.7 KiB)

wlan0     Link encap:Ethernet  HWaddr 00:16:ea:db:ae:86
          UP BROADCAST MULTICAST  MTU:1500  Metric:1
          RX packets:704699 errors:0 dropped:0 overruns:0 frame:0
          TX packets:730176 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:520385963 (496.2 MiB)  TX bytes:225210422 (214.7 MiB)

static routes line at the end of the client's config (I've been playing around with the 192.168.200.0 -- (un)commenting to see if anything changes):
route 192.168.200.0 255.255.255.0
route 192.168.110.0 255.255.255.0
route 192.168.22.0 255.255.255.0

route on a vpn client:
# route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
192.168.200.29  0.0.0.0         255.255.255.255 UH    0      0        0 tun0
192.168.22.0    192.168.200.29  255.255.255.0   UG    0      0        0 tun0
192.168.200.0   192.168.200.29  255.255.255.0   UG    0      0        0 tun0
192.168.110.0   192.168.200.29  255.255.255.0   UG    0      0        0 tun0
192.168.110.0   0.0.0.0         255.255.255.0   U     0      0        0 eth0
0.0.0.0         192.168.110.1   0.0.0.0         UG    0      0        0 eth0

edit:
Weirdly enough, if I set
push "redirect-gateway def1"

in the server config, (and thus routes all traffic through VPN, which is not what I want), it seems to work.
Comment: Could you please post an output of `ifconfig` from your OpenVPN server? Also, a routing table from one of OpenVPN clients would be helpful too.
Comment: added in the original post
Answer: I see two possible problems here. First, you OpenVPN clients probably do not get static routes to your LAN from OpenVPN config. Next, it looks like your OpenVPN server is not a default gateway for your LAN hosts. So, you should add another rule to iptables to allow packets to route back to your OpenVPN server properly.
Something like this:
-A POSTROUTING -o eth1 -j SNAT -s 192.168.200.0/24 -d 192.168.22.0/24 --to-source 192.168.22.70
I assume 192.168.22.70 is a LAN address of your OpenVPN server.
Comment: 192.168.22.70 is the lan ip of the vpn server, yes
Comment: I've added the static lines in the client configs in the original post. As for your iptables line: iptables: No chain/target/match by that name
Comment: You should either add this line to the `*nat` section of the config you posted above or add `-t nat` to the list of params if you are adding the rule manually, like this:

`iptables -A POSTROUTING -t nat -o eth1 -j SNAT -s 192.168.200.0/24 -d 192.168.22.0/24 --to-source 192.168.22.70`
Comment: Right, sorry, so I have these two lines at the *nat section: -A POSTROUTING -o eth1 -j MASQUERADE +
-A POSTROUTING -s 192.168.200.0/24 -d 192.168.22.0/24 -o eth1 -j SNAT --to-source 192.168.22.70 -- correct? But I'm still unable to ping
Answer: Apparently VPN was working all the time from outside the office.
It was just not routing anything for people inside the 192.168.110.0 network (office).
vpn.domain.tld was pointing to 192.168.22.70 in the LAN.
By changing vpn.domain.tld to point to the public IP address of the VPN server the problem was resolved weirdly enough.
With public IP address I mean the address that's mapped to the Cisco firewall (91.220.102.x), and all packets are forwarded to the lan IP (192.168.22.70) of the VPN (see the layout in my original post).
VPN is not needed at the office, but as VPN starts as a service on Windows machines, I have not yet been able to control when it should start and when it shouldn't (ideally only when outside of the office -- but that's for later).
Thanks for all the assistance.

IPTables masquerading with one NIC


Missing handler error in AWS Lambda

Question: My apologies for basic question. I am completely new to AWS as well as Python. I am trying to do sample code given in https://boto3.readthedocs.io/en/latest/guide/migrations3.html#accessing-a-bucket but facing a error.
import botocore
import boto3
s3 = boto3.resource('s3')
bucket = s3.Bucket('bucketname')
exists = True

try:
    s3.meta.client.head_bucket(Bucket='bucketname')
except botocore.exceptions.ClientError as e:
    # If a client error is thrown, then check that it was a 404 error.
    # If it was a 404 error, then the bucket does not exist.
    error_code = int(e.response['Error']['Code'])
    if error_code == 404:
        exists = False

Error in logs is

"errorMessage": "Handler 'lambda_handler' missing on module
  'lambda_function'"
Comment: @halfer understood.
Comment: Possible duplicate - https://stackoverflow.com/questions/40741822/aws-lambda-python-handler-missing-on-module
Answer: You need to define a function in your code. The code is missing the function named lambda_handler. Your code should look like:
    import botocore
    import boto3

    def lambda_handler(event, context):
        s3 = boto3.resource('s3')
        bucket = s3.Bucket('bucketname')
        exists = True

        try:
            s3.meta.client.head_bucket(Bucket='bucketname')
        except botocore.exceptions.ClientError as e:
            # If a client error is thrown, then check that it was a 404 error.
            # If it was a 404 error, then the bucket does not exist.
            error_code = int(e.response['Error']['Code'])
            if error_code == 404:
                exists = False

Answer: Move your code inside a python function. You can give it any name but that will become your handler. Go to lambda function basic settings and change the default handler to <yourfilename>_<yourfunctionname>. By default when you create a lambda function, the file name will be lambda_function_name.py (you can change it) and your handler method will be lambda_handler (you can change it), so the entry point is lambda_function_name.lambda_handler.
Answer: Kishna_mee2004 is right you need to define lambda_handler without this it never work but if you getting below error:

Handler 'py' missing on module 'jobdata_rdcmedia_s3_Etl_job_scheduler_lambda': 'module' object has no attribute 'py'

Then you need to check handler info whether you have mention lambda_function_name.lambda_handler or not.

Missing handler error in AWS Lambda


Why does C allow you to assign a value to a struct variable using "var = (struct NAME){…}"?

Question: Before I thought I cannot assign a whole value to a struct variable.
This is actually wrong:
struct Student student1;
student1 = {"Andy", 18};

but I thought I can only use:
struct Student student1;
student1.name = "Andy";
student1.age=18;

Today, I found I could use the format below to do it, whith prefix "(struct Student)", but it is hard for me to understand:
struct Student student1;
student1 = (struct Student){"Andy", 18}; // it is ok

Comment: What exactly is your question? The syntax you discovered was introduced with C99 and is called a `compound literal`.
Comment: The syntax of compound literals is defined by C11 in [§220.127.116.11 Compound literals](https://port70.net/~nsz/c/c11/n1570.html#126.96.36.199).  They've been a part of C since C99.  You could also use `student1 = (struct Person){ .age = 18, .name = "Andy" };` using 'designated initializers" — see [§6.7.9 Initialization](https://port70.net/~nsz/c/c11/n1570.html#6.7.9).
Comment: You can also directly assign structures.  Given two structures in `struct Student a, b;`, you can assign a full structure: `a = b;`.  You can also return a full structure by value: `struct Student someFunc() { struct Student a; ... return a; }` and then `struct Student s = someFunc();`.
Comment: sorry typo "(struct Person)", it is actually "(strcut Student)"
Comment: thanks to Gerharh, "compound literal" I learn it.
Comment: This Q/A is quite informative despite being closed(!): https://stackoverflow.com/questions/61485211/practical-uses-for-compound-literal-expressions
Answer:
Why does C allow you to assign a value to a struct variable using "var = (struct NAME){…}"?

Because it is convenient and useful.

Before I thought I cannot assign a whole value to a struct variable.

This is not correct. It has been possible to assign to a structure since at least C 1990, such as a = b, where a and b are both structures of compatible types.
The form student1 = {"Andy", 18}; does not work because {"Andy", 18} does not form a structure. It is a brace-enclosed list with no type. The compiler would not know whether this is supposed to be a value for a structure of type struct { char a[80]; int b; } or a structure of type struct { char *a; float b; }.
In C 1999, compound literals were introduced, where you can write (type) { initializers… }. With the type supplied in this way, the compiler is able to interpret the values and use them to form a structure with a known layout. Then you can assign it using the existing assignment grammar, a = (type) { initializers… }.
Answer: In your third example you are creating an unnamed object. This doesn't work in your first example, because the type (and thus the size) of the unnamed object isn't known.
Note, that you can perfectly write:
struct Student student1 = {"abc", 20};
struct Student student2;

student2 = student1;

to assign a whole struct to another variable.
You can also use designated initializers:
struct Student student = {.age = 20, .name = "abc"};

It is also possible to use this syntax to initialize a pointer, by initializing an array.
struct Student * student = (struct Student []) {{"abc", 20}};

But pay attention to the storage class of the unnamed object. Otherwise your pointer might contain garbage, which will invoke UB.
Comment: @RobertHarvey: It is just imprecise writing; by "the type … of the object isn't known," Caulder means "the type intended for the thing on the right side of the assignment, `{"Andy", 18};`, is not known," not that the type of `struct Student` or `student1` is not known.
Comment: @AndrewHenle: FYI, in the forthcoming C standard, you can specify `static` for a compound literal. Or even `register`, `thread_local`, or `constexpr`.
Comment: You *can* write that, but by that time the "shape" (i.e. the type) of student1 and student2 are perfectly known.
Comment: @RobertHarvey The type must already be complete in order to declare the variables. How does that affect the snippet?
Comment: *But pay attention to the storage class of the unnamed object. Otherwise your pointer will contain garbage, which might invoke UB.*  There's no "might".  If the compound literal used to initialized the pointer goes out of scope, accessing the data the pointer refers to or the pointer itself **will** cause undefined behavior.  You can't [safely access the pointer value](http://port70.net/~nsz/c/c11/n1570.html#6.2.4p2): "The value of a pointer becomes indeterminate when the object it points to (or just past) reaches the end of its lifetime."
Comment: @AndrewHenle Yes, but the storage class determines when the object goes out of scope.
Comment: The storage class of the pointer is irrelevant.  And [you can't specify the storage class of a compound literal](http://port70.net/~nsz/c/c11/n1570.html#188.8.131.52p5): "If the compound literal occurs outside the body of a function, the object has static storage duration; otherwise, it has automatic storage duration associated with the enclosing block."
Comment: @AndrewHenle I don't see a contradiction, as I was talking about the storage class of the unnamed object, which defines, when it goes out of scope, which in turn determines whether an access through the pointer is UB or not.
Comment: @Caulder: Re "which in turn determines whether an access through the pointer is UB or not": Yes, it **determines** whether the behavior is undefined. You wrote "might." It is not "might"; it is determined. Definite. Fully specified. The behavior of using a pointer to an object whose lifetime has ended is absolutely positively not defined by the C standard.
Comment: @AndrewHenle Agreed. Have swapped the verbs.


Weighing Questions within a Survey

Question: I work for a public child welfare agency. We have something called a level of care tool that categorizes children based on the amount of care they need. This helps us identify appropriate care options for the child. A level of care 1 is a child who needs the "standard" amount of care (these are usually children who are not developmentally delayed, who do not have severe behavioral issues, and so on). A level of care 10 is a child who needs constant care.
The level of care tool that categorizes these children is essentially a survey about behavioral issues, diagnoses, history of trauma, and delays, as well as strengths.
We are re-designing the survey to more accurately reflect the needs of children, and I have been asked to help assign weights to the questions so that the categorization is accurate. I don't have a PhD or even a masters in survey design, psychometrics, or item response theory and feel a out of my depth. Is there anyone out there who has worked on something similar and can share their approach? Are there any books or articles that you'd recommend?
Comment: Hi @ra_learns, welcome to CV! While I probably can't be very useful with a response, perhaps you can clarify, in the question, what _"I have been asked to help assign weights to the questions so that the categorization is accurate."_ means. For example, you have a bunch of questions which you then use to generate the Level of Care? And they questions relative to Level of Care in what way at the moment? This is a bit unclear to people (like me) who don't work in your field
Answer: Preamble
It is possible to incorporate item-level weights (e.g., a correct response to item 1 is worth 2 points, a correct response to item 2 is worth 1 point, etc.) within an item response theory (IRT) framework. However, I must say that this is a rather advanced application of IRT, so you may need to look for external help. The difficulty mainly comes from the fact that doing this would take extensive programming that requires precise knowledge of the intricacies of IRT, as no software I am aware of can do this on its own (though still with easy to use software this task would be difficult).
Your Question
Yes, assigning weights to items is possible. This can be done by extending the Lord-Wingersky algorithm (Lord & Wingersky, 1984). Generally speaking, the Lord-Wingersky algorithm is a way to obtain IRT scale-scores that correspond to number correct (or sum) scores. Implicit to the original formulation of this algorithm is that each item is equally weighted (i.e., a correct response is weighted equally). Without going into too much detail, the algorithm can be modified to weigh items however one wants. Stucky (2009) does something similar in his master's thesis, though he differentially weighs sections of a test, as opposed to individual items. For a general introduction to the algorithm, I recommend Stucky (2009), as well as Cai (2015) and Huang & Cai (2021).
References
Cai, L. (2015). Lord–Wingersky algorithm version 2.0 for hierarchical item factor models with applications in test scoring, scale alignment, and model fit testing. Psychometrika, 80, 535-559.
Huang, S., & Cai, L. (2021). Lord–Wingersky Algorithm Version 2.5 with Applications. psychometrika, 86, 973-993.
Lord, F. M., & Wingersky, M. S. (1984). Comparison of IRT true-score and equipercentile observed-score" equatings". Applied psychological measurement, 8(4), 453-461.
Stucky, B. D. (2009). Item response theory for weighted summed scores (Doctoral dissertation, The University of North Carolina at Chapel Hill).
Comment: Thank you so much for these references and for your helpful insights, Preston. I have begun the journey of reading these articles. I so appreciate your time and assistance.
Comment: @ra_learns No problem, I'm glad I could help!
Answer: I agree with @Preston Botter that this is an advanced application of IRT and support the advice that you might want to look for consultation.
However, I am aware of a possible realization. The R package TAM provides a (not officially supported/documented) solution for this issue using the so-called Q-matrix (quite possible that the following idea works for other software packages as well).
First, note that in case of the 2 parameter logistic model the loading structure of the factor loadings (discrimination parameter in IRT) is estimated in order to best fit the data. More importantly, the discrimination parameter (B-matrix in TAM) is the relative weight of the respective items in the total score.
Next, the Q-matrix is typically used as a binary matrix for assigning the loading of items to different latent dimensions. However, in TAM it is possible to assign values other than zero or one to the Q-matrix. The values of Q are multiplied to the factor loadings (discrimination parameter in IRT; 1 in case of the Rasch model). Thus, we can force a loading other than 1 to items in the Rasch model (or multidimensional versions thereof).
> library(TAM)
> data(data.sim.rasch)
> data.sim <- data.sim.rasch[, 1:15]
> head(data.sim)
     I1 I2 I3 I4 I5 I6 I7 I8 I9 I10 I11 I12 I13 I14 I15
[1,]  1  1  1  1  1  1  0  1  0   1   1   0   0   1   1
[2,]  0  1  0  0  0  1  1  1  0   1   1   1   1   1   0
[3,]  1  1  1  1  1  1  1  1  1   1   1   1   1   1   1
[4,]  1  0  1  1  0  1  1  1  0   0   1   1   1   0   0
[5,]  1  1  1  1  1  1  1  1  0   0   1   1   1   1   1
[6,]  1  1  1  0  0  1  0  0  0   0   0   0   0   0   0
> mod1 <- TAM::tam.mml(resp = data.sim,
+                      Q = data.frame("Loading" = c(rep(.5, 5), rep(1, 5), rep(2, 5))),
+                      verbose = FALSE)
> mod1$item
    item    N      M   xsi.item AXsi_.Cat1 B.Cat1.Dim1
I1    I1 2000 0.8270 -1.6257163 -1.6257163         0.5
I2    I2 2000 0.8145 -1.5382826 -1.5382826         0.5
I3    I3 2000 0.8000 -1.4422434 -1.4422434         0.5
I4    I4 2000 0.7860 -1.3542285 -1.3542285         0.5
I5    I5 2000 0.7725 -1.2731382 -1.2731382         0.5
I6    I6 2000 0.7710 -1.3979913 -1.3979913         1.0
I7    I7 2000 0.7430 -1.2253834 -1.2253834         1.0
I8    I8 2000 0.7435 -1.2283610 -1.2283610         1.0
I9    I9 2000 0.7295 -1.1462542 -1.1462542         1.0
I10  I10 2000 0.6945 -0.9509658 -0.9509658         1.0
I11  I11 2000 0.6905 -1.2062157 -1.2062157         2.0
I12  I12 2000 0.6615 -1.0102233 -1.0102233         2.0
I13  I13 2000 0.6515 -0.9443237 -0.9443237         2.0
I14  I14 2000 0.6415 -0.8791659 -0.8791659         2.0
I15  I15 2000 0.6000 -0.6152801 -0.6152801         2.0

A word of caution: I'm not sure of what will happen if both, relativ loading structure via Q-matrix are given and discrimination parameter are estimated.
Comment: Q matrices are present in IRT models as well in order to model multidimensional IRT models; also TAM is the IRT tool in Alex' package framework (that does indeed include the CDM package as well; which makes greater use of the Q matrix); thanks for the +1!
Comment: +1 Good idea @Tom. I was not thinking about diagnostic classification models (because the question referred to IRT) - though still good idea!
Comment: Thank you so much Tom! This is very helpful as I do program in R primarily. I appreciate your time and assistance!

Weighing Questions within a Survey


Find if a textbox is currently selected

Question: How would I find if a textbox (or textarea) currently is in focus? I don't care to know which one it is, I just need to know if one is in focus (has the cursor in it). How would I do this with javascript and jquery?
Answer: Since you have found document.activeElement, you can check its nodeName.
if (document.activeElement.nodeName == 'TEXTAREA' || document.activeElement.nodeName == 'INPUT') {
    // ....
}

Something like that.
Comment: Thanks, but how do I get the jQuery object from document.activeElement?
Comment: This does not check for editable HTMLDivElements. See my answer below.
Answer: Ok, just figured it out. Here's what I did:
function checkFocus() {

  if ($(document.activeElement).attr("type") == "text" || $(document.activeElement).attr("type") == "textarea") {

  //Something's selected

  return true;

 }

}

Comment: you're the only one who *can* mark this as the answer. Also, take a look at the [Stack Overflow Markdown help-page](http://stackoverflow.com/editing-help/), for guidance on how to format your answers, particularly code samples.
Comment: Someone mark this as the answer, it says I have to wait 2 days. :)
Comment: Note that this will work on all modern browsers, but it will *not* work on many outdated browsers.  Have a look at [this answer](http://stackoverflow.com/questions/1009777/determining-which-element-has-focus/1009787#1009787) for a technique to overcome this.
Answer: Extending the accepted answer by a check for editable HTMLDivElements:
if (document.activeElement.nodeName == 'TEXTAREA'
    || document.activeElement.nodeName == 'INPUT'
    || (document.activeElement.nodeName == 'DIV'
        && document.activeElement.isContentEditable)) {
    // …
}

Answer: $('#yourTextAreaID:focus');

would not work. :)  But
$('#yourTextAreaID').focus(function(){
    // do something
});

would excecute the //do something code when the element receives focus.
Comment: I don't recognise the `:focus` pseudo-selector, and nor does the API or a quick test...
Comment: Ok, but at any given time (not neccesarily when the user clicks a textbox) how would I check if any textbox has focus?
Comment: Given that the OP doesn't care "which one it is," I'd suggest amending the selector to: `$('textarea:focus, input:text:focus')...`
Comment: I just found document.activeElement. How would I check if that is a textbox or textarea?
Comment: @David Thanks, that's cleaner.
Comment: @lonesomeday, interesting catch: since it works under CSS I'd never thought to question whether or not it worked under jQuery.
Answer: $('#target').focus(function() {
  alert('Handler for .focus() called.');
});

Also Try:
alert($("*:focus").attr("id"));

http://jsfiddle.net/4KVvV/
Comment: as @lonesome pointed out above, :hover is not a real jquery selector.  I thought it was too, but when I checked the documentation, I couldn't find it mentioned.

Find if a textbox is currently selected


Monotouch socket problem

Question: BeginSend function does not throw exception when I disconnect iPad from Network. Interesting thing is that OnSend callback function calls and result.
Iscompleted returns true.
If I call another overloaded function with error code, it always return success
tcpAsyCl.BeginSend(
             write_data,
             0,
             write_data.Length,
             SocketFlags.None,
             out error,
             new AsyncCallback(OnSend),
             null);

if (error != SocketError.Success)
      throw new Exception("Not connected"); //never goes her

Does anyone know this behavior?
Answer: as It's an async call! You can't verify the result in the line below... I'm sure you have a method that you can hook up to get the correct error.
Asynchronous calls are created in a new thread and it's there that you need to wait for the answer. Not in your main thread, or that would be a Synchronous call.
here is a list of all methods that you can use
I would strongly suggest that you take a deep look at this document

Using an Asynchronous Client Socket
Comment: When I use this form it never throw exception. tcpAsyCl.BeginSend(write_data, 0, write_data.Length, SocketFlags.None, new AsyncCallback(OnSend), null); But under Windows it throw exception when netwrok unavailable.In iOS I can't fix the disconnected status.
Comment: all your errors will be in the `OnSend` callback as that's where you tell the Async method to return info to, you can use a delegate instead a method. See link on updated answer.
Comment: Add the linked document with all the code and explanation that you need for using `System.Net.Sockets` in an async call
Comment: I try this metods but didn't help me.When I disconnect device from network it continues send data an in OnSend client.EndSend(result) return 14 byte during disconneced time.

Monotouch socket problem


I want to learn how to sing. Where do I start?

Question: According to a couple of websites, the best way to learn how to sing is with a vocal teacher, a recorder, and practice. But let's say I don't have the means to get a vocal teacher right now. What other resources are available to me that I can use to sound better?
I'm not shooting for opera singer mastery, but rather, just enough to not sound horrible when I sing "Blackbird" by The Beatles.
Any tips, suggestions, or suggestion that a vocal teacher is the only way to go are welcome.
Comment: You should scrounge up for at least one or two lessons to get guidance on breath-support and tone-quality. After that, you can be allowed to safely pursue your own course of study. :)
Comment: The answer to this question is simple... 'Get a teacher.'
Answer: As @luserdroog said in the comments, it would be best if you could get at least a couple lessons.  Otherwise you risk learning bad habits with the physical aspects (that can't be taught well except in person) that you'll have to un-learn later.
Another approach is to join a community choir.  While some choirs require auditions, others do not (particularly church choirs, but not exclusively religious).  The choirs I've sung in have included work on technique, not just learning the repertoire.
Comment: __Relax__.  Don't discourage him from practicing "because he's going to learn bad habits."  That's like saying to a kid who wants to play basketball, "don't practice before you make the team, because you're going to teach yourself bad habits."  Actually having practiced before seeing a teacher will make what the teacher says make a lot more sense/have relevance/be _easier_ to learn.
Comment: @bobobobo, I agree with you to a point. But you don't want to wait long before seeking a lesson or three from a teacher. Certainly don't begin heavy practicing in earnest without seeking a teacher's advice. I don't think it'd be good advice to NOT practice… but take it easy, so you don't harm your voice.
Answer: Let me offer a serious suggestion that has been a popular method of learning to sing for people for many generations: Attend church services on Sunday mornings at a Christian church and sing along with the hymns. Find a church whose congregation sings traditional church hymns from a hymnal book.
This style of church music deliberately uses simple melodies in simple rhythms, with a narrow range of pitches that are easy for non-trained singers to sing. Once you get comfortable with it, you can try learning one of the four-part harmony lines in the hymn arrangements. This will be your introduction to harmonizing.
If you feel comfortable after awhile, ask to join the church choir. Then you can start learning more demanding and challenging vocal music, and you will have an opportunity to learn, practice and rehearse with some structure and some goals in mind, every Wednesday night and Sunday morning, for free.
It doesn't really matter if you are a Christian or not, or whether you believe the message in the lyrics or not, although it helps. All sorts of musician have gotten their start this way for centuries.
Comment: It is a bit weird for an athiest, though. One other options that I've heard of, and been meaning to try, is a workers' choir. There's one in most large cities, I think. Of course, then you might be uncomfortable if you don't share the politics, which can be just as weird as religion, sometimes :)
Answer: A (pretty cruel) way to learn is to record your own voice.  I use Audacity a lot.
First I record a base track (an existing recording, or just me going something like pfw tchk tchk tchk pfw tchk tchk tchk ....
Then I'll rewind and sing along, starting over and over until I'm confident I can record it without getting completely lost in the middle.
Then I'll do the same but with the record button pressed.  Again, I keep rewinding (and erasing the recording) until I'm reasonably happy.  By this time, I may still not be able to sing the song very well but I'll certainly have learnt a whole lot about how to sing it.
This will only work if you don't need anyone else to tell you how your part fits in with the prerecorded track, and if you have a tremendous amount of patience with yourself.
And it's never going to replace singing with others, so do that, too.
Comment: Yup, exactly.  What you're saying is __practice__ and "close the feedback loop".  Another thing you can do is stick your finger in your ear while you're singing, so you can hear yourself.  This is a really noob thing to do, but it kind of works to start.
Comment: Another thing I do is have a recording device with you. It doesn't have to be hi fi, but I use an Edirol.
Comment: A similar programme which I like is Capella Melody Trainer, which runs under MS Windows or in Wine on Linux, but it has only a German UI (as far as I can see).
Answer: Andrew, I don't believe anyone can teach you how to sing. You have to teach yourself - the same way that you learned how to eat and speak and walk. You have to find your singing voice and then develop it – just like you found your balance on two legs and then learned how to run. Also you cannot be shy about it - it won't work if you are.
The best way to sing is to try and try often, in 5 to 10 minutes bursts. The shower or bathroom is a fun place to make singing sounds and listen to them because it is very resonant.
All singing is produced on vowel sounds. Consonants don't have pitch. Some consonants like M and N are produced through a pitched hum - but that is not exactly singing. You need to work on what goes on in singing vowel sounds with your body.
Take a breath, think of a word like "who", "where", or "whah", say it out aloud and don't allow the vowel sound to finish. Keep the sound going (or resonating) for as long as possible - even after the count of one second you will be singing.
Try to extend the sound. Imagine the sound stretching or streaming out into the next room. How long can you sustain the sound? Notice that your stomach starts to tighten a bit - that is your diaphragm muscle kicking in to support the sound. Aim for holding the vowel sound for as long as possible while staying relaxed. Count in seconds in your head and keep a record of your progress.
Once you get the hang of extending the vowel sound focus on listening to the qualities of it - eg. volume (can you produce loud or soft?); pitch range (can you make the sound high or low?); pitch constancy (can you hold one pitch? Can you visit other pitches in the same breath?)
In addition to noticing your diaphragm move, think about your jaw, lips, tongue, cheeks and upper palate. Are they relaxed? What size and shape is the cavity inside your mouth? What happens to the sound if you change it? Make very small changes to consider the effects. Does it please you?
Next consider your nose, eyes, eyebrows, face, head and neck. Where are these positioned? Do they move? Are they relaxed? What happens if you raise your eyebrows? Close your eyes? Imagine your head has an invisible string lifting you straight up. Does it make a difference?
Move on to thinking about the rest of your body. Where are your shoulders, back, arms, bottom, hips, legs and feet? All these body parts have an effect on your sound. Experiment by moving these body parts differently. What happens?
Pay attention to your emotions too. Do you feel happy? relaxed? tense? anxious? angry? Ultimately singing should make you feel positive - in either a happy, envigorated or relaxed kind of way. If you don't feel uplifted, keep trying different body moves.
After you get a feel for your voice on single pitches or notes apply your knowledge to any song you know. Think about the vowel sound of every word sung and aim for the loveliest version of each one that you can muster. Sing a line at a time. Consider how you attack each word – particularly at the start of a phrase. Try to hit the opening note in the middle of its sweet spot. Also explore what it is to swoop up or down to a note - not always desirable but sometimes interesting.
Practice, Practice Practice - every day.
And enjoy it.
When you feel confident, join a community choir.
Learning to read music is also helpful, as is learning to play a pitched instrument like piano or recorder.
Answer: My recommendation is to wait till you can get the time to attend a teacher's class, but at the same time, try to increase your musical knowledge, about reading.
I know an audiobook (100% free) which is called how to sing. You can get this book (text can be downloaded from Gutenberg Project), and you can get some idea and knowledge about singing. Also you might take a look at Music Notation & Terminology.
Comment: @bobobobo, people have been singing for a lot longer than 96 years. I don't see the book's age as a valid reason for criticism. And there's no strong reason to trust Amazon's ratings. You might be right, but you need a better argument...
Comment: -1 While the text you linked is very nice linking to it would be a nice _comment_, this _isn't_ good advice as an answer.  Do you really think one should begin by reading a book from 1916?  I browsed the text and it would make little sense to me if I hadn't already attended classes by a music instructor.  There are [plenty of newer books](http://www.amazon.com/The-Structure-Singing-System-Technique/dp/0534255353/) are 4.5-5 star reviewed on average, on Amazon.
Comment: @naught101 My criticism isn't on the contents of the book and I'm not addressing the possibility that it may be _wrong_, but rather on the presentation of the text (which is archaic and hard to read). Just try and read the text yourself. It's not good studying to learn from something that's hard to grok while there are much more suitable books out there written in modern English. That book is a piece of history that IMO is to be enjoyed by experienced musicians who really feel like a tour down history's past, not something a beginner should learn from.
Comment: @bobobobo: I think the problem with the Lilli Lehmann (How to Sing) is not so much the age (I see English 1902, German 1900!) as that it seems to be a rather stilted translation from the German.
Answer: I would recommend you research Speech Level Singing.
Look at youtube videos of Brett Manning and Seth Riggs.
There are many good vocal coaches out there but also many bad ones. Many classically trained vocal coaches will tell you to push you diaphram, which can be harmful to your vocal chords. I had a teacher that would always tell me "Singing is an athletic exercise!". It's not, it should be very easy. You should never feel tension.
Basically, you need to record yourself and practice often. If your like me, you will hate the sound of your own voice at first. Don't worry, you will get better. Most importantly, don't hurt yourself. If you find a teacher that claims singing is "athletic", find a new teacher.
Answer: Just sing frequently, with and without your favorite songs playing :P.  If you're tone deaf like I used to be then I highly recommend interval training.  Once you're able to recognize when you are off-key then you can start correcting it, and you need to practice a lot to develop the musculature and control needed. Constant practice like this has changed me from terrible singing to passable, though I do wish I had time for lessons.
As an aside, Blackbird was the first song I learned on guitar and the first I sang for someone while playing as well.  Good choice :P
Comment: @iamcreasy http://en.wikipedia.org/wiki/Off-key
Comment: "recognize when you are off-key..." - What's the meaning of 'key'?
Comment: Would better English not be recognise when you are singing false? We need to be specific with terminology when dealing with newbies.
Comment: @NeilMeyer: 'out of tune' seems to me best, assuming that is what is meant. The Wikipedia article is not that helpful, as it refers to a means of expression as much as to a technical deficiency.
Answer: Man, I've seen a lot of questions here like that and I think the best way is to get an teacher. It is my oppinion. I think we can learn by ourselves but an experient teacher can make you progress faster and in the correct way.
There's some tricks that we just learn with time and teachers can pass it to you in a better way/moment.
Consider take some lessons.
Answer: I'm going to say it's close to impossible for anyone to teach you to sing, but reasonable for someone to help you sing better. Start on your own. Second, anyone who sings period, even those not as good as you, can help you.
Here are some tips, though...
Can you match pitch? If so, just try singing single notes, you don't even have to know how to play piano, just hit one random key at a time try to sing the pitch. (A good place to start is the middle of the piano and go up if you're a female or down if you're a male.) Also, sing what you like. It's a lot easier to do something that you enjoy. I don't enjoy basketball, so I don't play/practice it. That doesn't mean I don't get any exercise whatsoever, though. I just do what I find enjoyable.
And, I'm going to say "no", you don't need a vocal teacher. I'd sung since I was (5, maybe?), and in tune, but didn't get a vocal teacher until I was 11.
3 bad habits to avoid would be: (don't worry too much, though... a lot of good singers do this)
Clearing your throat. It grinds your vocal folds together. (I'm guilty of that. ) Don't even think about it. It makes you want to. Also, don't sing way out of your comfortable range. Who isn't guilty of this? Many popular male singers (me too) sing way higher they probably should. Don't drink anything but water before, and don't eat anything sticky/sweet before. It makes it harder to sing and reduces your vocal range.
4 good habits would be:
If a song is too high: Use your resonant (so-called "head") voice. It can increase your range about a half octave. (6 semitones exactly, for me) If you have no idea what I mean by head voice, look it up. It's a bit hard to explain. The other option is to sing louder (but don't yell) if it is too high. My head voice is very weak, so I sing loud instead. Also, make your consonants clear. (I'm guilty of this one, too! ) If you sing into a mic, probably want to use the soft spongy covers for it if you get into this habit. That way you're s's won't make everyone cringe from the high pitch. Don't freak out if you suddenly sound terrible on one note. The closer you are to being on the correct note the worse it sounds, until our ears can't hear the difference. And warm up first. Even if that's singing a scale.
A habit I have is to make my voice sound like the singer. (Or sing with someone who sounds like you.) This makes it easier to sing in tune, since the sound waves match more accurately. I sound a lot like TobyMac (you probably don't) and I have a similar vocal range (mine's a little higher), so I sing his songs a lot.
In terms of memorization, think of a song in a simple sequence. If I were trying to memorize the pre-chorus of "Beyond Me", I would think "first stars, then water, then need, then see." I learn new songs in under a week this way. (And old songs in 24 hours on the high end.)
One last point, and this is a big one. In general, if you are doing anything for your own pleasure, keep in mind you don't have to be good. (Although I know how great the "being good" feels.) The only person you'd be in competition with is yourself and yourself past, and you'll always be better than your past as long as you keep practicing, just as good as your are now. Instead of saying, "Holy cow, I'm bad at this," say, "It was[...] not bad, but there's always some room for improvement." And no one better than you would say you're bad at something. If someone says you're not good, they're not any better than you at that or something else. And anything is possible.
P.S.: I'm a believer (I guess you could call me a "Jesus Freak") and I'm not a huge fan of hymns, so that might not be a great place to start.
Answer: Try www.karaokegarage.com. It helps you sing along with the song and detects your pitch as you sing. It should be a good starting point for anyone to practice and gauge their singing level from.
Answer: People ask this question for several reasons. One is they like to sing and play instruments and become musicians. They fear that this is some kind of talent that only a few people got. I have some reasons to help those who like to be musicians and singers. These have helped me to think otherwise.

Can you identify the caller on your phone? Then you can identify music notes. If you can identify notes then you can sing. If you can sing a note then you can play an instrument. Very soon you will be performing on stage and get ten out of ten or all three Yes from the judges. Let me clear you.
First take this practical test which I found useful on YouTube. You will know where you stand:

People say they cannot identify notes to play or sing. We are going to help them to step in to the musical family. There are many who are not quite sure if they have built up their ears to sing or play or to identify the notes. I do not think you have toned-deaf. If I can sing and play you too can.
People think they cannot play or sing and cannot recognize notes. They also say they cannot enjoy a tune. I do not think like that. I am certain that you are not tone- deaf.
From the time you were born you started picking little words. At that time you could not speak advance words. You could not have a conversation with someone, because you were still a baby. When you grow up gradually you picked up things little by little. You picked the right words and you started having conversations or dialog with somebody else.
When you make a phone call the moment you pick up the phone, you can recognize the caller's voice. If you can recognize a voice then you can recognize a musical tone or music note.
Best thing you can do is to go to a piano play a note. For example C note and then play it for an half an hour. Then get that particular note or tone to your year. Then you are able to recognize the C note after awhile.
Some say they can play but they can't pitch the note. What is the solution for those people? Now you pick up a simple tune like happy birthday. If you can play definitely you will be able to sing it.
Some say they can sing but can't play. This is not true. If you can sing a note definitely you should be able to play that same note on the instrument.
Some recognize notes and enjoy a melody, but say they can't sing or play. I say you can sing and you can play. If you just follow the proper singing lessons and proper instrument basics, you can sing and play. It is not difficult but simple.  All you have to do is to put some effort.  Just to practice and that is all what matters.

Start practicing four to eight hours a day you will get there.
For good music lessons: https://www.rockatar.com
https://www.rockatar.com


For which values of the parameter $ a \in \mathbb{R}$ is the transformation $T(x,y,z)=(x+ay,x-ay,x+z)$ an isometry?

Question:
Find the eigenvalues and eigenvectors of the linear transformation $T(x,y,z)=(x+y,x-y,x+z)$. Verify that the eigenvectors are orthogonal.

$$T(x,y,z)=\begin{pmatrix} 1 & 1 & 0 \\ 1 & -1 & 0 \\ 1 & 0 & 1 \\ \end{pmatrix}\begin{pmatrix} x \\ y \\ z\\ \end{pmatrix}$$
\begin{equation*}
\begin{split}
det(T(x,y,z)-I_n \lambda ) & =\begin{vmatrix} 1-\lambda & 1 & 0 \\ 1 & -1-\lambda & 0 \\ 1 & 0 & 1-\lambda \\ \end{vmatrix} \\
& =(1-\lambda)\begin{vmatrix} -1-\lambda & 0 \\ 0 & 1-\lambda \\ \end{vmatrix}-\begin{vmatrix} 1 & 0 \\ 1 & 1-\lambda \\ \end{vmatrix} \\
& =(1-\lambda)^2(-1-\lambda)-(1-\lambda) \\
& =\begin{vmatrix} 1-\lambda & 1 & 0 \\ 1 & -1-\lambda & 0 \\ 1 & 0 & 1-\lambda \\ \end{vmatrix} \\
& =-(1-\lambda)[(1-\lambda)(1+\lambda)+1] \\
& =-(1-\lambda)[1-\lambda^2+1] \\
& =(\lambda-1)[2-\lambda^2]=0 \\
\end{split}
\end{equation*}
Hence $\lambda=1, \pm \sqrt{2}$.
$\lambda=1$: $\begin{pmatrix} 0 & 1 & 0 \\ 1 & -2 & 0 \\ 1 & 0 & 0 \\ \end{pmatrix} =\begin{pmatrix} 1 & 0 & 0 \\  0 & 1 & 0 \\ 0 & 0 & 1 \\ \end{pmatrix}$
Hence the eigenvectors for $\lambda =1$ are $\{ (1,0,0)^T, (0,1,0)^T, (0,0,1)^T \}$.
$\lambda=\sqrt{2}$: $\begin{pmatrix} 1-\sqrt{2} & 1 & 0 \\ 1 & -1-\sqrt{2} & 0 \\ 1 & 0 & 1-\sqrt{2} \\ \end{pmatrix} =\begin{pmatrix} 1 & 0 & 1-\sqrt{2} \\  0 & 1-\sqrt{2} & 1-\sqrt{2} \\ 0 & 0 & 0 \\ \end{pmatrix}$
Hence the eigenvectors for $\lambda =1$ are $\{ (1,0,0)^T, (0,\sqrt{2}-1,0)^T, (1-\sqrt{2},1+\sqrt{2},0)^T \}$.
$\lambda=-\sqrt{2}$: $\begin{pmatrix} 1+\sqrt{2} & 1 & 0 \\ 1 & -1+\sqrt{2} & 0 \\ 1 & 0 & 1+\sqrt{2} \\ \end{pmatrix} =\begin{pmatrix} 1 & 0 & 1+\sqrt{2} \\  0 & -1+\sqrt{2} & 1+\sqrt{2} \\ 0 & 0 & 0 \\ \end{pmatrix}$
Hence the eigenvectors for $\lambda =1$ are $\{ (1,0,0)^T, (0,1-\sqrt{2},0)^T, (1+\sqrt{2},1-\sqrt{2},0)^T \}$.

For which values of the parameter $ a \in \mathbb{R}$ is the transformation $T(x,y,z)=(x+ay,x-ay,x+z)$ an isometry?

$$T(x,y,z)=\begin{pmatrix} 1 & a & 0 \\ 1 & -a & 0 \\ 1 & 0 & 1 \\ \end{pmatrix}\begin{pmatrix} x \\ y \\ z\\ \end{pmatrix}$$
How do I find the values? I know the definition of isometry is $\|Tx\|=\|x\|$.
Comment: That is not the definition of an isometry. The definition of an isometry for a linear transformation $T$ is $|Tx|=|x|$.
Comment: I am sorry I type it in wrong.
Answer: Just evaluate $Tx$ and expand out the norms in the equation $\| Tx \| = \|x \|$ (and square to make it nicer); you need precisely that for all $x,y,z$,
$$(x+ay)^2 + (x-ay)^2 + (x+z)^2 = x^2 + y^2 + z^2.$$
Also note that part (a) implies that $a=1$ can't be a correct answer, as the eigenvalues of an isometry have modulus one.
Comment: \begin{equation*} \begin{split} x^2+y^2+z^2 & =(x+ay)^2+(x-ay)^2+(x+z)^2 \\ & =x^2+2xay+a^2y^2+x^2-2axy+a^2y^2+x^2+2xz+z^2 \\ & =3x^2+2a^2y^2+2xz+z^2 \\ \end{split} \end{equation*} So $2a^2y^2=y^2$ and $3x^2+2xz+z^2=x^2+z^2$, which is fine but I get $3x=x$ from $x^2+z^2$.
Comment: Yep, and setting $x=1$ gives a contradiction - the question doesn't say there has to be any values of $a$ that work.
Comment: Ok perfect that makes sense. Thank you.


multi v-drum modules, one setup

Question: What I would like to know is: would it  be possible  to run two separate drum set modules from the same trigger set? Meaning, say, if I had a TD 7 and a TD 11 module but only one drum set and say I  set one module to trigger at 0 to 63 velocity and the other to trigger at  64 to 127 velocity, is this possible? How  would I set it up? Would I need more equipment or software etc.? First and foremost would this even be implementable, or am I just overlooking some  simple thing?
The background is: I own a TD 11 now and I previously owned a TD 7 and I'm quite disappointed in Roland; with the TD 11 I miss  several of the features the TD 7 had like sample triggering dual zone pads etc. I'm sure the TD $2000.00+ models are feature rich  but I just  can't ever see myself ever being able to  look at  let alone purchase one. I have Ableton Live 9 and also Reaper for Daws if that helps any.
Answer: They use a 1/4" jack right? I don't see any reason why you can't use a Y cable out of each trigger pad into each brain
Answer: It can be done, but it may not work that way with these particular two modules.
If I were doing this (and if I understand your need correctly), I would normally use a MIDI filter to have each module only respond to MIDI events of a certain velocity range.
One issue, though, is that the TD11 does not have a MIDI input, only output. So you could send MIDI out from the TD11 to MIDI of the TD7 with a MIDI filter in between.
The problem is that the TD11, as far as I can tell, does not have any sort of internal MIDI filtering. That leaves you without any way to control whether the TD11 gets triggered by one velocity or another.
A method could be created with more devices, but it depends on the end result you want, and it might add a painful level of complexity that takes away from precious playing time.
If all you're trying to accomplish is to use sounds from both modules at once without them triggering together, a simpler solution could be to add some pads to your kit and route those only to the TD7, so you could just play the pads you want when you want them.
Answer: I've done something simlar with a TD-8 for the pad triggers, and a Boss (Roland) DR660 (ancient) drum machine.
I just ran a MIDI cable from the TD-8 to the DR660 and set the midi channels to be the same (15 I think - the default drum channel). A strike on a pad triggers them both at the same time. On the whole, the notes match up (eg a snare on one is a snare on the other) but of course you coudl program a drum kit on either to respond with whatever combination you like.
Regarding the velocity separation: The DR660 has a 'curve' setting so you can set a bank of sounds (a kit) to only respond to the lower half of the velocity range. However the TD-8 doesn't have that feature so far as I'm aware, so it plays all the volume range.
Actually I found the best sounding setup was to just have them both play at all the volume range, so they complement each other - especially the snare and the ride/crash cymbals.
If I wanted to achieve what you're describing, I'd set the DR660 to only respond to the lower half of the volume range and perhaps put an audio noise gate on the TD-8 to cut the lower half of the range out.
Alternatively, there may be MIDI devices which can split signals out by volume.

multi v-drum modules, one setup


Image of old metronome with faster tempo markings

Question: This is a link to an image of an old metronome I found on the internet: https://fineartamerica.com/featured/2-detail-of-an-old-mechanic-musical-metronome-stefan-rotter.html
It uses the following tempos for words:

Largo: < 70
Larghetto: 70-98
Adagio: 98-125
Andante: 125-154
Allegro: 154-182
Presto: > 182

All modern tempos would be slower than this (except Presto). How does one make sense of this?
I know about the double beat theory, but 91 for the max speed of allegro is really slow.
Comment: It's all style and personal choice.
Answer: This is a great question! From the looks of it, it seems it was from Beethoven's time. As a rule, Beethoven's metronome markings indicate quicker speeds in the slow movements than we hear today. In the fast movements, the prevailing tempos are likewise brisk, though not as fast as legend would have it and in some cases, they are downright slow.
There seem to be three general reasons these markings have been so readily ignored. One is that performers, clinging to their interpretive prerogatives, have chosen to take expressive markings and tempo indications less seriously than the notes themselves.
That tradition, several recent musicologists have persuasively argued, has seen a steady entropy of tempo over the past 200 years. In other words, Western classical music has slowed down. There are cosmic explanations for this phenomenon: tempos have slowed out of a search for mystical profundity, or from the need to insert ever-more-niggling expressive nuances, or from a sheer loss of vital energy in our culture.
Source: This
Comment: Just a bit of anecdote: Once upon a time I was hired as a ringer for a college orchestra to fill out the bass section. I picked up CDs of the pieces we were to play to prepare before showing up at rehearsal. The tempos on the recordings were noticeably faster than what we performed in the orchestra. It did make my job a lot easier, at least.
Answer: Haversine's answer makes some good points, but the problem is broader than just a "slowing down" historically.  The real issue is that the correspondence between the Italian tempo terms (which originated as stylistic terms too for performance and interpretation, not just tempo) and the metronome markings has always been inexact.  Metronome manufacturers created these arbitrary scales themselves, and different manufacturers prescribed different ranges for these Italian terms.

Just for some datapoints, take a look at this article, which discusses actual tempo measurements as recorded by a musician in the year 1800 using a pendulum device (before the metronome was invented).  He was literally recording, for example, the tempo of how some of Haydn's pieces were performed within Haydn's lifetime.
Anyhow, the appendices in that article give a sense of how wide-ranging the interpretation of Italian markings was back then.  Different pieces marked with the same tempo marking were apparently performed with tempos that could vary by a factor of two or more.  Appendix 1 offers different pieces with recorded tempos that fell into these wide ranges. (I just give a selection to accord with the tempos discussed in the question.)
Using eighth note as beat:

Largo - 60-119 bpm
Larghetto - 95-153 bpm
Adagio - 64-125 bpm
Andante - 72-153 bpm
Lento - 69-153 bpm
Andante - 72-153 bpm

Using quarter note as beat:

Allegro - 91-153 bpm
Vivace - 88-168 bpm

Using half note (or dotted quarter) as beat:

Presto - 82-108 bpm
Prestissimo - 77-168 bpm

Granted, these tempos were recorded by one musician estimating how certain pieces were performed, but they give insight into the arbitrary attempts to try to shoehorn Italian markings into metronome ranges.  Obviously things like time signature, beat groupings, and rhythmic "feel" of a piece frequently will mean that a piece with a particular Italian marking might be outside of the range any standard metronome prescribes.
The takeaway here is that while there was a general sense that certain Italian markings were relatively "slow" and others relatively "fast," there was a huge range for most of them and significant overlap, rather than the nice delineated scale most metronomes present, dividing each marking up into tidy numerical ranges.
I cited that particular article for another reason: it also produces in its Figure 1 (pp. 38-39) a scale from a "Modern Metronome," cited to have been manufactured around 1975 by Seth Thomas, which corresponds pretty much exactly to the scale in the image cited in the question.  Indeed, while I'm not sure of the manufacturer of the historical metronome discussed in the question, the scale is the same one used by the French manufacturer Paquet and the American manufacturer Seth Thomas (which imitated Paquet in its "Maelzel Metronome" models).
Note that Seth Thomas was producing metronomes with this scale into the 1980s (here's an example of an electronic Seth Thomas metronome with this scale currently on sale on eBay), so we can't be sure the metronome discussed in the question was from Beethoven's time.  It's likely a bit later (late 19th or early 20th century), when this scale was somewhat standard on Paquet and Seth Thomas models.
The Seth Thomas scale was notably faster in its tempo markings than the Wittmer metronome scale, which came to dominate metronomes in the past generation or two after many other metronome makers left the market.  The Wittmer metronome scale is probably what most people today think of when they see Italian markings on a metronome, which is why I assume the question thinks the linked metronome's markings seem "too fast."  It seems the Wittmer scale (or something close to it) is often assumed in many apps and electronic metronomes today.
Anyhow, my broader point is that these supposed conversions are really nothing of the sort, just approximations created by metronome manufacturers, probably based on no standards or research.  Also, it's not clear that all metronome scales were meant to apply to the same note value: for example, the Seth Thomas scale might make more sense when sometimes applied to shorter note values, but obviously that wouldn't necessarily apply to all tempos.
As seen in the article cited above with its data from 1800, Italian markings had great overlap in their actual performance tempo ranges, so the metronome manufacturers had to create artificial ranges and distinctions among them.  Although I've never really looked at this in depth, I'd guess that by the late 1800s, composers began to correlate their tempo markings on newly written pieces to the (originally somewhat arbitrary) scales of the metronomes with their imprecise adherence to Italian marking norms.  But when one examines actual evidence from composers and performers who noted bpm markings in the late 1700s and early 1800s, these numbers were all over the map.
Bottom line is that the bpm range = Italian marking concept was essentially invented by metronome makers and was never very precise.  The reason this metronome seems "fast" is because it was likely made by a different manufacturer than the ones commonly produced today, not necessarily because it's significantly older.  (Wittmer's metronome scale dates, I believe, to the late 1800s when it began manufacturing them, roughly the same time Seth Thomas starting making metronomes.  So it's not like one scale is really "older" than the other in a substantial way.)


Linux ACL behaviour: settings the mask changes 'ls' output, but not actual permissions

Question: It might be the time of night, but this is puzzling me. Picture the following.
[root@node1 acltest]# getfacl foo/
# file: foo
# owner: root
# group: testuser
user::rwx
group::r-x
other::---

[root@node1 acltest]# ls -la .
total 24
drwxr-xr-x  3 root root     4096 Feb  9 21:53 .
drwxr-xr-x 25 root root     4096 Feb  9 21:54 ..
drwxr-x---  2 root testuser 4096 Feb  9 21:53 foo
[root@node1 acltest]# setfacl -m m::rwx foo
[root@node1 acltest]# getfacl foo/
# file: foo
# owner: root
# group: testuser
user::rwx
group::r-x
mask::rwx
other::---

[root@node1 acltest]# ls -la .
total 24
drwxr-xr-x   3 root root     4096 Feb  9 21:53 .
drwxr-xr-x  25 root root     4096 Feb  9 21:54 ..
drwxrwx---+  2 root testuser 4096 Feb  9 21:53 foo
[root@node1 acltest]# su - testuser
[testuser@node1 ~]$ cd /acltest/foo/
[testuser@node1 foo]$ ls -la .
total 16
drwxrwx---+ 2 root testuser 4096 Feb  9 21:53 .
drwxr-xr-x  3 root root     4096 Feb  9 21:53 ..
[testuser@node1 foo]$ touch bar
touch: cannot touch `bar': Permission denied

In words: I create a directory foo, with mode 0750, root as owner and testuser as the group. (testuser is the private group of testuser, but that doesn't matter.)
The getfacl command correctly shows no ACL's on this directory and there is not mask yet. The mask will be set accordingly to the group permissions if I would add a named group or user now.
If I explicitly set the mask to rwx now, the group permissions as shown by ls change too. I know it happens the other way around (the mask changes when the group permissions change), but this seems puzzling.
The more puzzling because the getfacl output does not show the group permissions as rwx but - as said - ls does.
Which one is right? Apparently, the output of getfacl is right, because testuser cannot write to foo. As expected, by the way, because I did not grant the testuser group any permissions to do so.
It goes on. I cannot allow the testuser group write permissions on foo by just using chmod. I have to explicitly set an ACL using setfacl -m g:testuser:rwx foo to allow testuser to finally touch foo/bar.
Can someone explain the rationale behind the difference in the outputs of getfacl and ls? I know it can be tricky to have normal permissions go together with ACL's, but this seems plain wrong. (Though I expect to be missing something glaringly obvious ;))
I have already seen Why does chmod(1) on the group affect the ACL mask?
Comment: I just verified that this behaviour happens on FreeBSD9, Debian, RHEL5 and RHEL6. So it's either a bug that has spread itself very broadly, or it's not a bug at all. In that case, someone explain this to me :)
Answer: From the man(5) page of acl

    ACL_MASK        The ACL_MASK entry denotes the maximum access
                       rights that can be granted by entries of type
                       ACL_USER, ACL_GROUP_OBJ, or ACL_GROUP.

and later:

else if the effective group ID or any of the supplementary group IDs
        of the process match the file group or the qualifier of any entry of
        type ACL_GROUP, then

          if the ACL contains an ACL_MASK entry, then

              if  the ACL_MASK entry and any of the matching ACL_GROUP_OBJ
              or ACL_GROUP  entries  contain  the  requested  permissions,
              access is granted,

              else access is denied.

This means that rwx CAN be granted on the dir, but the chmod bits have to agree with it.
Comment: Yes, sorry. Here again from the acl(5): `If the ACL has an ACL_MASK entry, the group permissions correspond to the permissions of the ACL_MASK entry.` I think that should answer the question.
Comment: Yeah, close. This states that the mask and the group have to agree on giving write access, which is logical. But it does not explain why 'ls' shows a file as writable by a group when it clearly is not.
Comment: Well, how about that. I completely missed that :) Thanks for taking the time to read that manpage more thoroughly than I did ;)
Answer: I would like to add that when ACLs are used on an object, the permissions listed by ls -l is bit different.
Accoring to man ACL(5):

CORRESPONDENCE BETWEEN ACL ENTRIES AND FILE PERMISSION BITS
The permissions defined by ACLs are a superset of the permissions
  specified by the file permission bits.
There is a correspondence between the file owner, group, and other
  permissions and specific ACL entries: the owner permissions correspond
  to the permissions of the ACL_USER_OBJ entry. If the ACL has an
  ACL_MASK entry, the group permissions correspond to the permissions of
  the ACL_MASK entry.  Otherwise, if the ACL has no ACL_MASK entry, the
  group permissions correspond to the permissions of the ACL_GROUP_OBJ
  entry.  The other permissions correspond to the permissions of the
  ACL_OTHER_OBJ entry.

So when using ACLs you should consider the group permission section of ls -l output as the ACL mask
.


Erro na conexão SQL Server depois de atualizar DBeaver Community

Question: Coloco todos os dados da minha conexão porém está dando este erro:
<code>com/microsoft/sqlserver/jdbc/SQLServerDriver
 has been compiled by a more recent version of the
 Java Runtime (class file version 61.0), this version
 of the Java Runtime only recognizes class file versions up to 55.0
</code>
Isso começou logo após atualizar o DBeaver Community para a versão 23.0, já tentei atualizar o Java Runtime, mas não adiantou
Comment: Olá, poderia colocar a mensagem de erro dentro da pergunta, de forma textual? Não é necessário remover a imagem, mas é importante ter as partes essenciais do seu código fonte no corpo da pergunta. Aprenda porque não é legal colocar imagens em perguntas [Postar mensagem de erro como imagem](https://pt.meta.stackoverflow.com/a/7817/103217). Um dos motivos é que se alguém quiser responder a pergunta, não pode copiar e executar o seu código. Imagens não desempenham bem nos mecanismos de busca pelo fato do conteúdo não poder ser indexado.
Answer: O roteiro abaixo foi feito com base no Sistema Operacional Windows 11. Creio que, com os devidos ajustes, poderá ser aplicado para os demais Sistemas Operacionais também.

Baixar a versão mais recente do Java SE. No caso, no tempo desse post, usei 19.0.2 (https://www.oracle.com/java/technologies/downloads/#jdk19-windows)

Localizar a pasta onde está instalada a versão mais recente do Java SE (Exemplo: C:\Program Files\Java).

Copiar a pasta da instalação do Java SE (Exemplo: jdk-19) para dentro da instalação do Dbeaver (C:\Program Files\DBeaver).

Se houver alguma pasta com nome jre dentro da Instalação do Dbeaver renomeá-la ou apagá-la. Obs: como já não está funcionando mesmo, apagar não afetaria em nada

Renomear a pasta que foi copiada no passo 3 para jre

Abrir o Dbeaver e testar se a conexão com o SQL Server agora está funcionando.
Comment: a dica ajudou aqui, só que eu baixei a versão compactada(x64 Compressed Archive) do JDK, https://download.oracle.com/java/19/latest/jdk-19_windows-x64_bin.zip e extrai na pasta dbeaver e renomeei pra jre, substituindo a JRE atual da pasta. obrigado


Multiple results when identifying

Question: When IDing the song "Love Invaders - Fatima Yamah" I get the below results:
<code>python test.py ~/MusicID/File5.mp3
</code>
https://pastebin.com/YAdAru7A
None of which are actually correct, although some of the scores report 100. How can one song report back so many results? Is there a way to fix this?
Thanks
Answer: Thanks for pointing out this issue, it seems we don't have the song "Love Invaders - Fatima Yamah" in our database (but we've added it), we are looking to the issue of score 100. You can try again now. Sorry for the inconvenience.
Comment: Thanks, however it still isn't returning that song ID? Still results in numerous different IDs.
Comment: Hi Joe, Could you please send the audio file you want to recognize to us? firstname.lastname@example.com, we will look into this issue. Thanks
Comment: Hi, it's being recognised now, however still returning numerous results for the file:
https://pastebin.com/65raLKiR
Comment: Hi Joe, the system returns multiple results by default, but you can pick the first one as the best result.

Multiple results when identifying


How to track down segmentation fault in Linux?

Question: My server went down suddenly and the ISP supports says it may have had a segmentation fault. I am wondering how to track down and possibly fix this so it will not occur again?
Thanks
Comment: It "may have had" ? So they don't actually know?
Comment: @gparent actually no. That's the only explanation that I've got.
Comment: Is that a shared or dedicated host, vserver or physical/vm?
Comment: It's a dedicated server
Comment: Not enough information has been provided here for us to help you.  There are so many different reasons for a segmentation fault, and to fix it you'd have to be ready to edit the source code after analyzing the core dump and make the change and make a new binary.
Comment: When you say "my server", do you mean a process running on a machine? Or a machine?
Answer: Such segfaults are usually logged in the system's syslog facility. The exact name of which changes by distro, though dmesg should have it if it's recent enough; it'll be in /var/log one way or the other, though.
Interpreting the message will be another story entirely. But at least you'll know what faulted.


Can I do a max(count(*)) in SQL?

Question: Here's my code:
select yr,count(*)
from movie
join casting on casting.movieid=movie.id
join actor on casting.actorid = actor.id
where actor.name = 'John Travolta'
group by yr;

Here's the question:

Which were the busiest years for 'John Travolta'. Show the number of movies he made for each year.

Here's the table structure:
movie(id, title, yr, score, votes, director)
actor(id, name)
casting(movieid, actorid, ord)

This is the output I am getting:
yr      count(*)
1976    1
1977    1
1978    1
1981    1
1994    1
-- etc.

I need to get the rows for which count(*) is max.
How do I do this?
Comment: The question fails to disclose RDBMS and version. The answer very much depends on it.
Comment: The smartest (and probably fastest answer w/o a sub-query) is [here](https://stackoverflow.com/a/14249738/376483): Use `LIMIT 1` to avoid the subquery.
Answer: Use:
  SELECT m.yr,
         COUNT(*) AS num_movies
    FROM MOVIE m
    JOIN CASTING c ON c.movieid = m.id
    JOIN ACTOR a ON a.id = c.actorid
                AND a.name = 'John Travolta'
GROUP BY m.yr
ORDER BY num_movies DESC, m.yr DESC

Ordering by num_movies DESC will put the highest values at the top of the resultset.  If numerous years have the same count, the m.yr will place the most recent year at the top... until the next num_movies value changes.
Can I use a MAX(COUNT(*)) ?

No, you can not layer aggregate functions on top of one another in the same SELECT clause.  The inner aggregate would have to be performed in a subquery.  IE:
SELECT MAX(y.num)
  FROM (SELECT COUNT(*) AS num
          FROM TABLE x) y

Comment: Yes you can use MAX(COUNT(*)), but in Oracle. http://www.techonthenet.com/sql/max.php
Comment: @OMG Ponies - This answer was REALLY excellent - The first SQL you provided does work (obvs) BUT the second SQL you provided is so very elegant AND Enabled me to also gain a better understanding of subquery!   THANK YOU for taking the trouble to give a fully expanded answer. I was trying to accomplish this - but with a Group By in there as well - and doing this made it quite possible!
Comment: Just in trying to understand this further - How would you use this second query to obtain the year which had the max number of movies? As it is right now it can identify how many movies happened in the year that had the most movies - but it will not give which year that was.  I would quite like to understand how to pass a second value back from the subquery which is the Group By value correlated to the MAX result
Answer: Just order by count(*) desc and you'll get the highest (if you combine it with limit 1)
Comment: Now what if I had several rows with the max value and wanted to display all values that have a "max value"
Comment: @Wolph hes saying that you can have multiple rows with same max value, with limit 1 you cannot see that
Comment: Upon rereading that (3 year old) comment I think he's looking for `HAVING MAX(...) = ...`
Comment: @WhyCry: Not entirely sure what you're trying to ask this, but if you can't find the answer on Stackoverflow you should just ask it as a separate question :)
Comment: I love this solution! Easiest and most cost efficient
Answer: This question is old, but was referenced in a new question on dba.SE. I feel the best solutions haven't been provided. Plus, there are new, faster options.
Question in the title

Can I do a max(count(*)) in SQL?

Yes, you can achieve that by nesting an aggregate function in a window function:
SELECT m.yr
     , count(*) AS movie_count
     , max(count(*)) OVER () AS max_ct
FROM   casting c
JOIN   movie   m ON c.movieid = m.id
WHERE  c.actorid = (SELECT id FROM actor WHERE name = 'John Travolta')
GROUP  BY m.yr
ORDER  BY count(*) DESC;

db<>fiddle here
That's standard SQL. Postgres introduced it with version 8.4 (released 2009-07-01, before this question was asked. Other RDBMS should be capable of the same.
Consider the sequence of events in a SELECT query:

Best way to get result count before LIMIT was applied

Possible downside: window functions do not aggregate rows. You get all rows left after the aggregate step. Useful in some queries, but not ideal for this one.
To get one row with the highest count, you can use ORDER BY ct DESC FETCH FIRST 1 ROW ONLY:
SELECT c.yr, count(*) AS ct
FROM   actor   a
JOIN   casting c ON c.actorid = a.id
WHERE  a.name = 'John Travolta'
GROUP  BY c.yr
ORDER  BY ct DESC
FETCH  FIRST 1 ROW ONLY;

Using only basic SQL features, available in any halfway decent RDBMS. Most popular RDBMS (also) support alternative syntax for FETCH FIRST with LIMIT, TOP or ROWNUM. See:

SQL select elements where sum of field is less than N

Or you can get one row per group with the highest count with DISTINCT ON (only Postgres):

Select first row in each GROUP BY group?

Actual Question

I need to get the rows for which count(*) is max.

There may be more than one row with the highest count.
SQL Server has had the feature WITH TIES for some time - with non-standard syntax:
SELECT TOP 1 WITH TIES
       m.yr, count(*) AS movie_count
FROM   casting c
JOIN   movie   m ON c.movieid = m.id
WHERE  c.actorid = (SELECT id FROM actor WHERE name = 'John Travolta')
GROUP  BY m.yr
ORDER  BY count(*) DESC;  -- can't sort by year for this

db<>fiddle here
PostgreSQL 13 added WITH TIES with standard SQL syntax:
SELECT m.yr, count(*) AS movie_count
FROM   casting c
JOIN   movie   m ON c.movieid = m.id
WHERE  c.actorid = (SELECT id FROM actor WHERE name = 'John Travolta')
GROUP  BY m.yr
ORDER  BY count(*) DESC  -- can't sort by year for this
FETCH  FIRST 1 ROWS WITH TIES;

db<>fiddle here
This should be the fastest possible query. Further reading:

Get top row(s) with highest value, with ties

PostgreSQL equivalent for TOP n WITH TIES: LIMIT "with ties"?

To sort results by additional criteria (or for older versions of Postgres or other RDBMS without WITH TIES), use the window function rank() in a subquery:
SELECT yr, movie_count
FROM  (
   SELECT m.yr, count(*) AS movie_count
        , rank() OVER (ORDER BY count(*) DESC) AS rnk
   FROM   casting c
   JOIN   movie   m ON c.movieid = m.id
   WHERE  c.actorid = (SELECT id FROM actor WHERE name = 'John Travolta')
   GROUP  BY m.yr
   ) sub
WHERE  rnk = 1
ORDER  BY yr;  -- optionally sort by year

All major RDBMS support window functions nowadays.
Comment: [...you do not need to join to the table movie at all]. A join to the table 'movie' is required as this is the only table with the column 'yr' (year of movie).
Comment: @KevinSwann: I missed this somehow, sorry. You are right, I fixed accordingly. Added new, better options while being at it.
Answer: SELECT * from
(
SELECT yr as YEAR, COUNT(title) as TCOUNT
FROM actor
JOIN casting ON actor.id = casting.actorid
JOIN movie ON casting.movieid = movie.id
WHERE name = 'John Travolta'
GROUP BY yr
order by TCOUNT desc
) res
where rownum < 2

Comment: ORDER BY without LIMIT/TOP in a subquery has no effect.
Answer: it's from this site - http://sqlzoo.net/3.htm
2 possible solutions:
with TOP 1 a ORDER BY ... DESC:
SELECT yr, COUNT(title)
FROM actor
JOIN casting ON actor.id=actorid
JOIN movie ON movie.id=movieid
WHERE name = 'John Travolta'
GROUP BY yr
HAVING count(title)=(SELECT TOP 1 COUNT(title)
FROM casting
JOIN movie ON movieid=movie.id
JOIN actor ON actor.id=actorid
WHERE name='John Travolta'
GROUP BY yr
ORDER BY count(title) desc)

with MAX:
SELECT yr, COUNT(title)
FROM actor
JOIN casting ON actor.id=actorid
JOIN movie ON movie.id=movieid
WHERE name = 'John Travolta'
GROUP BY yr
HAVING
    count(title)=
        (SELECT MAX(A.CNT)
            FROM (SELECT COUNT(title) AS CNT FROM actor
                JOIN casting ON actor.id=actorid
                JOIN movie ON movie.id=movieid
                    WHERE name = 'John Travolta'
                    GROUP BY (yr)) AS A)

Answer: Using max with a limit will only give you the first row, but if there are two or more rows with the same number of maximum movies, then you are going to miss some data.  Below is a way to do it if you have the rank() function available.
SELECT
    total_final.yr,
    total_final.num_movies
    FROM
    ( SELECT
        total.yr,
        total.num_movies,
        RANK() OVER (ORDER BY num_movies desc) rnk
        FROM (
               SELECT
                      m.yr,
                      COUNT(*) AS num_movies
               FROM MOVIE m
               JOIN CASTING c ON c.movieid = m.id
               JOIN ACTOR a ON a.id = c.actorid
               WHERE a.name = 'John Travolta'
               GROUP BY m.yr
             ) AS total
    ) AS total_final
   WHERE rnk = 1

Answer: The following code gives you the answer. It essentially implements MAX(COUNT(*)) by using ALL. It has the advantage that it uses very basic commands and operations.
SELECT yr, COUNT(title)
FROM actor
JOIN casting ON actor.id = casting.actorid
JOIN movie ON casting.movieid = movie.id
WHERE name = 'John Travolta'
GROUP BY yr HAVING COUNT(title) >= ALL
  (SELECT COUNT(title)
   FROM actor
   JOIN casting ON actor.id = casting.actorid
   JOIN movie ON casting.movieid = movie.id
   WHERE name = 'John Travolta'
   GROUP BY yr)

Answer: Depending on which database you're using...
select yr, count(*) num from ...
order by num desc

Most of my experience is in Sybase, which uses some different syntax than other DBs.  But in this case, you're naming your count column, so you can sort it, descending order.  You can go a step further, and restrict your results to the first 10 rows (to find his 10 busiest years).
Answer: Thanks to the last answer
SELECT yr, COUNT(title)
FROM actor
JOIN casting ON actor.id = casting.actorid
JOIN movie ON casting.movieid = movie.id
WHERE name = 'John Travolta'
GROUP BY yr HAVING COUNT(title) >= ALL
  (SELECT COUNT(title)
   FROM actor
   JOIN casting ON actor.id = casting.actorid
   JOIN movie ON casting.movieid = movie.id
   WHERE name = 'John Travolta'
   GROUP BY yr)

I had the same problem: I needed to know just the records which their count match the maximus count (it could be one or several records).
I have to learn more about "ALL clause", and this is exactly the kind of simple solution that I was looking for.
Answer: create view sal as
select yr,count(*) as ct from
(select title,yr from movie m, actor a, casting c
where a.name='JOHN'
and a.id=c.actorid
and c.movieid=m.id)group by yr

-----VIEW CREATED-----
select yr from sal
where ct =(select max(ct) from sal)

YR
2013
Answer:      select top 1 yr,count(*)  from movie
join casting on casting.movieid=movie.id
join actor on casting.actorid = actor.id
where actor.name = 'John Travolta'
group by yr order by 2 desc

Answer: you can use the top along with with ties, which will include all of the years having the maximum count(*) value, something like this:
select top (1) with ties yr, count(*)
from movie
   join casting
      on casting.movieid=movie.id
   join actor
      on casting.actorid = actor.id
where actor.name = 'John Travolta'
group by yr;
order by count(*) desc

If the maximum is say 6, you'll get all of the years for which the count value is 6.

Can I do a max(count(*)) in SQL?


Cannot find Registry Setting for Office Shared Templates

Question: We have our Templates for Office 2003 located in a shared location \servername\Templates$
This is also the location of our Word Startup Folder. Both settings are set in a User Group Policy.
This has been working for Word forever. Now we have a company who is making a Powerpoint template for us. They are trying to refer to the network location by reading the registry setting SharedTemplates that is supposed to be located at

HKEY_CURRENT_USER\Software\Microsoft\Office\11.0\Common\General

The problem is that there is no such registry entry there. But Word is working.
So I am trying to find out how Word knows the network location, so that the Powerpoint template can get the same location.
I really do not want to hard code the location into the Powerpoint Addin.
Thanks!
Answer: You can use regshot to find defferences in registry with enabled setting in group policy and with disabled one.
Answer: You might try changing the template location setting on a sacrificial sample computer to a string of gibberish, and then searching the registry for that same string.


Drush contrib modules not available if executed externally

Question: Using Drush 5.8 contrib modules are not available if executed externally.
E.g. Drush Entity is not available if executed on a Django view via a check_output:
check_output("drush -l example.com -r /var/www/my/example/site/ entity-read node", shell=True)

Any command regarding Drush Entity return an error specifying that the command "could not be found.  Run drush cache-clear drush to clear the commandfile cache if you have installed new extensions."
The same command is available if executed via an interactive python shell or via ssh.
I've installed Drush Entity in this way:
drush dl drush_entity

This command on my system put drush_entity into /home/admin/.drush directory. This directory seems to be ignored, since site-alias too are ignored if i put them inside that directory.
Answer: The solution is to pass the environment variable $HOME to check_output, in this case /home/admin:
check_output("drush -l example.com -r /var/www/my/example/site/ entity-read node", shell=True, env={'HOME': "/home/admin"})

This force the /home/admin/.drush directory to be read. If everything is fine this command:
drush ev 'print(drush_server_home());'

should return /home/admin. If drush_server_home() returns an empty string, contrib modules installed inside .drush on home directory will not be available.
Ensure to install contrib modules with the same user controlling the /home/admin directory.
Read the documentation of the language you're using to pass the $HOME variable on command execution.
Comment: If you don't want to set up your environment, you can also use the Drush --include option to point at your drush resources folder, or use --config to point directly at a drushrc.php file.
Comment: Nice suggestion greg! It would be the right choice if multiple Linux users have different drush installations with different drush modules versions.


Alter form field from module

Question: In my user profile, I have some fields I want to alter. For my regular fields I use:
mymodule_form_alter(&$form, &$form_state, $form_id)
That works, but inside the $form there are some fields missing. Like for example the Timezone settings and the Private Messages. So fields from another module (like Private Messages) or standard settings. How can I alter those?
I tried a custom template file for the user profile and there I have access to those fields inside the $form. But I shouldn't altern them in a template file, right? So what would be the right approach for this?
Comment: I suggest you put all such code into one "common" module, which contains all custom code that doesn't warrant its own module, like random form hooks etc.
Answer: hook alter normally works on contrib modules. I can see the reason why it has not been working is due to fact that the module needs to be altered got more priority than the altering module.
To overcome such scenario you need to manually change the priority of your custom module, this can be done by changing the value of weight column in system table.

Alter form field from module


In every power of 3 the tens digit is an even number

Question: How to prove that in every power of $3$, with natural exponent, the tens digit
is an even number?
For example, $3 ^ 5 = 243$ and $4$ is even.
Comment: If you look at integer multiplication, only a finite number of digits of any two numbers number can influence any digit in the result. Enumerate all cases for those.
Answer: Use induction on the exponent:
The last digit is either 1, 3, 7 or 9.
If 1 or 3, multiplying a power of 3 will not change the evenness of the second last digit.
If 7 or 9, multiplying will result in a carry over of 2, which again does not change the evenness of the second last digit.
Answer: Hint $\,\bmod 20\!:\,\ 3^{\large 4} \equiv 1\,\Rightarrow\,3^{\large n}\equiv 3^{\,\large n\bmod 4}\in \{\color{#c00}01,\color{#c00}03,\color{#c00}09,\color{#c00}27\}$

Inductively: $\ 3^{\large n} = 20\,k\, +\{0,3,9,7\}\,\ $
$\qquad\ \Rightarrow\ 3^{\large n+1} = 20 K+\{0,9,7,1\},\,\  K = 3k\!+\!i,\,\ i\in \{ 0,1\}$
Notice $\,r< 10\,\Rightarrow\, 20k+r =  (\color{#0a0}{2k})10 + r\,$  has even tens digits $\,\color{#0a0}{2k} \bmod 10 = 2(k\bmod 5)$
Answer: Moron's answer is very elegant.
Here is an easy but tedious way of dealing with many similar questions: For any $n$ and $k$, the last $k$ digits of the numbers in the sequence $n^1,n^2,n^3,\dots$ eventually repeat, so we only need to check a few cases.
For the question at hand, note that $3^2=9=10-1$, so $3^{20}=(10-1)^{10}$ has the form $100k+1$ for some $k$. This means that the last 2 digits of powers of 3 repeat each 20 numbers. So we just need to check the last two digits of $3^0,3^1,\dots,3^{19}$, and this can be done very quickly even by hand: $$01, 03, 09, 27, 81, 43, 29, 87,\dots,89,67.$$
Answer: Case 1: $n = 2k; k$ even.
$3^{2k} = 9^{k} = (10 - 1)^{k} = 10^{k} - {k \choose 2}^{k-1} + .... + {k \choose k-2}10^2 - {k \choose k - 1}10 + 1 = N*100 - k*10 + 1$.  $k$ is even so the second digit is even.
Case 2: $n = 2k; k$ odd.
$3^{2k} = 9^{k} = (10 - 1)^{k} = 10^{k} - {k \choose 2}^{k-1} + .... - {k \choose k-2}10^2 + {k \choose k - 1}10 - 1 = N*100 + k*10 - 1$.  $k$ is odd so $k*10 - 1 = (k - 1)*10 + 9$ so the second digit is even.
Case 3: $n = 2k + 1; k$ even.
$3^{2k} = 9^{k} = (10 - 1)^{k} = 10^{k} - {k \choose 2}^{k-1} + .... + {k \choose k-2}10^2 - {k \choose k - 1}10 + 1 = N*100 - k*10 + 1$.
$3^{2k+1} = $M*100 - 3k*10 + 3$.  As $k$ is even the second digit is even.
Case 4: $n = 2k + 1; k$ odd.
$3^{2k} = 9^{k} = (10 - 1)^{k} = 10^{k} - {k \choose 2}^{k-1} + .... - {k \choose k-2}10^2 + {k \choose k - 1}10 - 1 = N*100 + k*10 - 1$.
$3^{2k + 1} = M*100 + 3k*10 - 7 = M*100 + (3k -1)*10 + 7$.  As $3k -1$ is even, the second digit is even.
This also tells you what the first digit is: 1, 9, 3, or 7.  Which gives a hint that might be a more efficient method.
Method 2:
$3^4 = 81 = 8*10 + 1$
So if $n = 4m + k; k = 0,1,2,3$
$3^n = (3^4)^m 3^k = (8*10 + 1)^m 3^k = (M*100 + 8*m*10 + 1)\{1,3,9,27\}$
$= N*100 + 8*m*\{1,3,9,7\}*10 \{+ 2*10\} + 1*\{1,3,9,7\}$
Or more elegantly as Bill Dubuque pointed out
$3^4 = 1 \mod (20) \implies 3^{4m + k} = (3^4)^m 3^k = 3^k \mod 20 \implies$
$ 3^n = \{1,3,9,7\} \mod 20$.
Answer: It's actually interesting.
If you do a table of multiples of 1, 3, 7, 9 modulo 20, you will find a closed set, ie you can't derive an 11, 13, 17 or 19 from these numbers.
What this means is that any number comprised entirely of primes that have an even tens-digit will itself have an even tens-digt.  Such primes are 3, 7, 23, 29, 41, 43, 47, 61, 67, 83, 89, 101, 103, 107, 109  to a hundred.
If the tens-digit is odd, then it must be divisible by an odd number of primes of the form 11, 13, 17, 19 mod 20.  Any even number of these would produce an even tens digit.
Answer: We know that
$3^1=03$
$3^2=09$
$3^3=27$
$3^4=81$
And so on.
Here we noticed that 81 is the largest two digit number that is in the form of $3^n$.
After that 3 digit number starts .
But till 81 if you see tens digit is even so here 2 case arises
Case 1
When we have last digit of $3^n$ = 3, 1
After multiplying it by 3 we see it not makes any effect on the ten's digit
and as ten's digit is even then any thing multiplied to even will give you even
So for this case ten's digit is even.
Case 2
When the last digit of $3^n$ = 9 , 7
Here after multiplying by 3 it will have a effect on ten's digit
But $9*3=27$
And$3*7=21$
Here wee see 2 will be added to ten's digit
Now again as before I said ten's digit is even then the product after multiplying it by 3 will be even and as 2 is added to the result it will also be an even number as 2 is even and even added to even gives us even.
Here's what I thought.
Answer: A slightly different approach:
Let $n$ be the exponent of the variable power of $3$. Therefore, the power of $3$ takes the form $3^n$. Now, $n$ can either be even or odd. Hence two cases are formed:-
Case1: $n$ is even.
 Since $n$ is even, let us say it is of the form $2k$.
Therefore, $3^n = 3^{2k} = (3^k)^2$. This means that is $n$ if even, $3^n$ is a square. Notice that the even powers of $3$ result in a number with the last digit $\in \{1,9\}$
And $(2m + 1)^2 \equiv 1(mod 4)$
$\Rightarrow 3^n \equiv 1(mod4)$
$\Rightarrow 3^n -1 \equiv 0(mod4)$
$\Rightarrow 4 |(3^n-1)$.
We know that, if $4$ divides a number, it must divide $(10($$the$ $second$ $last$ $digit$$) + $$the$ $last$ $digit$$)$
Therefore, if $4 |(3^n-1)$,$ $ $ $ $ $ $ $ $ $ $ $   $4|(10($$the$ $second$ $last$ $digit$$) + $$the$ $last$ $digit$$)-1$
$\Rightarrow 4|(10($$the$ $second$ $last$ $digit$$) + 1-1)$ and $4|(10($$the$ $second$ $last$ $digit$$) + 9-1)$.
$\Rightarrow 4|(10($$the$ $second$ $last$ $digit$$) + 0)$ and $4|(10($$the$ $second$ $last$ $digit$$) + 8)$.
Since, $4| 0$ and $4| 8$, $4|(10($$the$ $second$ $last$ $digit$$)$
This is true only if $the$ $second$ $last$ $digit$ is even.
Case2: $n$ is odd.
 Since $n$ is odd, let us say it is of the form $2k+1$.
Therefore, $3^n = 3^{2k+1} = (3^k)^2.(3)$. This means that if $n$ is odd, $3^n$ is a $($square $* 3)$. Notice that the odd powers of $3$ result in a number with the last digit $\in \{3,7\}$
And $(2m + 1)^2 \equiv 1(mod 4)$
$\Rightarrow (2m + 1)^{2p+1} \equiv (2m + 1)(mod4)$
$\Rightarrow 3^n \equiv 3(mod4)$
$\Rightarrow 3^n -3 \equiv 0(mod4)$
$\Rightarrow 4 |(3^n-3)$.
We know that, if $4$ divides a number, it must divide $(10($$the$ $second$ $last$ $digit$$) + $$the$ $last$ $digit$$)$
Therefore, if $4 |(3^n-3)$,$ $ $ $ $ $ $ $ $ $ $ $   $4|(10($$the$ $second$ $last$ $digit$$) + $$the$ $last$ $digit$$)-3$
$\Rightarrow 4|(10($$the$ $second$ $last$ $digit$$) + 3-3)$ and $4|(10($$the$ $second$ $last$ $digit$$) + 7-3)$.
$\Rightarrow 4|(10($$the$ $second$ $last$ $digit$$) + 0)$ and $4|(10($$the$ $second$ $last$ $digit$$) + 4)$.
Since, $4| 0$ and $4| 4$, $4|(10($$the$ $second$ $last$ $digit$$)$
This is true only if $the$ $second$ $last$ $digit$ is even.
Therefore, the tens digit of any power of $3$ is always even.
Answer: Considering $3^k \bmod 20$, we know from the Carmichael function that the values will cycle on a pattern of $\lambda(20)=4$ (or less). This is short enough to just evaluate:
$
3^1\equiv 3 \bmod 20 \\
3^2\equiv 9 \bmod 20 \\
3^3\equiv 7 \bmod 20 \\
3^4\equiv 1 \bmod 20
$
and the cycle repeats. As you can see, none of these values are greater than $10$ so the tens digit of any power of $3$ will be even (because these values will always be added to some multiple of $20$).
Answer: By brute force:
The powers of $3$ modulo $100$ are periodically
$$01,03,09,27,81,43,29,87,61,83,49,47,41,23,69,07,21,63,89,67,01,\cdots$$

By induction:
$$3^0\bmod20=1\in\{1,3,9,7\}$$
and
$$3^n\bmod20\in\{1,3,9,7\}\implies 3^{n+1}\bmod20\in\{3,9,7,1\}.$$
So the tenth digit modulo $2$ is always $0$.


Adding dividers between list items in the menu.html.twig template

Question: How do I add dividers between each
 in the menu.html.twig template. Obviously with the code below, the divider also gets added after the last item, which isn't the desired result.
{% import _self as menus %}

{#
  We call a macro which calls itself to render the full tree.
  @see http://twig.sensiolabs.org/doc/tags/macro.html
#}
{{ menus.menu_links(items, attributes, 0) }}

{% macro menu_links(items, attributes, menu_level) %}
  {% import _self as menus %}
  {% if items %}

    {% for item in items %}
      {%
        set classes = [
          item.is_expanded ? 'menu-item--expanded',
          item.is_collapsed ? 'menu-item--collapsed',
          item.in_active_trail ? 'menu-item--active-trail',
        ]
      %}

        {{ link(item.title, item.url) }}
        {% if item.below %}
          {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
        {% endif %}

    {% endfor %}

  {% endif %}
{% endmacro %}

Answer: See The Loop Variable in the Twig docs; you can use something like
{% if loop.last == false %}

{% endif %}


Simple Client-Server Communication?

Question: Working on a server-socket lab in Java and our instructor provided us with the Client Side of the code. In the project, Client sends a string to the server. The Server then turns around and sends the string back to the client.
Client
        Socket server = new Socket(host, 30000);

        // Sends the string to the Server
        Socket server = new Socket(host, 30000);
        OutputStream serverOut = server.getOutputStream();
        PrintWriter serverWrite = new PrintWriter(serverOut, true);
        serverWrite.println("Bryce");

        //Manages Server's response of "Hello, Bryce!"
        InputStream serverIn = server.getInputStream();
        Scanner serverScan = new Scanner(serverIn);
        serverScan.useDelimiter("$");
        String resp = serverScan.next();

Server
    ServerSocket ss = new ServerSocket(30000);
    Socket s = ss.accept();
    InputStream is = s.getInputStream();

     // Gets Message from Client
    InputStreamReader reader = new InputStreamReader(is);
    BufferedReader readerBuff = new BufferedReader(reader);
    String stringFromClient = readerBuff.readLine();

     // Sends Message back to Client
     OutputStream oos = s.getOutputStream();
     PrintWriter pl = new PrintWriter(oos, true);
     pl.println("Hello, " + stringFromClient + "!");

EverytimeI run the program, it pulls up a NoSuchElementException and cites the offending line in Client:
String resp = serverScan.next();

This should be a fairly simple problem(I've completed this sort of problem before). If i replace
 String resp = serverScan.next();

with
 String resp = serverScan.toString();

it works fine, but as I'm not allowed to modify the Client-Code, I'm totally confused. Am I missing something here?
Comment: serverScan.next() gets the next line from the client. serverScan.toString() gets a textual representation of the Scanner object (probably something like `java.util.Scanner@0xF35AB395`
Answer: In the client side code, you have
serverScan.useDelimiter("$");

This means the client side scanner will use $ as the delimiter for the incoming characters. So in order to let client side know that a complete tokenized string is sent, you need to add one more character at the end of the message string sent by server:
pl.println("Hello, " + stringFromClient + "!" + "$");

The javadoc of next method in Scanner class says:

Finds and returns the next complete token from this scanner. A
  complete token is preceded and followed by input that matches the
  delimiter pattern.
Comment: I ended up adding oos.flush and oos.close to the end of my server-code and that fixed it.
Comment: @user2453973 close() implies flush(). You don't need flush().

Simple Client-Server Communication?