Database agnostic stored procedure API

Question: Our legacy web application heavily uses stored procedures. We have a central interface through which all database calls (i.e. queries and procedures) are made. However, the current implementation uses the OracleCommandBuilder.DeriveParameters method under the hood to bind to the appropriate stored procedure signature. From the documentation:

DeriveParameters incurs a database round-trip and should only be used during design time.
  To avoid unnecessary database round-trips in a production environment, the
  DeriveParameters method itself should be replaced with the explicit parameter settings
  that were returned by the DeriveParameters method at design time.

We could use the OracleCommand class to explicitly bind to the correct stored procedure signature. However, littering our code (even if only the Data Access Layer) with OracleCommand objects is not database agnostic. We already support database agnostic dynamic queries in our database interface (hereafter referred to as IDatabaseService), which looks like this:
int ExecuteNonQuery(string query, object[] parameterValues);
IDataReader ExecuteReader(string query, object[] parameterValues);
// etc.

We want to also support database agnostic stored procedure calls. What is a good pattern for this?
More information:
To bind to a specific subroutine, OracleCommands allow BindByName. We prefer to not use that approach, as a string is more error-prone than a type. The other approach for binding a subroutine call is to provide the parameter types. We could rely on the parameter values and reflect on the runtime types, but we want stronger safety than that. We want to require that the types are explicitly provided to the database interface so that we can check that the provided parameter values match the provided subroutine parameter types before we communicate to the database.
Comment: So you're paying how much for Oracle, yet you want a completely generic/agnostic approach?  If you paid for Oracle, use it!  If not, just go with Postres or mysql or similar.  Just my 2 cents tho.
Comment: @tbone We are not in control of our deployment environment, yet it is subject to change. We are preparing for the scenario that our client wants to switch to another DB platform.
Comment: in my experience its more likely the middleware and/or front end will change before the backend will (esp if they've been using Oracle for a while and have developed a layer of packages/procedures/functions).
Comment: @tbone That's not the case here.
Answer: After prototyping various approaches, we settled on the following.
To IDatabaseService we added new ExecuteYYY methods that take an object implementing IDatabaseSubroutineSignature and (optionally, via an overload) an IEnumerable that are the parameter values.
The ExecuteYYY methods on IDatabaseService look like this:
DataSet ExecuteDataSet(IDatabaseSubroutineSignature signature);
DataSet ExecuteDataSet(IDatabaseSubroutineSignature signature, IEnumerable<object> parameterValues);
void ExecuteNonQuery(IDatabaseSubroutineSignature signature);
void ExecuteNonQuery(IDatabaseSubroutineSignature signature, IEnumerable<object> parameterValues);
IDataReader ExecuteReader(IDatabaseSubroutineSignature signature);
IDataReader ExecuteReader(IDatabaseSubroutineSignature signature, IEnumerable<object> parameterValues);
object ExecuteScalar(IDatabaseSubroutineSignature signature);
object ExecuteScalar(IDatabaseSubroutineSignature signature, IEnumerable<object> parameterValues);
ReadOnlyCollection<object> ExecuteScalarMultiple(IDatabaseSubroutineSignature signature);
ReadOnlyCollection<object> ExecuteScalarMultiple(IDatabaseSubroutineSignature signature, IEnumerable<object> parameterValues);

There are some differences between the standard .NET BCL ExecuteYYY methods and the above:

Our ExecuteNonQuery methods return void. This is because ExecuteNonQuery (on the command object) always returns -1 when a stored procedure is executed.
We have introduced a new ExecuteScalarMultiple method. This accounts for multiple output parameters.

IDatabaseSubroutineSignature looks like this:
public interface IDatabaseSubroutineSignature
{
    string Name { get; }
    IEnumerable<IDatabaseSubroutineParameter> Parameters { get; }
}

public interface IDatabaseSubroutineParameter
{
    ParameterType Type { get; }
    ParameterDirection Direction { get; }
}

// Using custom DbType attribute.
public enum ParameterType
{
    [DbType(DbType.Decimal)]
    Decimal,
    [DbType(DbType.String)]
    String,
    [DbType(DbType.StringFixedLength)]
    Character,
    RefCursor,
    [DbType(DbType.Double)]
    Double,
    [DbType(DbType.Int32)]
    Int32,
    [DbType(DbType.Int64)]
    Int64,
    [DbType(DbType.DateTime)]
    DateTime
}

The final problem we had is with a convenient way to create (and represent) the signatures in code. We settled on a monadesque approach by creating a subinterface of IDatabaseSubroutineSignature that exposes methods for creating parameters:
public interface IDatabaseSubroutineSignatureCreator : IDatabaseSubroutineSignature
{
    IDatabaseSubroutineSignatureCreator Input(ParameterType dbType);
    IDatabaseSubroutineSignatureCreator Output(ParameterType dbType);
    IDatabaseSubroutineSignatureCreator InputOutput(ParameterType dbType);
    IDatabaseSubroutineSignatureCreator ReturnValue(ParameterType dbType);
}

Finally, here is a usage example:
private static readonly IDatabaseSubroutineSignature MyProcedureSignature =
    DatabaseSubroutineSignatureFactory.Create("pkg.myprocedure")
        .Input(ParameterType.Decimal)
        .Input(ParameterType.String)
        .Output(ParameterType.RefCursor);

public IEnumerable<DataObject> CallMyProcedure(decimal userId, string searchQuery)
{
    using (IDatabaseService dbService = ...)
    using (IDataReader dataReader = dbService.ExecuteReader(MyProcedureSignature,
        new object[] { userId, searchQuery }))
    {
        while (dataReader.Read())
        {
            yield return new DataObject(
                dataReader.GetDecimal(0),
                dataReader.GetString(1));
        }
    }
}

Database agnostic stored procedure API


How can we extract all sub module from parent module?

Question: I checkout a project from SVN which contain many sub module.
In my collogue system these all module are showing like a separate module. some one else did this configuration
but in my system its showing a single module like..
how can I does same thing ..
this project contain so many technologies like Maven Gwt Java
please help me how this all are working I have no idea of this configuration.
Answer: If the ide is eclipse with maven plugin. you can navigate to annual-web in the project you have checked out. Right click on annual-web-> select import->type maven in filter-> click on existing maven projects-> select the pom->click finish


Distance between two lines inside a circle

Question: In the following figure:

The points are given by
$$
\begin{aligned}
A &= (\cos(a_1), \sin(a_1)) \times r_1 \\
C &= (\cos(a_2), \sin(a_2)) \times r_1 \\
&\\
B &= (\cos(a_1), \sin(a_1)) \times r_2 \\
D &= (\cos(a_2), \sin(a_2)) \times r_2
\end{aligned}
$$
where $a_1$ and $a_2$ are angles, $r_1$ the radius of the small circle and $r_2$ the radius of the big circle.
As you can see, the angles are the same for both circles, but because the radius is not the same, the points end up in a different place, and are not aligned.
Now I have two problems, that may be in fact the same, I don't know, you can choose to answer either of them:

Find the distance between the two lines (AC) and (BD)
Determine the angle of $B'$ and $D'$, from the point of view of the small circle, such as the points are on the (AC) line

I figured out the first problem by taking the dot product of the normal of (AC) and the vector AB, but this solution seems overkill, because the second line is not "any" line, it's just a scaled version of the first line, so maybe there's a better way to compute this distance?
Or we could solve the second problem instead, to get the angle such as $B'$ gets aligned with (AC) (and this angle is not $a_1$, because the radius is different unfortunately, and I have no idea what it could be)
Answer: The angular displacement between $A$ and $C$ is $a_2 - a_1$, therefore, the minimum (perpendicular )distance from the origin to line $AC$ is given by
$d_1 = r_1 \cos \dfrac{(a_2 - a_1)}{2} $
similarly the minimum (perpendicular) distance from the origin to $BD$ is given by
$d_2 = r_2 \cos \dfrac{(a_2 - a_1)}{2} $
Hence the distance between the two lines is
$d = d_2 - d_1 = (r_2 - r_1) \cos \dfrac{(a_2 - a_1)}{2} $
For the second part, point $B'$ is given by
$B' = r_2 (\cos \phi, \sin \phi ) = A + t (C - A) $
Since the distance of $B'$ from the origin is $r_2$, then $t$ must be the root of the following equation:
$\mathbf{A} \cdot \mathbf{A} + 2 t \mathbf{A} \cdot (\mathbf{C}-\mathbf{A}) + t^2 (\mathbf{C} - \mathbf{A}) \cdot (\mathbf{C} - \mathbf{A}) = r_2 ^2$
All the quantities can be computed, and the quadratic equation in $t$ can be solved using the quadratic formula resulting in two values of $t$ corresponding to point $B'$ and $D'$.  The negative value of $t$ corresponds to $B'$ and the positive value corresponds to $D'$.  To find the angles just use the $\text{ATAN2}$ function, so that
$\phi_{\text{B'}} = \text{ATAN2}( B'_x , B'_y)$
$\phi_{\text{D'}} = \text{ATAN2}( D'_x , D'_y)$
Comment: Draw triangle $AOC$, and find the altitude from $O$ to the base $AC$.
Comment: This works perfectly, but I wonder how did you come up with the formula for the perpendicular distance from the origin to the line?


Add all related content from entity reference with views

Question: I really hope someone can help me, because it's the last thing I have to do in this site, and I thought it would be more or less easy, but I can't get this to work.
Not even sure if this is the wright question, and sorry for some English.
My situation it's this one:
I have two content types: Books and Authors.
Books as a entity reference to authors.
In the node type Books, I want to display the book authors plus all their books.
As I use panels, I can do this simple or making a view.
But what I can't do, it's to display all the author's books in that node.
I can create a view with the authors and all their books, using views merge rows, to merge the books.
But if in the contextual filters I use the nid, all I get it's the same book from the node.
So I'm trying to create a attachment to display just the books titles from those authors, but honestly, I'm completely lost !
Perhaps someone could give me some examples how to achieve this.
Thanks
Comment: Well, I've manage to get all the books with the attachment by adding in the contextual filter with the relation : Content:Nid > Content referencing Content from field entity reference to the author. However, now I still get a duplicate book node, ex: if the author only has one book, the book still shows....
Answer: Click the "More" link in the contextual filter. That fieldset is collapsed by default but you'll find the option to make exclusions there. You may have to exclude the current node ID separately--not sure about that.


How to read values from dictionary > on the basis of key passed using linq

Question: I have got a dictionary object as below:
Dictionary<String, List<Component>> dicCountries = new Dictionary<string, List<Component>>();

Now dicCountries is grouped on the basis of region ID, so I want to get all the List<Component> when I pass region ID.
Is it possible using Linq or do we need to use C# code to read it.
Please suggest!!
Comment: What do you mean by : `Now dicCountries is grouped on the basis of region ID`  ? do you have `regionID` as key in dictionary ?
Comment: @Habib, Yes Region ID is key and List are the collection of coutnries components, so like first key is "123" which represent "ASIA", so all the countries of asia will be there in List
Answer: var result = dicCountries.FirstOrDefault(x => x.Key == regionID).Value;

or
var result = (from x in dicCountries
where x.Key == regionID
select x.Value).FirstOrDefault();

Personally, I think the first one is cleaner. And by the way, Linq or no Linq.. it's all C#
UPDATE:
Actually, when using FirstOrDefault, it might return a NULL and therefore you should check the code first. So:
var result = dicCountries.FirstOrDefault(x => x.Key == regionID);

List<Component> components = null;
if (result != null)
{
    components = result.Value;
}

UPDATE 2:
I just remembered.. KeyValuePair<TKey, TValue> cannot be compared with null and you would need to check like this instead:
if (!result.Equals(default(KeyValuePair<string, List<Component>>)))

which just goes to prove... sometimes LINQ is not the cleanest solution. In most cases it is, but not in this case.. so go with the easier solution:
List<Component>() list;
if (dicCountries.ContainsKey(regionID))
{
    list = dicCountries[regionID];
}

Comment: thanks for your reply as I am looking for List type of return, how can I read using above code as it returns KeyValuePair
Comment: Thank you it's really use for us


How to achieve this zooming and unzooming functionality?

Question: I am looking to achieving this effect from Mozilla Firefox, when clicking on a video thumbnail. I would also like to achieve this with photos as well. Check this link and click on the thumbnail play button.
Comment: Tony, would you try describing the effect that you saw, in a question edit? I cannot see it at the link here, so assume that a Mozilla redesign has removed what you wanted to do. You may know that link-only questions here tend to be closed, so if you can beef this up a bit, that may help.
Answer: If you're using jQuery, there's lots of plugins to provide zoom style thumb-to-full-size effects. For example fancybox (see the third single image example on this page).
Alternatively, if you want more control, you could build the features yourself without too much effort:

Load the full image with ajax
Replace the src attribute of your thumbnail image (make sure its a fixed size)
Do the zoom by animating your width/height (& position if necessary) to the full size of the final image

Note that depending on what you're showing (for example if you were doing this for embedded flash video), you may need to swap the order of 2 & 3, by zooming the thumbnail (or some other place holder image) & then swapping in the final, full size content.


Prove or disprove $a^{10}=b^{10} \pmod{10\alpha}$

Question: Today I got a question:
Find the remainder when $2^{1990}$ is divided by $1990$
I tried as follows
$199$ is a prime, so by Fermat's theorem
$$2^{199}\equiv 2 \pmod{199}$$
Now I used if $$a\equiv b \pmod{\alpha}$$
Then $$a^{10}\equiv b^{10}\pmod{ 10\alpha}$$
Then$$2^{1990}\equiv 2^{10}\pmod{1990}$$
Which is the answer.
But I am not able to prove the property that I had used. I would be pleased if someone would help me to prove or disprove the property. If I had used a wrong property then please provide other method to find the remainder.
Comment: $1990$ is not prime... It is obviously a multiple of $10$.
Comment: i was providing refrence of question but main question is to prove or disprove property I used
Comment: As a record, [this](http://math.stackexchange.com/questions/545759/what-is-the-remainder-when-21990-is-divided-by-1990?noredirect=1&lq=1) question already has many alternative methods to prove the question in reference, but does not address the titular question.
Comment: The property doesn't hold, consider for example $a = 2,\, b = 5,\, \alpha = 3$. Then $a^{10}$ is even and $b^{10}$ is odd, so they can't be congruent modulo any even integer.
Comment: You can say that if $a\equiv b\pmod x \implies a^n\equiv b^n\pmod x$  But you do not change the modulo.
Answer: The claimed property is false. Let's look at the exact instance you attempt to use here, namely $\, a \equiv 2\pmod{\!199}\Rightarrow\, a^{\large 10}\equiv 2^{\large 10}\pmod{\!1990}.\,$ Notice that $ $ odd $\,a:= 201 \equiv 2\,\pmod{\!199}\,$ $\, $ however we have $ $ odd $\,a^{\large 10}\!\neq 2^{\large 10}\!+1990k= $ even, so it fails. Below is one correct proof.
By Fermat $\, 2^{\large 4}\! \equiv 1\pmod{\! 5},\,\  2^{\large 198}\!\equiv 1\pmod{\!199}\ $ so $\ \color{#c00}{2^{\large 396}\equiv \bf 1}\pmod {5\cdot 199}$
Therefore $\,\ {\rm mod}\,\ \color{#0a0}{5\cdot 199\!:\,\ 2^{\large  1998}}\! \equiv  2^{\large 9+5(396)}\! \equiv  2^{\large 9} (\color{#c00}{2^{\large 396}})^{\large 5}\!\equiv 2^{\large 9}{\color{#c00}{\bf 1}}^{\large 5}\!\equiv \color{#0a0}{2^{\large 9}} $
So $\,\ 2^{\large 1990}\!\bmod 1990\, =\, 2\,(\color{#0a0}{2^{\large 1989}\!\bmod\ 5\cdot 199})\, =\, 2(\color{#0a0}{2^{\large 9}}) = 2^{\large 10} =1024$
We used  $\ ca\bmod cn =\, c\,(a\bmod n)\ $ in the prior line. See here for more on that.


$(\sin \alpha + \cos\beta)^2 + (\cos\alpha - \sin\beta)^2 - 2\sin(\alpha+\beta) = 2$

Question: I need to show that the following is true:
$(\sin a + \cos b)^2 + (\cos a - \sin b)^2 - 2\sin(a+b) = 2$

$\sin^2a + 2\sin a\cos b + \cos^2b + \cos^2a -2\cos a\sin b + \sin^2b - 2(\sin a\cos b + \cos a\sin b)=$
$\sin^2a + 2\sin a\cos b + \cos^2b + \cos^2a -2\cos a\sin b + \sin^2b - 2\sin a\cos b -2\cos a\sin b=$
$1 + 1 - 4\cos a\sin b = -4\cos a\sin b + 2$
..... I always get:  $-4\cos a\sin b + 2$
I should get:
$-2\cos\alpha\sin\beta + 2\cos\alpha\sin\beta + 2 = 2$
Does anyone get 2 as an answer? I don't know what I'm doing wrong(?!)
Thank you in advance!
Comment: i think the answer must be zero.
Comment: @SantoshLinkha Think again. That's a = sign not -
Comment: oh!! I forgot the initial squares of sines and cosines
Comment: Hint: (sin[a]+cos[b])^2 = sin^2[a] + cos^2[b] + 2*sin[a]*cos[b] and sin^2[a]+cos^2[a]=1
Comment: @Santosh Linkha: It should be 2. It seems like an easy problem and it is, but I just can't get that number.
Comment: you didn't note that the change of variables in the second square and got $-4cosαsinβ$
Comment: @AndréNicolas: Your comment looks to me like "[Math Processing Error]  {}{}{}{}{}{}". What's that supposed to mean? Am I missing something?
Comment: The comment was too short, so I just added some invisible spaces that for some reason give your computer trouble. So I will delete. I wrote "I get $2$."
Comment: @AndréNicolas: I'm sorry, but this is how I see your comment: "The comment was too short, so I just added some invisible spaces that for some reason give your computer trouble. So I will delete. I wrote "I get
[Math Processing Error]." Is it my computer's problem? (I've never had it before :(
Comment: Well, all I can say is that on my computer, the comment just above yours comes through with no problem. The only TeX content it has is dollar signs around the 1, and that gave my computer no trouble.
Comment: @AndréNicolas: Thank you for letting me know! I removed an extention from google chrome, which was apparently preventing me from seeing your *complete* comment.
Comment: By the way, edits to the post have made the answer different. A $+$ has been replaced by a $-$. This should be fixed.
Comment: @André Nicolas The author says in the comments below that it was changed on purpose but it doesn't seem to be right.
Answer: If your "job" is to prove that the left side is equal to the right side, then the minus in the second term needs to be a plus (answer by rbm).
Consider both versions: Plus
and Minus and you can see that the plus version is true.
One more possibility is given in this comment
If however the expression is correct, you may want to find the solutions to this problem (which means that you equation is true, but maybe not for all pairs of $\alpha, \beta \in \mathbb{R}$, i.e. there are certain restrictions on how you can choose a combination of $\alpha$ and $\beta$ so that the left side equals to 2):
$$(\sin\alpha + \cos\beta)^2 + (\cos\alpha - \sin\beta)^2 - 2\sin(\alpha + \beta) = 2 \\
\sin^2\alpha + 2\sin\alpha\cos\beta + \cos^2\beta + \cos^2\alpha - 2\cos\alpha\sin\beta + \sin^2\beta - 2\sin(\alpha + \beta) = 2 \\
(\sin^2\alpha + \cos^2\alpha) + (\sin^2\beta + \cos^2\beta) + 2(\sin\alpha\cos\beta - \cos\alpha\sin\beta) - 2\sin(\alpha + \beta) = 2 \\
1 + 1 + 2\sin(\alpha - \beta) - 2\sin(\alpha + \beta) = 2 \\
2 + 2(\sin(\alpha - \beta) - \sin(\alpha + \beta)) = 2 \\
2(\sin(\alpha - \beta) - \sin(\alpha + \beta)) = 0 \\
\sin(\alpha - \beta) - \sin(\alpha + \beta) = 0 \\
\sin(\alpha - \beta) = \sin(\alpha + \beta) \\
\implies $$
$1° \space \alpha - \beta = \alpha + \beta \implies 2\beta = 0 \implies \alpha \in \mathbb{R}, \beta = 0$
since $\sin(\pi - x) = \sin(x)$ :
$2°\space \pi - (\alpha - \beta) = \alpha + \beta \implies \pi = 2\alpha \implies \alpha = \frac{\pi}{2}, \beta \in \mathbb{R}$
Answer: Since
$(\sinα + \cosβ)^2 + (\cosα + \sinβ)^2 - 2\sin(α+β) = $
$(\sinα)^2 + (\cosβ)^2 + 2\sinα\cosβ + (\cosα)^2 + (\sinβ)^2 + 2\cosα\sinβ - 2\sin(α+β)$
and
$(\sinα)^2 + (\cosα)^2 = 1$
then
$((\sinα)^2 + (\cosα)^2) + ((\cosβ)^2 + (\sinβ)^2)  = 2$
and since $2\sin(a+b) = 2\sin(a)\cos(b) + 2\cos(a)\sin(b)$
then
$2\sinα\cosβ  + 2\cosα\sinβ - 2\sin(α+β)  = 0$
so the answer is $2 + 0 = 2$
Comment: @user114141: If you really want a $-$ in the second, you will need $-2\sin(\alpha-\beta)$ at the end.
Comment: (sina + cosb)^2 + (cosa - sinb)^2 - 2sin(a+b) = 2 (I corrected the equation and I appologize for the inaccuracy)
Comment: Are you sure the second term has minus?
Comment: Yep, and that's the reason why I can't get 2 as an answer. Apparently I didn't make any mistake this time.
Comment: I don't think thats correct then if the second term is cos(a) - sin (b)


Is the multimodal as in multimodal machine learning the same as that as in multimodal distribution?

Question: The multimodal distribution is a distribution with multiple modes as shown below.

It reminds me of the multimodal machine learning where multimodal implies multiple types of information, just like that in multimedia, thus I wonder if multimedia machine learning or multimedia deep learning would be more appropriate?
Does the multimodal machine learning have some connections with the multimodal distribution?
Answer: They're unrelated. So-called multimodal machine learning operates on multiple input modalities. That is, input signals of different types (e.g. auditory and visual input). Multimodal distributions have probability density/mass functions with multiple modes (i.e. peaks). The existence of multiple input modalities doesn't imply anything about multiple modes in the input distribution, or any other distribution.


Is this solvable for $d$? $r = \frac{1}{n}\frac{\sin(n\pi d)}{\sin(\pi d)}$

Question: Is this solvable for $d$?
$r = \frac{1}{n}\frac{\sin(n\pi d)}{\sin(\pi d)}$
$n$ is an integer, use $n = 2$ if that makes it significantly easier.
Inspired by this EE question:
https://electronics.stackexchange.com/questions/669376/what-is-the-formula-for-measuring-squarewave-duty-cycle-from-a-spectrum/669419#669419
(no need to watch the video, look at the answers)
Answer: If $n=2$, then using $\sin2u=2\sin u\cos u$ we get $r=\cos\pi d$, whence $d=(1/\pi)\arccos r$.
Comment: Of course this only gives real $d$ if $r\lt 1$ If $r=1$ we would need to cancel zeros of $\sin(\pi d)$.
Comment: Yes, 0 < *r < 1


Intel Rapid Storage Technology - Raid5 is very slow

Question: I build a computer with a raid5, using the motherboards raid controller (ASUS P7H57D-V EVO - intel Rapid Storage Technology). The read and write are however very slow, when using the raid controller :( - I am using Windows 2008 R2, and when using the windows software raid, it was ok in speed - so there must be an issue with the controller? Im using 6 disks on 2TB each.
Do anyone have any idea why its so slow, and how to fix it? I rather not pick the easy solutiuon of "just buy a raid controller" :|
If you need more info about my setup, please just ask.
Thanks :)
Comment: Not a solution, but you really shouldn't be using RAID-5 with multi-terabyte drives. You're quite likely to have a failure during rebuild, see http://www.zdnet.com/blog/storage/why-raid-5-stops-working-in-2009/162. With drives as cheap as they are, using RAID-10 is far safer (and performs much better for writes).
Comment: This is why its recommended on linux to get MDADM to run a badblock check every few weeks. echo check >> /sys/block/mdX/md/sync_action
Comment: Provide clearer explanation on what has changed, what has not, and more precise speed measurements ("very slow" is quite subjective).
Comment: @rmalayter, note that most newer drives are a couple orders of magnitude less likely to have an error; which is not accounted for in the linked article. URE of 10^16 is pretty common, and 10^17 is being seen in common SATA drives. I've seen enterprise SAS drives quoted as high as 10^21.
Comment: Very bad question. What is "very slow"? (rhetoric question)
Comment: @Chirs S, the Seagate barracuda XT and Western Digital Caviar Black are still rated at URE=10^14. These are the mainstream multi-terabyte "volume" SATA drives from each vendor. RAID5=bad on such drives (assuming the UREs from the manufacturer can be trusted). Of course "enterprise near-line" drives might be better (even if they use the same mechanisms, they might have more ECC in the firmware layer).
Answer: Did you just build the array? its possible that it is still syncing all the drives. on a 5x1TB array it took me 9 hours and during that time it was very very slow as there was a lot of background processing and writes.
Comment: Given no information from the OP on the state of the array syncing going on ins a likely culprit. It takes ages of time to sync a large raid and during this time - obviously - a lot of the IO budget is tied up for the sync process.
Answer: Check driver versions. It should not be high performance compared to a controller, but it should be comparable to windows own RAND implementation.
Comment: I did install the latest version of the driver - no change :(


When you flick a trumpet bell what should it sound like?

Question: I've heard conflicting stories on this - some say that if you flick your trumpet bell and it rings (goes "ping") then it's the sign of a Quality Trumpet.
Others are horrified if the bell goes ping, insisting instead that their trumpet bell should not produce any sort of pitched or resonant sound when it is flicked.
Who is right? Should a flicked trumpet bell go thud or ping? Or does it not really matter?
Comment: I'm not a brass player at all, so I wonder: How often does one encounter a trumpet with a bell that rings?  The few times I've handled trumpets (and kin) they seemed to be made of a relatively soft thin brass that wouldn't really lend itself to ringing. Very different from the hard bronze percussion instruments (cymbals, singing bells, etc.) I have played.
Comment: I'm no brass player either, but one would imagine the last thing you want from a wind instrument would be specific resonant tones that continue after you've stopped playing. That would say 'dead is best'.
Answer: Here's some discussion of the topic.  Including a respected instrument maker who would deliver a ringing bell or a dead one to the customer's preference, without comment.
Bell ringing - does yours?
I also recall a report in Scientific American where bells made from various materials were compared.  A stainless steel one proved unrewarding to play, one made from lead gave a bright sound (but obviously had practical disadvantages!)
There are basics of instrument construction - the physical dimensions and arrangement of the tubing, the flare of the bell - which I think can be agreed to be predominant factors in the instrument's quality.   Then there are details which can border on being fads - heavy clamps to 'couple' the mouthpiece and mouth pipe, bell sections stripped of lacquer...    I tend to put ringing/non-ringing bells in this category.  Pay your money, make your choice.
Comment: I think the article on bell materials was authored by Dr Schilke - here's the link: https://www.everythingtrumpet.com/schilke/Brass_Clinic.html#Materials
It specifically mentions tapping the bell...   Also mentions tempering the bell to change its sounds.
Comment: I wonder how far the current trend against lacquer is based on that one article, and whether Dr Schilke's results have been reproduced?
Comment: @BrianTHOMAS this article could be the answer IMO
Answer: Every object has a resonant frequency.  If you suspend a trumpet from various points and tap the bell sharply (in engineering terms, a Delta Function), the trumpet will vibrate at its fundamental body frequency -- which is not in any way related to the airstream fundamental frequency!  Whether that fundamental (or the first few harmonics) are in the audible range, I don't know.  Further, since unlike, say, a glass harmonica, the trumpet is not a simple shape, I would suspect that the energy quickly breaks out into lots of local modes of very low amplitude.
Comment: Does **every** object have a resonant frequency? What about a down pillow? Or a tree leaf? Or a burlap sack?
Comment: @CarlWitthoft I think it's true for materials that have a non zero elastic modulus. Purely viscous material won't. Of course when is way greater than the former then it's so damped that's it's hard to define a "real" resonance.
Comment: I'm not going to quibble with the "every object" bit, but it does seem like this answers a different question: *can* the bell vibrate, vs *is the sound of that vibration a mark of a good horn*.
Comment: Every object? My car has many, many resonances - proven by which bit rattles at what speed! I tap my mobile, and maybe its resonance is out of my hearing range - I can't tell. -1.
Comment: @ToddWilcox yes.   Trust me;  I have an ABD in physics :-)
Comment: So are things like pillows and leaves overdamped or something? They don't seem to have material properties that would allow harmonic motion after deformation.
Comment: @Tom  I agree with your assessment


Is it possible to use variable name and boolean value in method parameters?

Question: I have a few methods that have similar structure to each other. The only difference is the variable that is begin tested and which boolean condition is required.
public void OP_BCS(sbyte b)
{
    cv.PC += 2;

    if (cv._C == true)
    {
        cv.PC += (ushort)b;
    }
}

Is it possible to change the above code to something similar to what I have below (syntax might be incorrect, but should work in explaining what I mean)
public void OP_Branch(variable name, boolean condition, sbyte b)
{
    cv.PC += 2;

    if (variable == condition)
    {
        cv.PC += (ushort)b;
    }
}

I'd be able to make all the different combinations I need simply by giving the method a few extra parameters.
Comment: Consider making a `Dictionary`.
Comment: @SusiKette - your code is not very readable - consider using m ore meaningful names?
Comment: Perhaps [lambdas](https://stackoverflow.com/questions/167343/c-sharp-lambda-expressions-why-should-i-use-them) ?
Answer: Why not just take a bool as a parameter?
public void OP_Branch(bool condition, sbyte b)
{
    cv.PC += 2;

    if (condition)
    {
        cv.PC += (ushort)b;
    }
}

Then when you call it, you do the comparison in the method call:
OP_Branch(variable == condition, b);


Should allowing multiple DVs to covary in SEM influence beta coefficients?

Question: I am running a replication study to test a model with 8 IVs and 3 DVs (all variables are continuous).
In the initial study, I had a moderate sample (≈ 200), and thus relied upon multivariate multiple regression.
In this replication study, my sample is considerably larger (≈ 1500).
Importantly, the 3 DVs are moderately correlated (r = .10 to .50), and I have been advised to use SEM to help control for the inter-correlation between the DVs.
I downloaded AMOS, constructed my path model, and convaried the error terms for the DVs.
This was my first attempt at SEM path analysis, though to my surprise, the beta coefficients were exactly the same as when I ran 3 test regression analyses (one for each DV) separately.
I appreciate that this is a beginners question, but where have I gone wrong?
Have I:
a) ran the model incorrectly
b) misunderstood how I should control for the covariance between the DVs
c) misunderstood the effect that controlling for covariance should have on the results
Any advice would be greatly appreciated
Answer: I think (c).
Allowing the outcomes to covary is appropriate. If you don't, the model is wrong (and you'd see this in the fit statistics).
Your results should  (very close to) exactly the same as if you did a multivariate regression - which isn't a surprise, as you fitted the same model. (And by results I mean estimates, standard errors, CIs, etc).


(Jade) a href that has its link as the displayed text

Question: The relevant line in my code is: a(href = data[i][propt] ) data[i][propt]. data[i][propt] stores the URL, for instance, www.google.com. However, this way, what is shown on the webpage is a clickable data[i][propt] that directs to www.google.com. But what I wanted is a clickable www.google.com that directs to www.google.com. Is this possible?
Answer: Try:
a(href = data[i][propt]) #{data[i][propt]}

or:
a(href = data[i][propt])= data[i][propt]


Is this an immediate consequence of the Straddle Lemma?

Question: As main book, I'm using Bartle, Introduction to Real Analysis (2011 4 ed). Exercise 17 Section 6.1, p 171 asks you to prove the Straddle Lemma:

Let $f:I\rightarrow\mathbb R$ be differentiable at $c\in I$. Establish the Straddle Lemma: Given $\varepsilon >0 $ there exists $\delta >0$ such that if $u, v\in I$ satisfy $c-\delta \lt u\leq c\leq v\lt c+\delta$ then we have $|f(v)-f(u)-(v-u)f'(c)|\leq \varepsilon (v-u).$
[Hint: The $\delta$ is given by Definition 6.1.1. Subtract
and add the term $f(c) - cf'(c)$ on the left side and use the Triangle Inequality.]

It is sufficient to know the formal definition of derivative to prove this result. Later, in exercise 18 of section 6.2, p 180 (that is based on the Mean Value Theorem and some of its consequences) asks

Let $I:=[a,b]$ and let $f:I\rightarrow\mathbb R$ be differentiable at $c\in I$. Show that for every $\varepsilon >0 $ there exists $\delta >0$ such that if $\;0<|x-y|\lt \delta$ and $a \leq x \leq c \leq y \leq b$, then
$$\left|\frac {f(x)-f(y)}{x-y}-f'(c)\right|\lt \varepsilon$$

Is this a direct consequence of the Straddle Lemma?
I didn't get to anything keeping distance from the Straddle Lemma and trying to use the Mean Value Theorem. I'm unsure about using the Straddle Lemma firstly because it gives me a not strict inequality and the second exercise has a strict inequality, and secondly because I'm not using any "tools" provided from the respective section. Is the Straddle Lemma useful? If so, how can I end up with a strict inequality? If not, any hints would be appreciated. Thank you in advance.
Comment: Strict inequality: Apply the Lemma with $\varepsilon / 2$ instead of $\varepsilon$. Also you can not apply the mean value theorem as $f$ is only assumed differntiable at $c$, not on any interval.
Comment: @PhoemueX you mean using $\varepsilon /2$ in the Lemma and then just pointing out that $\varepsilon /2 \lt \varepsilon$?
Comment: Yes, that is exactly what I meant.
Comment: If you suppose $u \neq v$, the straddle lemma can be restated with "$<$". See Yee/Vyborny _The Integral $\dots$_ (2000), p. 46 .
Comment: The second part is an immediate consequence of the Taylor expansion about the point c.
Answer: You don't need Straddle Lemma.

Given $ε>0$, let $δ =δ(ε)$ be as in Definition 6.1.1 on p 161 (see bottom), and let $x<c<y$ be such
that $0<|x−y|<δ$. The trick here is to rewrite $\left|\dfrac{f(x)-f(y)}{x-y}-f'(c)\right|$, and exploit that $\left(\dfrac{\color{red}{x-c}}{x-y}+\dfrac{\color{skyblue}{c-y}}{x-y}\right) = 1$.

$\begin{align} \left|\frac {f(x)-f(y)}{x-y}-f'(c)\right| & = \left|\frac{f(x)\color{limegreen}{-f(c)}}{x-y}+\frac{\color{limegreen}{f(c)}-f(y)}{x-y}-\left(\frac{\color{red}{x-c}}{x-y}+\frac{\color{skyblue}{c-y}}{x-y}\right)f'(c)\right| \\
&\leq\left|\frac{f(x)-\color{limegreen}{f(c)}}{x-y}-\frac{\color{red}{x-c}}{x-y}f'(c)\right|\color{limegreen}{+}\left|\frac{\color{limegreen}{f(c)}-f(y)}{x-y}-\frac{\color{skyblue}{c-y}}{x-y}f'(c)\right|\\
& \text{Notice that both} \frac{\color{red}{x-c}}{x-y}, \frac{\color{skyblue}{c-y}}{x-y} \text{ are positive. And  factor them out }. \\
& = (\frac{\color{red}{x-c}}{x-y})\left|\frac{f(x) - f(c)}{\color{red}{x-c}} - f'(c) \right| +(\frac{\color{skyblue}{c-y}}{x-y})\left|\frac{f(y) - f(c)}{\color{skyblue}{c-y}} - f'(c)\right|  \\
& < (\frac{x-c}{x-y} +  \frac{c-y}{x-y})ε \\
& \qquad =ε \end{align}$
Note that if one  of $x$ and $y$ (but not both) equals $ε$, the conclusion still holds.
Comment: https://math.stackexchange.com/q/1273269


How to hide svchost.exe (dos prompt) when executing a scheduled task in Windows

Question: I created a java program that will pop up a dialog, and scheduled it as a task. Everything works fine except when the scheduled java program runs and the dialog pops up, there is another window (svchost.exe) hanging behind the dialog box and doesn't go anywhere until the java program finishes its execution. The program is running in Windows XP.
How can I avoid that dos prompt?
Thanks
Answer: One word of warning (posting as an answer so I can get fancy links and for length): Services which pop up UI are basically security holes waiting to be exploited (search for "shatter attack" for more information).  That's why in Windows Vista and beyond services cannot display UI on the desktop (services run in session 0, the interactive user runs in session 1).
More importantly, there are several scenarios in Windows XP where your application will fail to work:  If there are multiple users on the computer logged on at once (fast user switching) or if the machine is a server 2003 machine running with the terminal server role your UI won't pop up in the interactive user's session.
This article talks about the session 0 isolation issue and how to work around it.
Answer: If you want your Java program to have no console window, you need to launch Java using javaw, not java.
Answer: Create a shortcut for the thing you want to schedule.  In the shortcut's properties dialog, Select Run Minimized in the shortcut tab.  When scheduling this shortcut, make sure you refer to the shortcut, it ends in .lnk  Browsing for it may bypass the shortcut for what the shortcut points to.  Source: http://ask.metafilter.com/18994/Windows-Batch-File-Run-Minimized


error while using FREAK

Question: I'm trying to create Descriptor extractor using FREAK. but
at the following line:
freakExtractor = cv2.DescriptorExtractor_create('FREAK')
I get an error saying:
freakExtractor = cv2.DescriptorExtractor_create('FREAK')
AttributeError: 'module' object has no attribute 'DescriptorExtractor_create'
can someone tell me what is the exact problem and why i'm getting this error?
I'm using ubuntu 12.10 with opencv 2.4.3 and python 2.7.
Comment: It worked for me. Not getting any errors. Try using "SIFT", "STAR" instead of "FREAK"
Comment: And just to make sure check the version of your python opencv again. print cv2.__version__
Comment: @Froyo the AttributeError would clearly indicate there is no function called DescriptorExtractor_create. vineetrok: try to 'print dir(cv2)' and see if the function is inside.
Answer: I think,
cv2.DescriptorExtractor_create('FREAK')

is not a part of python interface, just use the latest opencv for that then it will work or you simply can write the code in c++ which is availabe in that version in c++.

error while using FREAK


Gstreamer videoconvert color conversion wrong?

Question: I'm launching a gst-launch-1.0 that captures camera images with nvgstcamera. The images are encoded to VP9 video. The video is tee'd to a filesink that saves the video in a webm container and to a VP9 decoder that pipes the images into an appsink.
Later, I want to extract frames from the saved video and run them through the application again. It is important that the frames are absolutely identical to the ones that were piped into the appsink during video capture.
Unfortunately, the decoded frames look slightly different, depending on how you extract them.
A minimal working example:
Recording:
$ gst-launch-1.0 nvcamerasrc ! "video/x-raw(memory:NVMM), format=NV12" ! omxvp9enc ! tee name=splitter \
  splitter. ! queue ! webmmux ! filesink location="record.webm" \
  splitter. ! queue ! omxvp9dec ! nvvidconv ! "video/x-raw,format=RGBA" ! pngenc ! multifilesink location="direct_%d.png"

Replaying with nvvidconv element:
$ gst-launch-1.0 filesrc location=record.webm ! matroskademux ! omxvp9dec \
! nvvidconv ! pngenc ! multifilesink location="extracted_nvvidconv_%d.png"

Replaying with videoconvert element:
$ gst-launch-1.0 filesrc location=record.webm ! matroskademux ! omxvp9dec \
! videoconvert ! pngenc ! multifilesink location="extracted_videoconvert_%d.png"

Testing image differences:
$ compare -metric rmse direct_25.png extracted_nvvidconv_25.png null
0

$ compare -metric rmse direct_25.png extracted_videoconvert_25.png null
688.634 (0.0105079)

nvvidconv:
videoconvert:
My guess is that this has to do with the I420 to RGB conversion. So videoconvert seems to use a different color conversion than nvvidconv.
Launching the pipeline with gst-launch -v shows that the element capabilities are basically the same for both replay pipelines, the only difference is that videoconvert uses RGB by default, while nvvidconv uses RGBA. Adding the caps string "video/x-raw,format=RGBA" behind videoconvert makes however no difference in color conversion.
Note that this is on an Nvidia Jetson TX2 and I would like to use hardware accelerated gstreamer plugins during recording (omxvp9enc, nvvidconv), but not during replay on another machine.
How can I extract images from the video that are identical to the images running through the pipeline during recording, but without the use of Nvidia's Jetson-specific plugins?
Answer: Check for colorimetry information - https://developer.gnome.org/gst-plugins-libs/stable/gst-plugins-base-libs-gstvideo.html#GstVideoColorimetry
Videoconvert for example take these into account when converting images. Depending on the caps found at input and output.
You probably have to check what the Tegra is doing here. Most likely there is a difference if the signal is interpreted as full range or tv range. Or the matrices differ from 601 and 709.
Depending on precision there may still be some loss during the conversion. For metrics at video codecs it may make sense to stay at YUV color space and use only RGB for display if you must.
Comment: Sorry, I don't remember :/ We moved to GigE cameras at some point and all these problems were replaced by new ones ;)
Comment: both nvvidconv and videoconvert use chroma-site=mpeg2,colorimetry=bt709. The TV range is an interesting idea, I will try to check.
Comment: What ended up being the solution to this? I am running into a similar problem when saving I420 frames as pngs vs jpegs using gstreamer pipelines (or when saving pngs in gstreamer vs opencv).


Invalidate Cache using VaryByCustom

Question: I want to invalidate cache using VaryByCustom attribute.
Following code is being used for cache setup.
<code>public override string GetVaryByCustomString(HttpContext context, string arg)
{
    if (!string.IsNullOrWhiteSpace(arg))
    {
        if (context.User.Identity.Name != null)
        {
            return context.User.Identity.Name;
        }
    }
    return base.GetVaryByCustomString(context, arg);
}
</code>
Comment: So where have you put this code, what's not working?
Comment: I've put it in Global.asx. I want to invalidate the cache base on the VaryByCustom attribute that this method gets as arg.
Comment: Essentially, I want to do this http://stackoverflow.com/questions/19196309/how-to-invalidate-cache-using-asp-net-mvc-4-0-donutoutputcache-varybycustom but without using the MvcDonutCaching package.
Answer: Are you using it like this:
Make sure you decorate your action with attribute:
<code> [OutputCache(Duration = 3600, VaryByParam = "*", Location = OutputCacheLocation.Server, VaryByCustom =
  "YourStringThatIsArgParamInYourGlobalAsaxMethod")]
  public ActionResult MyActionOnTheController(string myParam)
 {
 }
</code>

Invalidate Cache using VaryByCustom


Determine the specific type of an argument in Racket when the argument's type is a union type

Question: Apologies for the messy title—my technical vocab is lacking, and I was unsure of how to phrase this. How can I identify an argument in Racket as being of a certain type, without knowing either

the constructors of the type (for use with match)
a function type? (such as integer?) that checks if it is the specified type?

Specifically, imagine I have some function with the type (: fn : (All (a b c) (a -> c) (b -> c) (Listof (U a b)) -> Listof c)); we can imagine it being called as (fn fa fb xs). I would like this function to convert xs into a Listof c; it should do so by mapping each element x of xs to (fa x) if x is of type a, and (fb x) if x is of type b. For example, we might take in a list of strings and reals, and map the strings to their lengths, and the reals to the nearest integers.
In the specific case where I know that a is String and b is Real, I can write something like
(define (fn fa fb xs)
    (map (lambda (x) (if (string? x) (fa x) (fb x))) xs))

But this works only if I have a known function string? to check the type of x.
Is it possible to do what I'm suggesting in Racket?
Answer: There's no "type of" operation in Typed Racket, so the answer is no. However, you can pass a "decider" to fn to select which function should be used to apply for each element.
The -> form allows you to specify propositions for occurrence typing, so you can write this code:
#lang typed/racket

(: fn (All (a b c)
           ((U a b) -> Boolean : a)
           (a -> c)
           (b -> c)
           (Listof (U a b))
           ->
           (Listof c)))
(define (fn decider fa fb xs)
  (map (lambda ([x : (U a b)])
         (if (decider x) (fa x) (fb x)))
       xs))

Then you can invoke it:
(fn string? string-length add1 (list 1 "a" 23 "bc"))

;; '(2 1 24 2)

Thanks to Sam Tobin-Hochstadt for his help!


Congruence of first grade

Question: Solve the congruence $8x\equiv 10\pmod 6.$
Hello. My question is about of the solution. Because my Professor me indicated the solution:
$8x\equiv 10\pmod 6\iff 8x-6k=10$ for some $k\in \mathbb{Z}.$ Can use the Euclides algorithm? Thanks!
Comment: One, replace "any" with "some" please, as stated what you have written is plain wrong. Two, sure, do whatever you want.
Comment: Sorry. Ok, I 've managed.
Answer: Since the modulus is so small, just try $0,1,2,3,4,5$ mod 6 for $x$ and see that only $2$ and $5$ make $8x \equiv 10$ mod $6.$

Congruence of first grade


Modelbinder creates new instance of collection item instead of updating existing

Question: I want to create a dynamic form based on content from a CMS. The label of my fields (and also many more properties) will be generated in the CMS. To illustrate I statically create the view model within the controller GET action. With a custom model binder I will create the same structure of the view model for POST action.
Here are view models:
[ModelBinder(typeof(TestModelBinder))]
public class TestViewModel
{
    public TestViewModel()
    {
        this.Fields = new List<FieldViewModel>();
    }

    public string Title { get; set; }

    public IList<FieldViewModel> Fields { get; private set; }
}

public class FieldViewModel
{
    public FieldViewModel(string label)
    {
        this.Label = label;
    }

    public string Label { get; set; }

    public string Value { get; set; }
}

The index view:
@model Website.Models.TestViewModel

Title: @Model.Title

@using (Html.BeginForm())
{
    for (int i = 0; i < Model.Fields.Count; i++)
    {
        @Html.Partial("Field", Model.Fields[i], new ViewDataDictionary(ViewData)
                    {
                        TemplateInfo = new TemplateInfo
                        {
                            HtmlFieldPrefix = string.Format("Fields[{0}]", i)
                        }
                    })
    }

    <input type="submit" value="submit" />
}

The partial view for the fields:
@model Website.Models.FieldViewModel

@Html.LabelFor(model => model.Value, Model.Label)
@Html.TextBoxFor(model => model.Value)

The controller:
public ActionResult Index()
{
    var model = new TestViewModel { Title = "GET action" };
    model.Fields.Add(new FieldViewModel("Name"));
    model.Fields.Add(new FieldViewModel("E-Mail"));

    return View(model);
}

[HttpPost]
public ActionResult Index(TestViewModel model)
{
    return View(model);
}

And my model binder:
public class TestModelBinder : System.Web.Mvc.DefaultModelBinder
{
    protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
    {
        var model = new TestViewModel { Title = "POST action" };
        model.Fields.Add(new FieldViewModel("Name"));
        model.Fields.Add(new FieldViewModel("E-Mail"));
        return model;
    }
}

The GET action works as expected. But I have a problem while binding the model. After posting the form, I get the following error:
No parameterless constructor defined for this object.

Stack Strace:
[MissingMethodException: No parameterless constructor defined for this object.]
   System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
   System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +159
   System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +256
   System.Activator.CreateInstance(Type type, Boolean nonPublic) +127
   System.Activator.CreateInstance(Type type) +11
   System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) +275

[MissingMethodException: No parameterless constructor defined for this object. Object type 'Website.Models.FieldViewModel'.]
   System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) +370
   System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +151
   System.Web.Mvc.DefaultModelBinder.UpdateCollection(ControllerContext controllerContext, ModelBindingContext bindingContext, Type elementType) +569
   System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +974
   System.Web.Mvc.DefaultModelBinder.GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder) +33
   System.Web.Mvc.DefaultModelBinder.BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) +441
   System.Web.Mvc.DefaultModelBinder.BindProperties(ControllerContext controllerContext, ModelBindingContext bindingContext) +180
   System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Object model) +68
   System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +997
   System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +437
   System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +153
   System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +642

As the error message say, this is because FieldViewModel doesn't have a default constructor. But says also, that the DefaultModelBinder tries to create a new instance of a FieldViewModel? This feels weird, because I have created my model instance and filled the Fields list with 2 instances of FieldViewModel and I would expect that the model binder updates the existing instances instead of creating new ones...
After digging into the DefaultModelBinder I found the following line of code within the UpdateCollection while creating the innerContext:
ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, elementType)

If this line would look something like this, I think it would work:
ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(existingCollectionElement, elementType)

Is this the expected behavior? What can I do to get rid of this and use my existing instance within the collection? Overriding this seems not a good option, because this code is internal and I would copy many code, for this simple line. Is there maybe another way of doing what I want or am I doing something wrong?
Update: It is not a problem of the binding itself. When I would remove my constructor from FieldViewModel, then the posted values are correctly added into the Value property of the view models. The problem is, that the label property will be empty (because it creates a new instance and not take the one I've created in the custom modelbinder) and will be set to "Value" in both fields. At the end, the FieldViewModel should also implement the IValidatableObject interface and should be validated by the DefaultModelBinder. The available validators for each field is also defined in the CMS and will be added to the view model instance in the custom model binder. So also this case won't work actually because all added validators will be lost.
Answer: The solution is to create a custom model binder for the IList<FieldViewModel> and handle the model binding for the list:
public class ListModelBinder : System.Web.Mvc.DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var model = bindingContext.Model;
        var collectionBindingContext = new ModelBindingContext
        {
            ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, bindingContext.ModelType),
            ModelName = bindingContext.ModelName,
            ModelState = bindingContext.ModelState,
            PropertyFilter = bindingContext.PropertyFilter,
            ValueProvider = bindingContext.ValueProvider
        };

        return this.UpdateCollection(controllerContext, collectionBindingContext, model.GetType().GetGenericArguments()[0]);
    }

    private object UpdateCollection(ControllerContext controllerContext, ModelBindingContext bindingContext, Type elementType)
    {
        var collection = (IList)bindingContext.Model;
        var elementBinder = Binders.GetBinder(elementType);
        var modelList = new List<object>();

        for (var index = 0; index < collection.Count; index++)
        {
            var innerContext = new ModelBindingContext
            {
                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => collection[index], elementType),
                ModelName = CreateSubIndexName(bindingContext.ModelName, index),
                ModelState = bindingContext.ModelState,
                PropertyFilter = bindingContext.PropertyFilter,
                ValueProvider = bindingContext.ValueProvider
            };

            modelList.Add(elementBinder.BindModel(controllerContext, innerContext));
        }

        return modelList;
    }
}

And register this binder to the list in the global.asax:
ModelBinders.Binders.Add(typeof(IList<FieldViewModel>), new ListModelBinder());

Answer: As far as I understand you need to dynamically add/edit a collection to your parent entity.
For that I suppose you can check BeginCollectionItemHelper which will do in this case.
You can get an easy jumpstart here.
I suppose you won't even need the ModelBinder then and as per your illustrated FieldViewModel, the editor will look something like this:
@using (Html.BeginCollectionItem("Fields"))
{

        @Html.LabelFor(model => model.Value, Model.Label)
        @Html.TextBoxFor(model => model.Value)

}

And in the main View you can just call:
@foreach (var field in Model.Fields)
    { Html.RenderPartial("FieldEditor", field); }

Comment: Unfortunately this does not solve the problem. The model binding itself works. If I remove the constructor from my `FieldViewModel` then the data is correctly binded. The only problem is, that I will not have the `Label` property,  because I set the label within the model binder to all my field instances. If i simply remove my constructor, all works fine, but on postback the label for both fields will be "Value" (instead of "Name" or "E-Mail").


How can I sort a Javascript array alphabetically?

Question: I want to Sort the people alphabetically by last name. I'm curious if there's a more professional approach to doing that.
My Array :
const people = [ 'Bernhard, Sandra', 'Bethea, Erin', 'Becker, Carl', 'Bentsen, Lloyd', 'Beckett, Samuel', 'Blake, William', 'Berger, Ric', 'Beddoes, Mick', 'Beethoven, Ludwig', 'Belloc, Hilaire', 'Begin, Menachem', 'Bellow, Saul', 'Benchley, Robert', 'Blair, Robert', 'Benenson, Peter' ];

The code is working properly, but I am confused about why the split method returns inverse values.
Despite asking Poe for help, I am still confused.
The positions of the destructured variables were swapped by Poe when I asked for help but I haven't changed the code yet.
const alpha = people.sort((a, b) => {
    const [aFirst, aLast] = a.split(', '); // expected ["Bernhard", "Sandra"] Not [ 'Sandra', 'Bernhard' ]
    const [bFirst, bLast] = b.split(', '); // expected ["Bethea", "Erin"] Not [ 'Erin', 'Bethea' ]
    return aFirst > bFirst ? 1 : -1;
})
console.table(alpha);

Comment: If you are sorting by last name, why not just `people.sort()`?
Comment: Your destructuring assignment is putting last name into aFirst and first name into aLast, same for b
Comment: `'Bernhard, Sandra'.split(', ')` *is* `['Bernhard', 'Sandra']` and not the other way around. Splitting does not reverse the order.
Comment: Are we supposed to know who "Poe" is?
Comment: Split does not return inverse values.
Comment: @ mykaf  Not working properly and how can the results be reversed? (z to a)
Comment: @ Scott Marcus https://poe.com/ AI assistant.
Comment: How exactly is `people.sort()` not working properly? You would reverse it with `people.sort.reverse()`
Comment: @Luatic
in return aFirst > bFirst ? 1 : -1;  I used ( aFirst and bFirst ) not ( aLast and bLast ) to make the code work as I wanted.
back to the question:
I want to Sort the people alphabetically by "last name" not a first name.
Comment: @mykaf, Pls, note  I want to Sort the people alphabetically by "last name" not a first name.
Comment: Typically names are formatted *last, first* or *first last* (no comma).
Are your last names *before* or *after* each comma? Assuming before, `Array.sort()` will work just fine. You didn't give an expected output.
Comment: @mykaf
I've never noticed how names are formatted with commas before. This is a missing point .
You have taught me to look at the final results I expect before asking questions. Your effort is greatly appreciated . Thanks
Answer: Your array already contains strings of names where the last name is the first part of the string, so you can just call the .sort() method.
Oh, and your array contains a typo:
'Blake, 'William' should be: 'Blake, William'

const people = [ 'Bernhard, Sandra', 'Bethea, Erin', 'Becker, Carl', 'Bentsen, Lloyd', 'Beckett, Samuel', 'Blake, William', 'Berger, Ric', 'Beddoes, Mick', 'Beethoven, Ludwig', 'Belloc, Hilaire', 'Begin, Menachem', 'Bellow, Saul', 'Benchley, Robert', 'Blair, Robert', 'Benenson, Peter' ];

console.log(people.sort());
Comment: @AhmadTantawy Given the strings in your array start with the last name, it *is* that simple. What makes you think this doesn't work? What is the expected output, and what output do you get instead when using this approach?
Comment: @Scoot Marcus, Please note that I want to sort people alphabetically by last name. It's not that simple.
Sorry for the typo. It is a Typo error, but my code is correct. I will edit the question. Thanks for that.
Answer: The variables are simply mislabelled, see the following:
const alpha = people.sort((a, b) => {
    const [aLast, aFirst] = a.split(', '); // expected and got ["Bernhard", "Sandra"]
    const [bLast, bFirst] = b.split(', '); // expected and got ["Bethea", "Erin"]
    return aLast > bLast ? 1 : -1;
})

Comment: I missed how the sort method works when I tried to console.log a and b inside the sort function. Also, I've never noticed how names are formatted with commas before.
I Appreciate Your effort. Thanks


Cannot invoke 'append' with an argument list of type'(String)' in my firstViewController

Question: firstViewController. This is where the problem is. In my 'for loop' it is giving me an error. I have tried to use what Xcode suggested, but it isn't working. I still consider myself a beginner with Swift. I looked at other answers when people have posted the same question and I still can't solve my problem.
 import UIKit

var toDoItems:[String] = []

class FirstViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet var tasksTable:UITableView?

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return toDoItems.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        var cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cell")

        cell.textLabel?.text = toDoItems[indexPath.row]

        return cell
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func viewWillAppear(animated: Bool) {

        if var storedToDoItems : AnyObject?  = NSUserDefaults.standardUserDefaults().objectForKey("toDoItems") {

            toDoItems = []

            for var i = 0; i < storedToDoItems?.count(); ++i {
                toDoItems.append(storedToDoItems[i] as! String)
            }

        }

        tasksTable?.reloadData()
    }

}

This is my secondViewController.
import UIKit

class SecondViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var toDoItem: UITextField!

    @IBAction func addItemButton(sender: AnyObject) {

        toDoItems.append(toDoItem.text)

        let fixedToDoItems = toDoItems

        NSUserDefaults.standardUserDefaults().setObject(fixedToDoItems, forKey: "todDoItems")
        NSUserDefaults.standardUserDefaults().synchronize()

        self.view.endEditing(true)

    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func textFieldShouldReturn(textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }

    override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
        self.view.endEditing(true)
    }

}

Answer: When you load your to-do list array from NSUserDefaults, use if let to test if it's a [String] (that is, an array of strings), and then you won't need to cast it to a String later on, which might be contributing to your error. Try replacing your viewWillAppear method with this:
override func viewWillAppear(animated: Bool) {

    if let storedToDoItems = NSUserDefaults.standardUserDefaults().objectForKey("toDoItems") as? [String] {

        toDoItems = []

        for var i = 0; i < storedToDoItems.count; ++i {
            toDoItems.append(storedToDoItems[i])
        }
    }

    tasksTable?.reloadData()
}

While you're at it, there's a much nicer way to loop over the contents of an array in Swift (and many other languages):
override func viewWillAppear(animated: Bool) {

    if let storedToDoItems = NSUserDefaults.standardUserDefaults().objectForKey("toDoItems") as? [String] {

        toDoItems = []

        for item in storedToDoItems {
            toDoItems.append(item)
        }
    }

    tasksTable?.reloadData()
}

In this case however, you should be able to just set your variable directly from the loaded one:
override func viewWillAppear(animated: Bool) {

    if let storedToDoItems = NSUserDefaults.standardUserDefaults().objectForKey("toDoItems") as? [String] {
        toDoItems = storedToDoItems
    }

    tasksTable?.reloadData()
}

Comment: You should be able to add a `println(toDoItems)` as the last thing of the `if let` block to verify it correctly loaded your items.
Comment: What happens instead? If it's nothing, then the `if let` statement is probably failing (it can't find an array of strings in `NSUserDefaults`). Try adding an `else` to the `if let` to see if that is indeed the case. If it is, you probably haven't written to `NSUserDefaults` "toDoItems" (or what you have written isn't an array of strings).
Comment: This worked. Thanks @Robert. Now I am trying to get the array to show in the console. It isn't showing the element that i put in the array.
Comment: I guess I can use just a simple println() to print it to the console to show the elements.
Comment: I did that, but It still isn't showing the items that should be loaded.
Comment: Yes. Since I used the `else` statement, it adds the item to the array.


What is the best way to learn scales in order to improve improvisation/writing of lead guitar parts?

Question: Where I'm at skill-wise

Played guitar on-and-off for about 5 years
Up until a year ago had only really learned by playing from tabs
Have been undertaking bi-weekly guitar lessons for just over a year
I don't know which notes are which on the fretboard, I just play using common shapes and experience

What I want to do
I want to be able to improvise and create my own melodies/lead parts on guitar using scales, but have struggled to pick up non-theory based ways of learning them, primarily in terms of how to apply them. I've previously tried using the major/minor pentatonic shapes (I guess this is a common thing). Is this one of the better ways for someone like me to learn? Or is there a better way? Someone told me that diatonic scales are the most useful in terms of jamming etc. I've also seen the pentatonic shapes referred to as a 'parlor trick', which makes me feel like it's not the most useful. My guitar teacher encouraged me to use the pentatonic shapes, but he's probably not the most experienced in terms of teaching, so I don't know if there's a better way. I found the pentatonic shapes were making me feel a bit confined, perhaps because I wasn't combining the shapes much, of that I just didn't understand the theory. Either way, I feel that it's worth finding out what other common techniques are used to teach learners. In terms of the style of music, I'm just looking to create music that is fairly 'pop' sounding, occasionally touching upon fairly standard rock.
Answer: Your teacher did the right thing teaching the pentatonic first. 5 notes is enough to learn to  start with. But if you're finding it restrictive, now is the time to add in more notes.
Knowing what notes are what on the fretboard will be of some use and is not that difficult, so you should glance over it and have the ability to do it if you have to. On the A string, for example, we have A A# B C C# D D# E F F# G G# and back to A on the 12 fret.
but knowing which note is which within the pentatonic scale shape will be far more useful, and should become second nature. The  pentatonic major scale consists of I II III V VI I (without IV or VII) which in C is C D E G A C (without F or B.) This is of course the pentatonic scale that you play when you are allowed to play all the notes on the 5th fret. The root note in that position (in this case C) is on the 3rd string.
Draw out (or print from the internet) three copies of a pentatonic scale shape. This can be  whatever position you are most comfortable with, but I suspect it will be the ones where you have a certain fret in which you can play all the notes.

Take that C major pentatonic scale and pencil in all the B's and F's. You now have a C major diatonic scale, the full 7 white notes on the piano.
Now, take your second copy of the same position, and pencil in all the B's and F#'s. This is the G major diatonic scale. (Made by adding two notes to the C major pentatonic! Weird, but clever.)
Finally, take the third copy, and pencil in all the Bb's and F's. This is the F major diatonic scale. (From the C major pentatonic. Again, weird but clever.)

These new scales will give you more flexibility, especially in playing single semitone intervals. Include these in your solos bit by bit, starting as trills, and your ear will confirm if you have the theory right.
Now, why did I make you do 3 copies?
Well, take your C diatonic major scale (which is of course the same notes as A diatonic minor, it just depends, which you consider to be the root.)
You now have two ways to think about turning it into an F diatonic major scale. You can either move the whole shape up 5 frets/ down 7 frets OR you can stay at the same place on the neck and turn all the B's into B flats.
You also have two ways to thing about turning it into G diatonic major scale. You can either move the whole shape down 5 frets / up 7 frets OR you can turn all the F's into F sharps.
Of course, with the second method the root note will change to a different string, but it's useful to appreciate the patterns in the notes.
And that's the diatonic. If you get bored with that, you can start adding in accidentals. These are often associated with different styles. For blues there is the blue note, Eb if you are in the scale of C major / A minor. G# and F# are other extra notes you may want to add in. You can find these theoretically with pen and paper, but you can also find them on the fretboard by ear.
But in order to orient yourself with these new notes, it helps to know which note you of the pentatonic you are playing. It will be more useful to say to yourself "that's the third, I need to go outside the pentatonic to play the fourth" than to say:
I'm in C major pentatonic, I know where E is, I want to play an F
I'm in Db major pentatonic, I know where F is, I want to play a Gb
I'm in D major pentatonic, I know where F# is, I want to play a G
etc, through all the 12 possibilities.
Because all 12 of these possibilities are equivalent to the previous statement.
EDIT: Now the OP has confirmed he was asking about scales, I'll throw in this handy diagram of some of the "pencilled in" scales.
It shows two positions of the pentatonic scale (marking the fret on which all notes can be played which would be 5th fret if you are in C major.) The additional notes F and B required for C major diatonic are shown in red.
Where you see red-black on consecutive frets on the same string, that's B-C (generalises to VII-I.)
Where you see black-red on consecutive frets on the same string, that's E-F (generalises to III-IV.)
For ease of understanding it is assumed you will play each of the following options separately:
(1) Use 5th fret and below (cover up the right hand side of the diagram)
(2) Use 5th fret and above (cover up the left side.)
If you do this you will need one F on the 1st fret for (1) and one B on the 9th fret for (2). However you will probably find it easier to play if you substitute for the equivalent notes on the 6th and 4th frets.

By applying the flattening and sharpening of individual notes mentioned above, together with moving scales up and down, in all possible permutations, it is actually possible to define all positions of the diatonic scale just with this diagram.
Disclaimer for any pedants out there: the notes are from the key of C major. It's only correct to call it the scale of C major if you play the scale from C to C.
Comment: @Fergus Thanks for explaining the downvote. I went with the text of the OP's question (which does mention scales quite a lot), rather than the title. It's important that the OP understands he doesn't have to throw the pentatonic out, just build on it either by using theory or by ear. How to improvise is a far more subjective question to answer.
Comment: @Tim Scales aren't mentioned in the title but they seem to be the main thrust of the OP's text. He seems to think the diatonic is different from the pentatonic, when in fact it is an extension of the pentatonic. In fact most useful scales are an extension of the pentatonic (whether you find them by theory or by ear.) That needed clarifying. I hope I have given the OP something useful. That's more important than a vote.
Comment: Downvoted as this answer is about how to learn scales not how to improvise. Related but still very different.
Comment: This is a good way to explain scales and how they relate to each other. Sadly, it's the answer to a different question from the OP's. Find the right question (it's here somewhere) and you'll get  upvotes !
Comment: I think my post may have been poorly constructed in terms of what I was trying to ask. Indeed, in my head at least, I was asking more how to learn scales. Which is why I referenced specifically the pentatonic shapes that I was taught. Steve's post is very much in line with the sort of response I was wanting. Thanks Steve, and all others for your input!
Comment: @Rich I'm punching the air at getting the acceptance after being told TWICE that I'd missed the point of the question. Some people don't read in detail. You could edit the question title with the word (Scales) in brackets at the end to make the question more searchable. I've added one of the "pencilled in" scale shapes I mentioned. I hope you find it useful.
Comment: @steveverrill I'll take the blame - I probably underestimated the importance of the title! Have made it specific to scales now. It's definitely the answer I was looking for. Thanks for the extra added part too!
Answer: This is how it has always been done:

Learn your favorite lead guitar solos or parts of them you like (there are plenty of tabs in the Internet)
Steal
Profit!

I myself play along with records I think I might learn something of. I used to over-use the descending mixolydian scale in my solos but stealing interesting (surprisingly simple) licks from records helped. Now I play about a half of notes I used to.
On the other hand when you're jamming alone you don't have to be original or interesting. If you come up with an interesting lick, try playing it again. And again. And again. Can you add something to it or take something away? Our first ideas are often not that good, and they don't need to be. They're raw material. Beethoven wrote a lot of clumsy sketches and hammered them through endless variations until he came up with masterworks.
Playing again helps you learn to listen to your playing. If you know why your solos suck, you're pretty near to realize how you can make them not to suck anymore. Or maybe what you don't like is really something your own and you can elaborate it to become your personal distinctive style.
The key is to use both your and other's ideas, jam a lot and listen to your playing.
Answer: It sounds like you might need to "Gain inspiration" ?
When I was starting out I was listening to the likes of Hendrix and Dire Straits. Learning a few of the tricks involved there seemed to help me out a lot, because although their sound is totally different, some of the techniques are pretty similar.
Add to that a bit of Van Halen (ie, something quite different technique-wise) and mix it all together and I have ended up with a kind of pallette of 'stuff' I can use which suites what I want. Needless to say I like rock ;-)
Incidentally you can use the pentatonic just as a basic  "Shape" meaning you can solo in any key, and also add extra notes in to make it more interesting. Where/when depends a lot on the song though and would get more into the description of a scale, already provided here by steve verrill.
I think the main thing I have learnt, though, is to consider what kind of sound I want to make when going into a solo. If I don't do this, I just start using "muscle memory" and while that's ok, it can get a bit samey and routine-like. I play much better solos if I think to myself something like "I think a smooth jazz one at first then rock it up towards the end". That is, I'm kind of setting myself a 'mood'.
I guess you could do this either way before playing, perhaps establish a practiced solo, then reveal it when playing live, or think about it just as the solo is coming up. I personally prefer the "just in time" approach because I like the spontinaity, but some prefer to work things out in advance.
Also sometimes, especially when jamming, the notion of what would work changes halfway through though so a bit of flexibility to go with the mood works well.
Comment: Thx for the acknowledgement and +1. There's actually 2 questions here, one about improving improvisation in the title and one about scales in the text (OP mentions pentatonic 4 times, complains it's limiting and even questions his teacher's wisdom in teaching it. I HAD to say something about that, so I'm slightly annoyed by multiple negative comments.) Everything I do is based on pentatonic, with notes from diatonic and blues scales thrown in, and other notes that I don't know if they're from a scale but like you say, it fits the mood. Thinking ahead what moods to express really helps a solo.
Comment: pleasure! seems obvious to me that scales ahve a place in soloing and pentatonic is commonplace for a reason :-)
Answer: Yes, start with pentatonic scales. A pentatonic scale is a subset of the diatonic scale. So, once you become proficient at making good solos with the pentatonic, then you can learn how to incorporate those extra two notes.
A very good book to start with is: "The Blues Scales: Essential Tools" by Dan Greenblatt. A blues scale, after all, is just a pentatonic scale with an added blue note.
This book will keep you busy for a while.
Answer: I can really recommend pages like:
http://www.songsterr.com/ - Where you can see the tabs and actually play along with a computersimulated version of the song.
If you just want to learn the cords, you can see them on for example Wikipedia:
http://en.wikipedia.org/wiki/Chords_guitar
Try to learn the chords E, A, D, G. First try to make them sound good and clear, then fx 4 strokes on one chord, then change fast and precise. After some days practicing, you will be able to change through a few chords and play your first song or make your own!
Note: Acustic guitars are often harder to do chords on, because the strings are often further away from the fretboard, which makes your fingers work harder to make the chord clear sounding... If you have money for it, buy an electric Fender Squire or something like that, and a starter amp + jack cable. It's often way easier to learn chords on an electric guitar, or at least, that's what I found out :)
Hope this helped.
Good luck, good practice and keep on rocking ;)
Answer: Learning all the notes on the fretboard will be of immense help. For example, try to find all C for 5 minutes, until it becomes completely natural. Next try to find all D and so on... Once you're done with the C major scale, go for all the F#, then Bb...
If you're working on scales, then you can spot all notes of a scale (that is, with all its # or b) while you're working on this scale.
Fretboard discovery and understanding is of great importance when going for improvisation.
You can also checkout David Walliman free lessons on YouTube. He's got a super understandable approach to modes (scales) including pentatonic scales.
And practice everyday!


Group Theory : A property related to the intersection of all subgroups

Question: I was solving a problem from the book by Herstein (problem 2.5.2) and came across the following solution (the question is given there itself): http://www.artofproblemsolving.com/community/q1h1083399p4773230
Can someone give me an example of such a situation?
[Edit] In other words a group with the property that the intersection of its non-trivial subgroups is non-trivial as well. [/Edit]
Comment: Please make your questions as self-contained as possible in the future. Judging from the answer I guessed what exactly you are asking, and edited it in. Roll it back if you disagree.
Answer: Sure, consider the cyclic group of order $4$. It has precisely $2$ non-trivial subgroups, the entire group, and the unique subgroup of order $2$. The intersection of these groups is the subgroup of order $2$.
You can generalize this to any cyclic group of order $p^n$, for $p$ a prime.
Comment: The Prüfer $p$-group ought to do it.
Comment: Can you give me an example of a group whose order is infinite and holds this property?
Answer: An infinite group with this property is the following subgroup of the multiplicative group of complex numbers
$$
G=\{z\in\Bbb{C}\mid z^{2^n}=1\ \text{for some natural number $n$}\}.
$$
If $z\in G$ is $\neq1$, then $-1$ will also be a power of $z$. This is because if $k$ is the smallest non-negative integer with the property $z^{2^k}=1$ then we have $k>0$ (otherwise $z=1$). Consequently $W:=z^{2^{k-1}}$ satisfies both $w^2=1$ and $w\neq1$, so $w=-1$.
Therefore $-1$ belongs to the intersection of all non-trivial subgroups of $G$. Clearly $G$ is an infinite group, so this example works.

We can use any prime number $p$ in place of $2$ above. In the more general case all the roots of unity of order $p$ will be contained in the intersection of all the non-trivial subgroups.
Comment: Thank you sir! Also being new to forums, I will take care next time.
Comment: No problem, @AlmondPie. In your shoes I might have kept David Wheeler's answer as the accepted one. After all, the group I describe IS the Prüfer $2$-group he mentions in a comment. His comment must have come while I was typing/polishing my answer. Otherwise I would have refrained from answering.
Comment: Lol, Jyrki, it's all good. Almond Pie got the information he was after which is the important thing.


How to protect origin server?

Question: I have an AWS EC2 as origin web server, and cloudflare in front of it. And I cached all static files in Cloudflare, but still there are many static files access logs in log files.
Is it possible to find out origin behind CloudFlare?
 CloudFlare  (cname => AWS ELB, www.example.com => myweb.elb-domain.com )
=> ELB  (:80 => origin-ip:8080)
=> Origin server (:8080)

Normally, how much would people know about my web server?
Answer: The IP address that accessed your site is passed in CloudFlare's own CF-Connecting-IP header. You should always use this instead of X-Forwarded-For, as that can be supplied by the user and contain untrustworthy information.
Answer: CloudFlare passes an X-Forwarded-For http header with its requests to your origin server, giving the original IP address of the requester. You can log that header at your end if you want to.

How to protect origin server?


Show that $\tan{x}<\frac{4x}{\pi}$, $0<x<\frac{\pi}{4}$

Question: Show that $$\tan{x}<\frac{4x}{\pi}, ~~0<x<\frac{\pi}{4}$$
I want to use appropriate Mean Value Theorem to solve it. Please help.
Comment: As you are not at all a newcomer, why don't you show us what you have attempted, where you are blocked, etc ?
Comment: HINT: use that $$\frac{f(b)-f(a)}{b-a}=f'(c)$$ and $$0<c<\frac{\pi}{4}$$
Answer: If you use the Mean Value Theorem you get
$$
\tan x=\tan x-\tan0=(\tan)'(c)\,x=(1+\tan^2c)\,x\le2\,x,
$$
where $0<c<x<\pi/4$. But this is not what you want. Instead, use the fact that $\tan x$ is a convex function.


Sentiment analysis, are my samples significantly different?

Question: I have extracted data from a reviews website. I have created a dictionary with all words that appear in the reviews and corresponding number of counts.
I have then spit the reviews into two samples: reviews_plus (reviews with 7 stars or more) and reviews_minus (7 or less).
I have finally populated the two samples with the number of times a given word appears in a given sentiment-review, such as:
reviews_plus = {"the" : 1238, "ruin": 18, "hot": 291, etc...}
reviews_minus = {"the" : 1134, "ruin" : 87, "hot": 341, etc...}
Now I would like to test if the two samples are consistently different or not, a.k.a. if people giving bad and good reviews use different vocabularies.
I have read around the topic for two days but I am really stuck. Could anyone please help?
Answer: If you only have two types of reviews (but many words), the easiest thing to do would be to run exact Fisher's test. You can do it in R using the function fisher.test.
Comment: Hey, thanks for the reply. Fisher's test didn't pop up in my mind, it looks like the right choice. I was also thinking about Wilcoxon signed rank test. Would it be OK as well?


Is there such a thing as a "one way player" in tennis?

Question: I'll use an example from baseball to illustrate my question. A designated hitter is someone who bats, but is not deployed on the field. In its extreme form, a "one way player" would be someone who was one of the best hitters in the game, but could not field as well as a good minor league player. Examples would be David Ortiz or Frank Thomas.
Are there people in tennis who are great servers but who have trouble at returning serve in the later stages of a major event? That is, they will almost never have their serve broken in a given match, but also almost never break serve? Meaning that a large number, if not the majority, of their sets are decided by tiebreakers?
Put another way, how "lopsided" are John Isner, Ivo Karlovic, or other similarly challenged world class players.
Comment: I think John Isner is a classic example of this.  I assume that's what generated the question.  I don't think any player could be 'great' while only having a serve and not being at least very good at returning, though.  That's why Isner is unlikely to compete for a major - he's just not capable of breaking good players enough to win.
Comment: I nominate Ivo Karlovic over and above John Isner
Comment: Nadal might be the opposite, really.  His serve is only decent, but he's amazing at returning.  That's part of why he's so good at clay.  But it's all relative - I think this would be a hard question to have a legitimately complete answer to.  Too hard to judge what the bar is for "terrible".
Comment: That's not really objective, though.  What's inordinate?  I suppose you could tailor a standard such that some people meet or fail to meet it, but I don't think there's any sort of clear objective standard, and _certainly_ there is nothing like the blatant lack of ability some hitters in baseball possess in the field.  Any tennis player that is not at least very good on both sides of the ball will never be "great".  (And what is "notable" or "great"?)
Comment: @Joe: The key standard was "a large number, if not the majority, of their sets go into tiebreakers." So someone in this category can hold serve (in a four point game) against anyone in the world including Djokovic, but can never beat Djokovic because he can never break Djokovic (or even lesser players).
Comment: You also would need to realize that any "great" player would not go to too many tiebreakers against mediocre competition compared to great competition.  Isner will easily handle most players ranked under 100 without going to tiebreaks.  But once he starts facing other extremely strong servers, like Cilic, he starts to have issues returning serve.  So would you only count matches in the quarterfinals or later of a major, for example?  You certainly wouldn't count random midlevel tournaments in the ATP 1000 or something, right?  Or would you...
Comment: @Joe: I think your standard of "the later stages of a major" is the operative one. In theory, it could include the others but realistically, no one is that "lopsided." I edited the question to reflect this understanding.
Comment: I saw Inser play in person at a tournament in the quarter finals against Philipp Kohlschrieber with a score of 6-7, 7-6, 7-6... He also played the final against Lu Yen-hsun where it was 7-6, 7-6. I was sitting right behind the Ad court receive and his serve is huge. It has pace but bounces very high also, even going above the height of the railing. He rarely lost a point on serve. However when getting in a rally (returning) it seemed like he was fish out of water and struggled to win a point particularly going down low, thus could not break a serve himself.
Answer: As the comments say, there are rather striking examples of such players.
It's not clear (to me) how to answer the question of "how lopsided" the players you mention are. The natural answer is "very much, compared to other players with similar achievements". Leaning towards the other end of the spectrum, Santiago Giraldo is well known for having ultra aggressive service returns coupled with an average serve. Less noticeably still, Agassi himself had a rather weak serve, which he made up for with incredible groundstrokes and returns. Fabrice Santoro is an interesting example of a player seemingly without aggressive strokes at all - also an imbalance in a sense.
The difference in level between different strokes is just more blatant when it comes to serving because it sets the rhythm at the beginning of the point, which typically doesn't last enough to develop interesting dynamism.


Session is not getting maintain in settings.php drupal 7

Question: I have Created one php file on root of drupal7 and access it using URL.I have one form in that file which has dropdown values and submit button. Now in settings.php i am getting those value in POST. Based on That post value i want to select DB for drupal. But it Throws error because session is not getting maintain.
This is my code in settings.php
session_start();
$_SESSION['data'] = $_POST['year'];
if(!empty($_SESSION['data'])) {
  $databases = array (
    'default' =>
       array (
        'default' =>
          array (
            'database' => 'mydbname'.$_SESSION['data'],
            'username' => 'root',
            'password' => '',
            'host' => 'localhost',
            'port' => '',
            'driver' => 'mysql',
            'prefix' => '',
          ),
      ),
  );
}
else {
  header("Location: welcome.php");
}

Answer: You can't start session_start() the second time, since Drupal is already started it.
So either remove it, or wrap it into the condition, e.g.:
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

Parsing input user variables is not a good idea, so it's better if filter it out, e.g.
$_SESSION['data'] = filter_input(INPUT_POST, 'year', FILTER_SANITIZE_STRING);

or better use db_escape_table().
Answer: Session records are stored in the database. Hence, it is simply impossible to select the database connection based on values stored in a session.
Answer: Using session it is not possible so I did it using Cookie.
    if (!isset($_COOKIE['yr'])|| $_COOKIE['yr'] == '') {
          if (isset($_POST['year'])) {
            setcookie("yr", $_POST['year']);
            $_COOKIE['yr'] = $_POST['year'];
          } else {
            header('Location: welcome.php');exit;
          }
        }
        elseif(isset($_POST['year'])) {
            setcookie("yr", $_POST['year']);
            $_COOKIE['yr'] = $_POST['year'];
        }
        $databases = array (
          'default' =>
          array (
            'default' =>
            array (
              'database' => 'db' . $_COOKIE['yr'],
              'username' => 'root',
              'password' => '',
              'host' => 'localhost',
              'port' => '',
              'driver' => 'mysql',
              'prefix' => '',
            ),
          ),
        )
;


Regex for not matching a string

Question: I have a URL:
/ice-cream/stuff/sandwich/banana
I want to write a regular expression that ONLY matches the URL if these conditions are met:

"ice-cream" is in the URL
"sandwich" is in the URL and comes after "ice-cream"
"banana" is NOT in the URL

I tried this:
ice-cream.sandwich.^[(banana)] as well as many others but haven't found the solution.
Help is appreciate it.
Comment: It would be helpful to see example of strings (URL's) that match and those that don't (but come close). Also, what flavor are you using?
Answer: Give a try to the below regex,
^(?!.*banana.*).*?ice-cream.*?sandwich.*$

OR
^(?!.*banana.*)(?:(?!sandwich).)*ice-cream.*?sandwich.*$

DEMO
Explanation:

^ Asserts that we are at the beginning of the line.
(?!.*banana.*) Negative lookahead which checks the line contain the string banana or not. If it's not then the regex engine set the marker on the starting. Or Otherwise it skips the lines which contains the string banana.
(?:(?!sandwich).)* Matches all the characters which are not of the string sandwich.
ice-cream.*?sandwich.* String sandwich must be after to the string ice-cream.
$ End of the line.
Comment: Care to elaborate the difference, and how that `(?!)` thing (that the OP doesn't seem to know) works?
Comment: In your regex, why lazy (vs greedy) quantifiers?
Comment: @RonRosenfeld is there any difference if you remove the `?` quantifier?
Comment: In testing against some samples, I did not see any difference in what was matched.
Comment: yep. don't care about the lazy or non-greedy quantifier. `.*` after sandwich will match everything.
Answer: Hard to be precise without examples of matches and non-matches, but give this a try:
^(?!.*banana)(?:(?!.*sandwich(?=.*ice-cream))).*ice-cream.*sandwich.*$

Explanation of Regex:
^(?!.*banana)(?:(?!.*sandwich(?=.*ice-cream))).*ice-cream.*sandwich.*$
----------------------------------------------------------------------

^(?!.*banana)(?:(?!.*sandwich(?=.*ice-cream))).*ice-cream.*sandwich.*$

Options: Case insensitive; Exact spacing; Dot doesn't match line breaks; ^$ match at line breaks; Default line breaks

Assert position at the beginning of a line «^»
Assert that it is impossible to match the regex below starting at this position (negative lookahead) «(?!.*banana)»
   Match any single character that is NOT a line break character «.*»
      Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
   Match the character string "banana" literally «banana»
Match the regular expression below «(?:(?!.*sandwich(?=.*ice-cream)))»
   Assert that it is impossible to match the regex below starting at this position (negative lookahead) «(?!.*sandwich(?=.*ice-cream))»
      Match any single character that is NOT a line break character «.*»
         Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
      Match the character string "sandwich" literally «sandwich»
      Assert that the regex below can be matched, starting at this position (positive lookahead) «(?=.*ice-cream)»
         Match any single character that is NOT a line break character «.*»
            Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
         Match the character string "ice-cream" literally «ice-cream»
Match any single character that is NOT a line break character «.*»
   Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
Match the character string "ice-cream" literally «ice-cream»
Match any single character that is NOT a line break character «.*»
   Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
Match the character string "sandwich" literally «sandwich»
Match any single character that is NOT a line break character «.*»
   Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
Assert position at the end of a line «$»

Created with RegexBuddy

Comment: Care to explain/link that `(?!)` thing which seems to be new to the OP?
Comment: @Bergi Other's have explained the negative look-ahead.
Comment: Your regex wont match a string like `/ice-cream/sandwich/stuff/ice-cream` and its unclear what the OP wants.
Comment: @hwnd As designed.  And I agree that the OP's requirements are not clear in the instance where sandwich both precedes and follows ice-cream.  It also won't match  /tuna/sandwich/ice-cream/sandwich  If the OP does NOT want to exclude sandwich prior to ice-cream, so long as it exists after ice-cream, then it is just a matter of removing the 2nd "clause" from my regex, leaving it as **^(?!.*banana).*ice-cream.*sandwich.*$** (similar to Avinash Raj but without some of the "?"
Comment: Well, you can combine your lookaheads together. `^(?!.*(?:banana|sandwich(?=.*ice-cream))).*ice-cream.*sandwich.*$`
Comment: I can.  I don't know that it is more efficient. In Regexbuddy, it seems to take about the same number of steps with the data I'm using.
Answer: .*ice-cream.+sandwich.(?!banana).*

Try this one
Comment: Might be helpful to explain your code a bit, as others have done.

Regex for not matching a string