Not able to disable a multi-select drop down

Question: Hi I am new to AngularJs. Here my problem is on a certain condition I need to disable my multiselect dropdown.
So, I made the logic and on with the help of I tried to disable the dropdown-
document.getElementById("multidropdown").disabled = true;

But no luck.
So, then I google it and get to know about ng-disable. So, I put a ng-disable there and give it a name like this
ng-disabled="makeItDisabled"

And in my js file, I set
$scope.makeItDisabled = false

And in the condition, I made the same
$scope.makeItDisabled = true

But still got no luck.
This is my HTML-
column type="dropdownMultiSelect" styleName="form-control ng-isolate-scope multidropdown" ng-dropdown-multiselect=""  options="dropdownData" selectedmodel="dropdownelect" extrasettings="multiselectsettings"  events="DropDown_changed" text=""  uniqueID="multidropdown" ng-disabled=" makeItDisabled

This is my js code which I have tried
document.getElementById("multidropdown").disabled = true;

and also
$scope.makeItDisabled = true;

I did the same with the disabled also but there also I was not able to do it. I want to know where I am getting it wrong.
I am using this
https://github.com/dotansimha/angularjs-dropdown-multiselect
Comment: are you using any plugin for multiselect dropdown?
Comment: I think you are using isolate scope on select and then taking the parent controller scope variable to disable it that why your code is not working
Comment: Try for `$scope.makeItDisabled = { isDisable: true}` and `ng-disabled = "makeItDisabled.isDisable"`
Comment: @MayankPatel no I am not using
Comment: @ARUN I tried its not working
Comment: Added the URL of github from where I am using the multiselect
Answer: Finally I was able to do it by just using css
I disabled the dropdown by using
pointer-events:none;

Answer: Try this:
  <ng-multiselect-dropdown
       [placeholder]="' '" [data]="myList"
       [(ngModel)]="mySelectedItems" [settings]="mySettings"
       (onSelect)="onItemSelect($event)" (onDeSelect)="onItemDeSelect($event)"
       (onSelectAll)="onSelectAll($event)"
       (onDeSelectAll)="onDeSelectAll($event)"
       [disabled]=!isToDisable()>
  </ng-multiselect-dropdown>

Comment: Please explain what the code in your answer does and why it might help. See [How-To-Answer](https://stackoverflow.com/help/how-to-answer).
Answer: Use ng-disabled not ngdisabled and it should work. Post further if you have any queries
Comment: sorry mistake it was already ng-disabled. I posted it correctly again thanks for pointing


Count all characters in file during reading CSV

Question: I just want to ask you if there is any possibilities to get the number of all characters in file during reading the CSV file? I don't want to load file into memory two times (one time for parsing, second time for counting).
I need to parse CSV file but also I need to get the number of all characters in this file (with delimeters). Someone has any idea how to do that in the most efficient way?
   using (TextReader stream = new StreamReader(file.OpenReadStream()))
   {
        CsvReader reader = new CsvReader(stream, GetCsvReaderOptions());
        while (reader.Read())
        {
             //parsing
        }
   }

There is an option to iterate through all fields in actual reader row
and at the end increment length by delimeters (number of fields ==
number of delimeters).

Also I have idea to count characters on parsed objects by reflection
(get all properties value from object).

I don't think that these options will be efficient.
Thanks in Advance
Comment: Please define: "character". What do you, personally, think it means? And what do you think the .NET CLR defines it as as compared to the Unicode consortium? Note that a UTF-16 `Char` is not the same thing as a single discrete glyph. What about ligatures? Or in the case of denormalized Unicode?
Comment: @Mateusz Which is exactly what Dai also means. You need to think about the points raised before counting "characters".
Comment: @Dai I think I mean any character in file (digits, letters, special chars, whitespaces)
Answer: You can use Reader.Context.RawRecord and remove the line endings. (Assuming you don't want to count those)
using (TextReader stream = new StreamReader(file.OpenReadStream()))
{
    var count = 0;

    CsvReader reader = new CsvReader(stream, GetCsvReaderOptions());
    while (reader.Read())
    {
        count += reader.Context.RawRecord.Replace("\n", "").Replace("\r", "").Length;
        //parsing
    }
}

Answer: The basic way of doing this could be the following:
using (TextReader stream = new StreamReader(file.OpenReadStream()))
{
     var content = stream.ReadToEnd();
     var length = content.Length;
}

So that variable "length" will contain the count of all symbols in the passed file
Comment: I will need to open stream second time of the same file because if I will ReadToEnd() with CsvReader in the same using block, after fire ReadToEnd(), EndOfStream will be set to true. Also I don't think that it will be most efficient. Thanks for your response


Orthogonal complement in pre-hilbert space

Question: I just want to be sure that the following is correct:
Let $T:H \rightarrow H$(continuous), where $H$ is a pre-Hilbert space, then we have $H=\ker(T) \oplus\ker(T)^{\perp}$, where $\ker(T)^{\perp}$ is isomorphic to $H/\ker(T)$.
(So there's a Hilbert space isomorphism between them).
Further, $\ker(T)^{\perp}$ is isomorphic to $ran(T)$ as a vector space.
So all I would like to know is whether this true or false!
Answer: We have to move in the contex of Hilbert spaces, since completeness is required for your statements.
Note that $\mbox{ker}\,T^\perp$ is isomorphic to $(H/\mbox{ker}\,T)'$, where the prime denotes the dual (true in Banach spaces). However, $H / \mbox{ker}\,T$ is itself Hilbert, since the kernel of a continuous operator is always closed, so it is isomorphic to its dual via the Riesz' isomorphism (antilinear).
Now, if $\mbox{ker}\,T^\perp$ and $\mbox{ran}\,T$ were isomorphic, then $\mbox{ran}\,T$ would be always closed and this is not the case. However, it is true for projections and, more generally, we have

Theorem. Let $H$ Hilbert, $M < H$ closed. Then $H = M \bigoplus M^\perp$, $M$ and $M^\perp$ are complementary and $M=\mbox{ker}\,P$, $M^\perp = \mbox{ran}\,(I - P)$ for some $P$ projection. Moreover, $\| x \|^2 = \|Px\|^2 + \| (I-P)x \|^2$ for all $x\in H$.

($I$ is the identity operator and $<$ stands for "linear subspace".)


Is it possible to tune a short scale (22.4") acoustic guitar up to ADGCEa with 10-47 strings?

Question: I'm considering getting this guitar: http://www.thomann.de/gb/harley_benton_ds_10_mini.htm?ref=search_rslt_benton+mini_321012_0
According to the description, the scale is 568mm (~22.36") and it comes with 10-47 strings. Considering the light gauge and the short scale, I'm pretty sure it needs to be tuned up for the strings not to be flabby and stay in tune. But I'm still wondering if it's possible to get it up to ADGCEa without snapping the strings. My questions are:

Do you think it's possible to tune that guitar up to ADGCEa with the strings that are being shipped with it?
If not, do you think it would be possible with lighter gauge strings, say 9-42 or even 8-38?
I've read about a guy who tuned his Fender Squier Strat Mini RD (22.64" scale) up to ADGCEa with 9-42 strings. On that note, is there a difference between acoustic and electric guitars with regard to tuning?

Lastly: I know I could simply take a guitar with standard EADGBe tuning and capo the fifth fret. I'm curious to find out if there's an alternative without capo though :)
Thanks in advance!
Comment: You may find this very handy: http://www.mcdonaldstrings.com/stringxxiii.html Calculate the total and per-string tensions for the factory setup and then work with trial and error to find a combination that is closest to the same total and per-string tensions with the notes you want. For instance, a .013 string tuned to E is slighter higher tension than a .009 string tuned to the A above it (for a 25.5" scale length).
Comment: You may also find this one useful (not a duplicate though):  http://music.stackexchange.com/questions/28978/short-scale-guitar-tuning-to-a
Answer: I did it for you, since I was curious:

Low A: .034 wound
D: .028 wound
G: .020 wound
C: .017 plain
E: .011 plain
High A: .008 plain

Total tension is almost exactly the same. Individual tensions are pretty close.
One main difference between electric and acoustic strings that may come into play is that on electric guitars, the 3rd string is usually plain, whereas on acoustic it is usually wound. This does have an effect on feel and string bending.
Also note that with strings so much thinner than normal, you could get rattling at the nut or saddle depending on how the slots are cut. If they are not tapered into the cut enough then one or more strings may just be sitting on a flat surface with some wiggle room. If it's at the nut end, you could deal with that by tuning down a half step and capoing at fret 1 (possibly with going with a slightly larger guage). If it's at the saddle, you might be stuck with having to get a special saddle cut. Even though the total tension is almost identical, it might be a good idea to double check the neck relief a couple days after setting this up.
Also check out Nashville tuning.
Comment: Thanks a lot, Todd! As for the calculator, when selecting "Guitar medium" with a scale of 65cm, I get the following tensions that I want to use as benchmark: Overall: 80.67, Low E: 13.58, A: 14.6, D: 13.75, G: 14.58, B: 11.99, High E: 12.17. When changing the scale to 56.8cm and the strings to the factory setup, I get this: Overall: 77.62, Low A: 11.61, D: 15.86, G: 14.64, C: 14.9, E: 10.71, High A: 9.9 --> Lower overall tension but individual tensions are higher. All in all, it doesn't look bad though. Is there something like a max tension? As to both overall and per string? Many thanks!
Comment: I wonder (often!). But this time it's about intonation. The bridge is set up for the original gauge of strings, so will probably need adjusting. s.Not particularly easy on most acoustic
Comment: Hey Tim, the tension values in my comment above would be the result if I used the original gauge strings and tune them up to ADGCEa. So if the tension (both overall and on individual strings) is not a problem, then this should work. Is there maybe something like a max tension cheat sheet. E.g. gauge .010 string -> max tension 15kg and so on... Or is this not only about the gauge but also the instrument itself?
Comment: @Peter Is there something stopping you from just getting the most appropriate strings for the tuning you are looking for? There certainly is a tension that will damage a guitar outright, assuming the strings can handle it, but that's not the biggest concern. The biggest concern (to me) is a lower tension that will *slowly* be bad for the guitar. Forgetting about all that for a moment, there is a maximum tension that the truss rod on the guitar can compensate for, you wouldn't want ot exceed that. If you have no truss rod, then matching the factory tension is a lot more important.
Comment: Not at all, I could definitely get the strings you looked up for me (thanks again for that). I just didn't know that matching the factory tension was the best alternative. I didn't even know there was such a thing as factory tension. It was my understanding that the manufacturer puts the strings on the guitar they think are best suitable in terms of sound. However, I thought people could change strings as they see fit. Now I learned that this is not entirely true (e.g as it's potentially required to adjust the bridge to avoid rattling).
Comment: Actually, this kind of brings me back to the initial situation resp. my original plan, i.e. getting a guitar where the factory set-up might be suitable to tune up to ADGCEa. However, and please confirm the following in case it is correct :) Due to the fact that there is something like a "factory tension", there will never be a scenario wherein I can have the best of both worlds, i.e. using the existing strings (=no adjusting of bridge required) and being able to tune up to ADGCEa (=desired tuning).
Comment: @Peter You *might* be able to tune the factory strings to the tuning you are looking for without major problems. At the same time, the increased tension will make the guitar much harder to play. As someone who has played around with different tunings and set up guitars in different tunings, I can tell you that every part of the playing experience is improved by matching the string guage, tension, tuning, and setup. Only changing the tuning by a whole step is very detrimental to the feel of a guitar if you don't compensate by changing the string guages. A fourth would be **very** different.
Comment: I see... One (hopefully :)) last question: It doesn't always say which strings come with a guitar. Is there a way to find out what gauges are recommended by the manufacturer? If I don't know the recommended set-up, I obviously can't match it if I want to use a different tuning. Many thanks for help and patience :)
Comment: @Peter I'm a little confused because I thought you already had a guitar and its guages in mind and you question specifies both of those. Either way, manufacturers usually tell you at least approximately what their guitars are strung with from the factory.
Comment: Sorry, didn't mean to confuse you :) For this particular guitar, you're absolutely right. With the new things I learned here, I was already looking into other options though. And that's when I noticed that the description doesn't always state the strings that come with the guitar. Many thanks!
Answer: 22.4/25.5=88% scale length.
tuning up 4/3 requires 16/9 tension at the same scale length.
56% more tension. I wouldn't do it. I wouldn't worry about tearing the top off the guitar (if this is a half size guitar, it has less perimeter about the top, and less strength), but I don't worry about anything. I also have a couple of tenor guitars with broken necks.
Even if your A4 tunes up, it will break very soon. 0.010 gauge steel strings are past their yield strength at that scale length. A4 is for violas, which are 17 inches or less.
Maybe try G2 C3 F3 Bb3 D4 G4?
edit: since you asked about gauges, multiply each diameter by 3/4 for the same tension at 4/3 frequency. 7.5 to 36 rather than 10 to 47.
Answer: There is absolutely nothing wrong with Todd's fantastic amazing answer!  But the ensuing comment thread seem to interject some potential confusion.
Let me make a couple of observations.  A shorter scale guitar will require less tension to reach a given pitch.  The guitar you mentioned has a scale approximately three full inches shorter than a "full scale" guitar.  I am away from a guitar at the moment but I am guessing that might be equivalent to a capo on the 2nd fret (if not almost 3rd) fret of many full scale guitars.
So while it is likely that tuning a .10 steel string to a on a 25.5 inch scale guitar would snap the string, it is highly probable that you could get there on a 22.36" scale. Yes that would increase the tension and yes, too much tension can damage the guitar.  But there is a limit to how much tension you can get from a .10 or .09 gauge string before it breaks.  You could torque a .47 gauge string to a dangerously high tension before it would break, but that is not going to be happening in the scenario you describe.
Also of importance, the lighter the string gauge, the less tension required to reach a given pitch.  So the combination of very light strings and a short scale guitar will very likely translate into a very floppy feeling set up - as you suggested.  So I think your idea of a higher tuning in that scenario, makes perfect sense and may contribute to a better overall playing feel.
When a guitar manufacturer builds a particular guitar, someone will decide what gauge strings would be optimal for that guitar (assuming standard tuning).  Then that guitar will be "set up" (hopefully) in the factory for the particular gauge strings the manufacturer "recommends".  Sometimes, manufacturers change their mind as did Taylor Guitars with their acoustic 800 and up series.  I would assume that when they changed the recommended string gauge, they altered the factory set up accordingly.
Radical departure from the gauge the guitar was set up for can result in significant problems including intonation, nut slots being too large, bridge height too low, or other issues.  Slight departures (going from .010 to .009 for example) don't usually have a discernible effect.
Assuming the guitar you mentioned has been set up for the gauge strings they ship with it, you should be able to make some slight modifications to your string set without radically diminishing the play ability.
It is very important to maintain relatively consistent string tension for all strings for playing comfort. It is also important not to exert so much tension on the neck that the truss rod is unable to compensate. But the overall tension can be adjusted up or down and appropriate adjustments to the truss rod will maintain the proper and desired relief in the neck.
So let's look at what you are considering in another way.  Below you will find a string gauge description for a heavy set and a .010 - .047 Extra Light Set.

These are two different gauge sets from same manufacturer and same type strings.  I am sure most full scale guitars would be able to handle the higher tension of the heavier gauge.  As you can see, the heavy set uses a .049 gauge for the A string.  So no problem on a shorter scale (less tension required) to tune a .047 gauge to A.  We also see that on the heavy gauge set, we can get a .014 gauge string to high e.  Same gauge as on the 2nd string in the light gauge set.  So again, even less tension on the short scale guitar to get the .014 gauge string to high e.
The only question not answered by the chart, is will the .010 string tune up to high A on the short scale guitar.  We can see that the difference between B and e is either .018 to .014 OR .014 to .010 - either way a .04 difference.  The shorter scale will make it easy to get to high a on a .010 and I would bet you could even get there with a .011 since the scale is equivalent to at least a 2nd fret capo already.
I am certain you won't have a problem tuning the .010 string to a on the short scale and the overall tension should be reasonably balanced, albeit higher than with standard tuning.  As mentioned above, this higher tension is probably a potentially more comfortable tension on the short scale than the .010 to .047 set would provide.
If in the very unlikely event that the .010 string snaps before you get to high A, you can buy a single .09 gauge from Just Strings Single Strings Page
The biggest difference between strings for electric verses acoustic (aside from the metal composition being different to react to magnetic pickups) is that generally strings for electric can be lighter to accommodate string bending - since the volume is controlled by the electronics and amplification.  It is common for electric sets to have a plain steel G (third) string instead of a wound G string.
Speaking of wound G strings, at the above mentioned site for single strings at Just Strings dot com, you can purchase acoustic wound G strings in a .018 gauge if you decide you want to construct a lower tension A - a tuning and still have a wound 3rd string.
I have not gone as far as Todd and tried a hands on experiment, but I have played with enough different string gauges on different scale length guitars, to confidently say that you should be just fine tuning up the guitar you mentioned with the strings they shipped which are probably the strings the guitar is set up for.
You will probably want to adjust the truss rod to compensate for the higher tension.  But with the shorter scale, the effect on overall tension should not be beyond the adjustment range of the guitar's truss rod.
Comment: Another incredibly useful answer, thank you very much! It's quite a cheap guitar, so I guess I'll just go ahead and give it a shot. I'll obviously keep you posted on the outcome :) Do I need to tune the guitar up really slowly, not more than half-tone per hour/day or something like that? As for adjusting the truss rod, I guess I don't want to do that myself. So if it's necessary, I would bring it to my local shop.
Comment: Truss rod adjustments should be done very slowly.  No need to do the tuning so slowly  - but it might not hurt to do it over an hour or so - maybe whole steps then let the neck adjust for 15 minutes. I say that but when I re-string any of my guitars, I take all the strings off at once and then tune new strings zero to full tension in 10 minutes.  But if you are going to have your local shop do the set up, you should let them tune it at the same time. Just be sure they write down exactly how you want it tuned so they don't hand it off to the assistant tech who defaults to standard tuning.


Filtering arrays for neighbors

Question: Is there an easy way to filter an array of elements quickly to only output the neighbors?
Say I have an array of elements. Now I want to find the neighbors of a specific element.
The code I made works but looks quite ugly and I'd like to find an easier-to-read solution.
My code:
int[] myArray = {6, 8, 9, 12, 30};
// index of element where I want to find the neighbors of
int index = 1;

if(index == 0){
  //first element so only add the right neighbor
  System.out.println(myArray[1]);
} else if(index == myArray.length -1){
  //last element so only add left neighbor
  System.out.println(myArray[index-1]);
} else{
  //middle element so add both neighbors
  System.out.println(myArray[index-1]);
  System.out.println(myArray[index+1]);
}

Answer: Here is a good and short solution:
if(index > 0) System.out.println(myArray[index-1])
if(index < array.length-1) System.out.println(myArray[index+1])

Answer: Actually, using Java 8 you can use this by quite simple lambda solution:
final int[] numbs = { 1, 3, 5, 7 };
int index = 2;
IntStream.rangeClosed(index - 1, index + 1)
        .filter(idx -> idx != index && idx >= 0 && idx < numbs.length)
        .forEach(idx -> System.out.println(numbs[idx]));

But please, create a method that receives your array and index in order to reuse the code.
Comment: no need to stream the entire range of the array. you can stream just the neighbors `IntStream.rangeClosed(index-1, index+1)` and filter `idx != index && idx >= 0 && idx < numbs.length`
Comment: I do not think that this is a good idea, because the streams usually perform for a long time. Also, lambdas are usually more difficult to understand than simple if-else.
Comment: And yes, lambdas are hard to understand for people who doesn't study them. So don't use if you don't know how to use them @AntonSorokin and do never use the new Java features too.
Comment: @RhuanKarlus My message doesn`t mean that I don`t know lambda or I propose not to learn/use new language features. I meant that it is not necessary to use a complicated version when there is a simpler construction.

Filtering arrays for neighbors


Non-vector data and SVM?

Question: My research is on antimicrobial peptide classification and prediction. I have gathered peptide sequences of lengths ranging from 10 - 200 and classified them using different machine learning algorithms. The algorithm with the highest performance in terms of ACC, SEN, SPC and MCC was the SVM. My negative and positive datasets are balanced, each with about 500 samples. The total number of attributes was 126. I want to know if my dataset can be classified as a non-vector dataset? Also, if the reason SVM had the best performance is that kernel methods are more appropriate when dealing with non-vector inputs?
P.S. I major in biotechnology and my knowledge on machine learning is very general and basic.
Comment: What do you mean by a non-vector dataset?
Comment: @MarcClaesen Well I don't exactly know what it is but in an article it explained as datasets like sequences and graphs, but I haven't been able to find an exact definition for it.
Comment: Graphs and the like can be summarized as a vector and then dealt with through an appropriate kernel function, so this is no problem.
Answer: If you were able to easily run SVM and other ML models then your dataset is not "non-vector like". You had to somehow represent your data in a way that is understandable by SVM and other methods - if you did encode them to vector format then your data is vector like. If you, however used some tricky kernel, which fitted model to raw, non vector data (such as text, or graph) you could advocate the term "non-vector like", however this is purely linguistic as "under the hood", SVM always works on vectors, sometimes in a very weird spaces, yet still vector, Hilbert spaces.
Comment: By way of example, OP may be interested in this article on graph kernels. "Diffusion Kernels on Graphs and Other Discrete Structures" http://people.cs.uchicago.edu/~risi/papers/diffusion-kernels.pdf
Comment: It's true that kernelized SVMs work in Hilbert space under the hood. But, points in this feature space are not the original data. Rather, they're implicit representations defined by mapping the original data into feature space, as determined by the kernel function. I think it's important to distinguish 1) the fact that data are mapped into a vector space from 2) the data themselves being vectors. (1) doesn't imply (2)
Answer: (I just saw this, so if this response is too late, I am sorry.)
Yes, your data is non-vector data.
Since you are able to compute similarities between instances you can cluster them. Once you can cluster them, you can do a number of things (from simplest to more complex):
-Cluster and use centroids for classification: e.g. http://ieeexplore.ieee.org/document/4401090/
-Use RBF Networks where the RBF units use your similarity function instead of the regular Gaussians.
-Use SVMs with your similarity measure in the kernels.
...
Hope this helps.
Comment: See also: http://www.sciencedirect.com/science/article/pii/S0031320310002463

Non-vector data and SVM?


A non-Views, Panels-compatible slideshow?

Question: The common way to create some variety of slideshow within Drupal is to use Views Slideshow and then display content that way.
However, what if I just want a simple slideshow that appears in all of one Panel on the front page? Creating a new content type (and the requisite nodes) seems fairly overkill.
To that end — is there a slideshow that is both compatible with Panels and able to be invoked without using Views (or otherwise creating a bunch of nodes)?
Answer: umm sure. you can always make a Block using admin/structure/blocks with like full_html. You could then easily make whatever HTML markup you need to get your images on the page.
Then in your theme file include a scripts[] = /path/to/your/js-slideshow.js.
A slideshow is just a slideshow. For example the slideshow at www.ucsb.edu is simply some HTML for images, 1 custom JS file, and CSS to hide all but the first image initially -- this is easily reproducible with Core Drupal. You could then place the block wherever you want with Panels.
The only caveat with this approach is uploading images from Drupal to power the slideshow is obviously harder since your keeping it very lean and not 100% drupal integrated.
Edit
Another example of getting remote images into drupal could be seen here by Fago making Entities from Google Picasa images and slideshows. Unless your comfortable with all this custom code, I dont recommend this type of approach. Drupal may have many approaches to getting something done, but as I mention in my last comment dont fight drupal's conventions or default way of doing something simply learn to embrace it. I've seen this idea spread by MerlinofChaos telling themers (im paraphrasing) "learn to use Views css, even though its ugly -- its feature complete". The same applies to drupal 7 "table per field" default storage structure. When you try to work around what you perceive is a shortcoming you simply fight an uphill battle to make drupal do what you want.
Comment: re the caveat, you certainly could put static images in a images/ subdirectory of your theme/module and either through the Block UI mentioned here, or a block hook in a custom module, do whatever you wanted with them via JS
Comment: Well, yes — that would technically work. But the reason I use Drupal as a *Content Management System* is to **manage content** — telling clients "You just need to write a bunch of HTML!" doesn't really fly in most cases...
Comment: It sounds like you dont want to use Nodes, Entities, or even Views as dependencies. A Block is a piece of content and managed by Drupal, its reusable. You can use Nodes, Entities, or write a custom admin form and store X variables to image paths. Your question is hacking out valid drupal mechanisms left and right here. If you dont want to write HTML, you'll need to use these building blocks of drupal together to meet your needs. Please rephrase your question to include what Drupal dependencies you want for your slideshow, or how you think it should function.
Comment: @Tenken — The only real dependency is Panels, and I'm just really not wanting to use nodes. Drupal uses nodes for everything -- that's why it's a difficult question. It's about thinking of Panels less as a developer tool and more a site builder/CMS tool. I ask this not to criticize the Views Slideshow route so much as to question whether there's another — possibly simpler — approach than creating a View for everything. That said, I'm sure there are non-nodal ways of using Views Slideshow for this purpose (For instance, Views can interact with arbitrary tables through the Data module).
Comment: your right, but a table exposed to Views via hook_views_data() for instance is basically shoehorned into being viewable by Views. Eg, how do the images get into this table (from Drupal) by your client? If the data were an Entity/Node already you'd have a Drupal File Field  instance on some piece of content. So if you dont want heavy Nodes, entities whatever behind Views good luck having a "drupal" simple interface for your client to do something. Maybe a 3rd party Flash player is what you want ? Work with Drupal's with conventions, not around them.
Answer: To make a slideshow of all the panels within a panel region, use the Slideshow style in Panels Style Pack. As for the panels to put in that region, if you don't want to use nodes you can do what @tenken says and use custom blocks. Otherwise you can also use Fieldable panels panes to create a Drupal entity just for use in panels. These entities will be more lightweight than full nodes and won't clog up your node management.
Answer: I have been experiencing the same issue. In the end I have found the Gallery Formatter module is compatible.


Criar tabela excel baseada em filtro

Question: Olá,
Eu tenho uma tabela no Excel de 3 colunas:
Pessoa | ID | País
João   | 1  | Flórida
Maria  | 2  | Flórida
Ana    | 3  | Miami
Ana    | 4  | Califórnia
Pedro  | 5  | Califórnia
João   | 6  | Flórida

etc...
Gostaria de construir uma tabela que contivesse as pessoas somente da 'Flórida' para que eu pudesse referenciar em uma outra planilha.
Tentei usar a Segmentação de Dados, porém ela funciona apenas como um filtro, e eu não consigo fazer as referências dinâmicas de tabela (ele não fica [@Pessoa], por exemplo, mas sim referenciado na célula). Gostaria, então, de construir uma subtabela que contivesse apenas as pessoas da Flórida, de forma que, quando eu atualizar os dados dessa tabela, essa subtabela também se atualize (mas seja uma tabela, não um 'filtro').
Alguém tem alguma sugestão? Tentei uma Query, porém a subtabela dá erro quando atualizo minha tabela original.
Obrigada!
Comment: "Tentei uma Query", você está se referindo aquela opção do "Microsoft Query" que fica no menu Dados? Pois fiz um teste aqui e funcionou, edite a pergunta e coloque qual erro aparece.
Answer: Copiar e Colar não te resolve o problema? Se sim, use o comando para selecionar apenas células visíveis:
Selecione a sua tabela inteira ou as colunas que deseja consolidar sua nova lista. Filtre por 'Flórida' e siga a instrução abaixo:
Aba Início > Localizar e Selecionar > Ir para... > Especial... > Apenas célilas visíveis

Em seguida, selecione OK, aperte Crtl+C e cole na área desejada.
Answer: Utilizar uma Tabela Dinâmica não lhe ajudaria? Assim vc pode colocar fórmulas ao lado da Tabela Dinâmica e não ter o problema de referência ou linhas ocultas ao filtrar. Além disso, vc pode inserir Slicers para fazer os filtros.

Caso precise de orientaão de como montar a tabela dinâmica dessa form, me avise!

Criar tabela excel baseada em filtro


Finding the Bayesian classifier for a bivariate Gaussian distribution

Question:
Very close to: Joint Gaussian of two Gaussians

I am trying to find the Bayesian classifier for two classes given by the following bivariate Gaussian distributions:
$$p(x|c_1) = N(\mu_1, \Sigma_1)$$
$$p(x|c_2) = N(\mu_2, \Sigma_2)$$
What is the formula and the methodology I should use to do this? I am confused with out a proper understanding on a formula to do that at the moment. Prior probabilities of $c_1$ and $c_2$ are 0.5 respectively.
FYI:
<code>μ1 = ( 2        Σ1 = (2 0
       2 )            0 1)

μ2 = ( 2        Σ1 = (4 0
       4 )            0 2)
</code>
Comment: Please rather use edits and comments than new question if you only want to ask for extending the answer.
Answer: Define a random variable $C\in\{1,2\}$ with prior distribution $\mu_C$ given by
$$
  \mu_C(A) = P\{C\in A\} = \frac{1}{2} I_A(1) + \frac{1}{2} I_A(2) \, ,
$$
where $A$ is any subset of $\{1,2\}$.
Use the notation $X=(X_1,X_2)$ and $x=(x_1,x_2)$. Suppose that
$$X\mid C=1\sim N(\mu_1,\Sigma_1)\, ,$$
$$X\mid C=2\sim N(\mu_2,\Sigma_2)\, ,$$
where $\mu_1=(2, 2)^\top$, $\Sigma_1=\textrm{diag}(2,1)$, $\mu_2=(2,4)^\top$ and $\Sigma_2=\textrm{diag}(4,2)$.
Now, study this
http://en.wikipedia.org/wiki/Multivariate_normal_distribution
to understand that
$$
  f_{X\mid C}(x\mid 1) = \frac{1}{2\pi\sqrt{2}} \exp\left(-\frac{1}{2}\left(\frac{(x_1-2)^2}{2} + \frac{(x_2-2)^2}{1} \right)\right) \, ,
$$
$$
  f_{X\mid C}(x\mid 2) = \frac{1}{4\pi\sqrt{2}} \exp\left(-\frac{1}{2}\left(\frac{(x_1-2)^2}{4} + \frac{(x_2-4)^2}{2} \right)\right) \, .
$$
Using Bayes Theorem, we have
$$
  P\{C=1\mid X=x\} = \frac{\int_{\{1\}} f_{X\mid C}(x\mid c) \,d\mu_C(c)}{\int_{\{1,2\}} f_{X\mid C}(x\mid c)\, d\mu_C(c)} = \frac{\frac{1}{2} f_{X\mid C}(x\mid 1)}{\frac{1}{2} f_{X\mid C}(x\mid 1) + \frac{1}{2} f_{X\mid C}(x\mid 2)} \, .
$$
The idea is to decide for the first classification if
$$
  P\{C=1\mid X=x\} = \frac{1}{1+\frac{f_{X\mid C}(x\mid 2)}{f_{X\mid C}(x\mid 1)}} > \frac{1}{2} \, ,
$$
which is equivalent to
$$
  \frac{f_{X\mid C}(x\mid 2)}{f_{X\mid C}(x\mid 1)} < 1 \, ,
$$
or
$$
  \log f_{X\mid C}(x\mid 2) - \log f_{X\mid C}(x\mid 1) < 0 \, ,
$$
which gives us
$$
  \log \frac{1}{2} - \frac{(x_1-2)^2}{8} - \frac{(x_2-2)^2}{4} + \frac{(x_1-2)^2}{4} + \frac{(x_2-4)^2}{2} < 0 \, . \qquad (*)
$$
Therefore, you decide that the point $x$ belongs to classification $1$ if it is inside the ellipse defined by
$$
  \frac{(x_1-2)^2}{8(2+\log 2)} + \frac{(x_2-6)^2}{4(2+\log 2)} = 1 \, ,
$$
otherwise, you decide for classification $2$.
Answer: $X_1$ and $X_2$ are independent normal random variables with means $2$ and $4$ under both hypotheses.  The variances under one hypothesis are half those under the other.  So, the log likelihood ratio is something like
$$\ln 2 - \frac{(x_1-2)^2}{8}-\frac{(x_2-4)^2}{4}  +
\frac{(x_1-2)^2}{4}+\frac{(x_2-4)^2}{2}$$
and has to be compared to $0$ since the hypotheses are equally likely.  After simplification you should get a classifier saying something

Decide $c_1$ if $(x_1,x_2)$ lies inside an ellipse with center $(2,4)$; $c_2$ if outside.

where the equation of the ellipse wil be revealed to you as you do the algebra.
Comment: Thank you very much for your answer Dilip. Still there are certain things that I don't understand maybe because I am pretty new to stat stuff. What does happen to the vector properties of the means (μ) and where are the co variance matrices represented in the equation you are giving? What you are giving is after substituting the values right? Do you have the bare bone equation which I can use in the classification? Thanks.
Comment: See, for example, [here](http://courses.engr.illinois.edu/ece313/fall00/ppt/Lecture39.pdf) for the bivariate normal density formula.  The barebones equation for the likelihood ratio is the ratio of the two bivariate densities under the two hypotheses. The covariances are zero according to the FYI statement and so $X_1$ and $X_2$ are independent normal random variables while the means are there subtracting off from x_1 and x_2 in the formula I gave. I took the log of the likelihood ratio to get the formula.


How to use a generator expression in python to create a list of odd integers?

Question: How would I go about changing the program below to a generator expression that yields the same result?
print 'this program creates a list of odd numbers in the range of your choice'
start_num=int(input('Enter Starting Number'))
end_num=int(input('Enter ending number'))
my_list=[]
for i in range(start_num,end_num+1):
    if i%2==1:
        my_list.append(i)
print ('odd numbers in the range', my_list)

Answer: print("this program creates a list of odd numbers in the range of your choice.")

def generator():
     start_num=int(input("enter the starting number:"))
     end_num=int(input("Enter the ending number:"))
     odds=list(i for i in range(start_num,end_num+1)if i%2==1)
     print(odds)

if__name__=='__main__':
     generator()``

P.S. GOOD LUCK ON THE MIDTERM THIS WEEK!


MRTK V2.6.1 - Getting DirectoryNotFoundException after fresh install of mrtk

Question: I have set up a new Unity project with MRTK today. I'm using Unity 2020.3.26 and MRTK 2.6.1. I installed MRTK via the Microsoft Mixed Reality Feature Tool.
Immediately after installation, as usual with Microsoft/MRTK, I was greeted with countless errors. However, I could not fix the following error and do not know what to do:
<code>System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\Users\[Username]\source\repos\[Folder]\Unity\[Folder]\Library\PackageCache\com.microsoft.mixedreality.toolkit.foundation@2a959d4b1c8c-1621237827345\SDK\Experimental\InteractiveElement\Examples\Scripts\CustomStateExample\KeyboardState'.
  at System.IO.__Error.WinIOError (System.Int32 errorCode, System.String maybeFullPath) [0x000f7] in <695d1cc93cca45069c528c15c9fdd749>:0
  at System.IO.FileSystemEnumerableIterator`1[TSource].HandleError (System.Int32 hr, System.String path) [0x00006] in <695d1cc93cca45069c528c15c9fdd749>:0
  at System.IO.FileSystemEnumerableIterator`1[TSource].CommonInit () [0x00054] in <695d1cc93cca45069c528c15c9fdd749>:0
  at System.IO.FileSystemEnumerableIterator`1[TSource]..ctor (System.String path, System.String originalUserPath, System.String searchPattern, System.IO.SearchOption searchOption, System.IO.SearchResultHandler`1[TSource] resultHandler, System.Boolean checkHost) [0x000d6] in <695d1cc93cca45069c528c15c9fdd749>:0
  at System.IO.FileSystemEnumerableFactory.CreateFileNameIterator (System.String path, System.String originalUserPath, System.String searchPattern, System.Boolean includeFiles, System.Boolean includeDirs, System.IO.SearchOption searchOption, System.Boolean checkHost) [0x00009] in <695d1cc93cca45069c528c15c9fdd749>:0
  at System.IO.Directory.InternalGetFileDirectoryNames (System.String path, System.String userPathOriginal, System.String searchPattern, System.Boolean includeFiles, System.Boolean includeDirs, System.IO.SearchOption searchOption, System.Boolean checkHost) [0x00000] in <695d1cc93cca45069c528c15c9fdd749>:0
  at System.IO.Directory.InternalGetFiles (System.String path, System.String searchPattern, System.IO.SearchOption searchOption) [0x00000] in <695d1cc93cca45069c528c15c9fdd749>:0
  at System.IO.Directory.GetFiles (System.String path, System.String searchPattern) [0x0001c] in <695d1cc93cca45069c528c15c9fdd749>:0
  at System.IO.DirectoryInfo.GetFiles (System.String searchPattern) [0x0000e] in <695d1cc93cca45069c528c15c9fdd749>:0
  at System.IO.DirectoryInfo.GetFilesSubdirs (System.Collections.ArrayList l, System.String pattern) [0x00002] in <695d1cc93cca45069c528c15c9fdd749>:0
[ ... ]
  at System.IO.DirectoryInfo.GetFilesSubdirs (System.Collections.ArrayList l, System.String pattern) [0x0002f] in <695d1cc93cca45069c528c15c9fdd749>:0
  at System.IO.DirectoryInfo.GetFiles (System.String searchPattern, System.IO.SearchOption searchOption) [0x00017] in <695d1cc93cca45069c528c15c9fdd749>:0
  at (wrapper remoting-invoke-with-check) System.IO.DirectoryInfo.GetFiles(string,System.IO.SearchOption)
  at Microsoft.MixedReality.Toolkit.Utilities.Editor.OnLoadUtilities.FindShaderFolderInPackage () [0x0004c] in C:\Users\[Username]\source\repos\[Folder]\Unity\[Folder]\Library\PackageCache\com.microsoft.mixedreality.toolkit.standardassets@570a6e7bd8eb-1621237819262\EditorUtilities\OnLoadUtilities.cs:152
  at Microsoft.MixedReality.Toolkit.Utilities.Editor.OnLoadUtilities.EnsureShaders (System.Boolean bypassIgnore) [0x00000] in C:\Users\[Username]\source\repos\[Folder]\Unity\[Folder]\Library\PackageCache\com.microsoft.mixedreality.toolkit.standardassets@570a6e7bd8eb-1621237819262\EditorUtilities\OnLoadUtilities.cs:42
  at Microsoft.MixedReality.Toolkit.Utilities.Editor.OnLoadUtilities..cctor () [0x00000] in C:\Users\[Username]\source\repos\[Folder]\Unity\[Folder]\Library\PackageCache\com.microsoft.mixedreality.toolkit.standardassets@570a6e7bd8eb-1621237819262\EditorUtilities\OnLoadUtilities.cs:23
UnityEditor.EditorAssemblies:ProcessInitializeOnLoadAttributes (System.Type[])
</code>
Furthermore, I am a bit confused as to how the Microsoft Mixed Reality Feature Tool installed MRTK. Is it correct that after the installation everything ended up under the path "/Packages"? No folders were added under "/Assets". And the files under "Packages" can be considered "read only", so I'm confused that everything ended up there.
What I already found were some posts about the limitation of 260 characters for the path, but looking at the error there are 243 characters. Can this still be the problem?
Comment: You can read the solution at the end of my post :)
Comment: Please add the solution as an answer below
Answer: I saw in the documentation that there is already version 2.7.3, although Microsoft Mixed Reality Feature Tool does not show that at all. In the settings you have to activate the update and then you only get a version above 2.6.1 displayed. With the installation of 2.7.3 the error is gone! Regardless, I ask the future reader not to ignore my question about the imported mrtk files into the "/Packages" path.
Thank you!


How can I read the message properties of an Activemq.Advisory message from a Python3.7 application

Question: I am using paho.mqtt.client on a Raspberry Pi4 in Python3.7 to publish messages to an ActiveMQ instance running locally. I would like to monitor the status of the consumer of my queues so that I can raise an alert (to a Siemens PLC using snap7) if the subscriber goes offline. When I use a program like QueueExplorer, manually, I can look at a message in the 'Advisory' topic for my queue and from it's Custom property, I can see the 'consumer Count' and determine that there is an active consumer.

I need to get this information into my app but unfortunately MQTT messages don't have 'Properties' that can be accessed by paho.mqtt.client, and Activemq 'Advisory' messages don't have any data in the 'body' of the message, so I have to find another method of reading the 'consumer Count'. I have looked at STOMP but cannot find any examples of reading message 'Properties'. Any suggestions please?
This is the code I would need if I was using the CMS API from the ActiveMQ-CPP Library, but I believe that this is in C++ and that is not my world! :-)
void AdvisoryProducer::onMessage( const cms::Message* message ) {

   if( message->getCMSType() == "Advisory" ) {

       std::cout << "Received an Advisory Message!" << std::endl;

       if( message->propertyExists( "consumerCount" ) ) {

           std::string consumerCount = message->getStringProperty( "consumerCount" );
           std::cout << "Number of Consumers = " << consumerCount << std::endl;

           // Do Something Meaningful here....
       }

   } else {
       std::cout << "Received a Non-Advisory Message!" << std::endl;
   }
}

This is the code that I am trying to use at the moment but instead of subscribing to the topic, it creates a new queue!
import time
import sys

import stomp

class MyListener(stomp.ConnectionListener):
    def on_error(self, headers, message):
        print('received an error "%s"' % message)
    def on_message(self, message):
        print('received a message "%s"' % message)
        print(message.body)
        print(message.cmd)
        print(message.headers[''])

TOPIC = 'ActiveMQ.Advisory.Consumer.Topic.xbox_001'

conn = stomp.Connection()
conn.set_listener('', MyListener())
conn.connect('admin', 'password', wait=True)
conn.subscribe(destination=TOPIC, id='1', ack='auto')

time.sleep(3600)
conn.disconnect()

Before I run the code, I can see the existing topic that is created when the  'xbox_001' topic is created, and messages are generated in the advisory topic when subscribers connect etc. so that is working.

But when I run the code, it creates a new queue (and an advisory topic) instead of subscribing to the existing topic!
Comment: Try using `TOPIC = 'topic/ActiveMQ.Advisory.Consumer.Topic.xbox_001'`. I believe STOMP clients need to use `queue/` or `topic/` prefix to tell the broker which semantics to use since the STOMP protocol itself makes no such distinctions.
Comment: What STOMP client are you using from your Python application?
Comment: I'm using stomp.py V7.0.0
Answer: I FINALLY managed to sort out the issue, it was a simple (but annoying) string/path formatting problem. Unlike any other code in the history of programing EVER!, the path is a combination of '/' and '.' delimitators, and despite the fact that the file structure clearly has ''Topics' not 'topic' as the root, the path needed to be..... wait for it.... :-)

TOPIC = '/topic/ActiveMQ.Advisory.Consumer.Topic.xbox_001'

The mind boggles...
For completeness, here is the final code.

import time
import sys

import stomp

class MyListener(stomp.ConnectionListener):
    def on_error(self, headers, message):
        print('received an error "%s"' % message)
    def on_message(self, message):
        print('received a message "%s"' % message)
        print(message.body)
        print(message.cmd)
        print(message.headers['consumerCount'])

TOPIC = '/topic/ActiveMQ.Advisory.Consumer.Topic.xbox_001'
conn = stomp.Connection()
conn.set_listener('', MyListener())
conn.connect('admin', 'password', wait=True)
conn.subscribe(destination=TOPIC, id='1', ack='auto')

time.sleep(3600)
conn.disconnect()


proper test for indifference of two groups

Question: I'm reaching out with a question that, at first glance, might seem elementary, but given some perplexing advice from my thesis supervisor, I find myself in need of your expertise.
The scenario is straightforward: we have two groups of shooters, each with 100 participants. Every shooter takes 10 shots, and each shot is either a success or a failure.
I aim to determine if there's a significant difference in shooting accuracy between the two groups. My initial approach was to calculate the individual success rates and then compare these rates using a t-test. However, my mentor has indicated that this method is not suitable for analyzing proportions. On the other hand, if I use a proportion test (like prop.test or Fisher's exact test), I must consider each shot as an independent event, which doesn't seem correct since each shooter takes multiple shots.
I'm currently feeling uncertain and wonder if I might have overlooked something.
Answer: I can think of some sophisticated approaches that might work better (e.g., shooter as a random effect in a logistic regression), but sticking two groups of $100$ counts of hits into a two-sample t-test seems like it would be a solid approach. Since that just multiplies the values by the ten shots taken instead of using the proportion of hits (since everyone takes ten shots), this isn't fundamentally different from what you seem to have proposed.
If your advisor gripes about a t-test requiring normality of the two groups as well as equal variance:

Welch's t-test, which is the default in R software through t.test, handles the case where equal variances are not safe to assume (which I think it is not safe to assume here).

Both the usual and Welch t-test are quite robust to deviations from normality.

The Wilcoxon-Mann-Whitney U test (wilcox.test in R) could be a viable alternative.
Comment: I think your supervisor is mistaken and that my post is correct.
Comment: Hi Dave, thanks for your answer. However, it seems that my thesis supervisor instead looks for something like a proportion test. He gave me a link for that: https://online.stat.psu.edu/stat415/lesson/9/9.4. It is a bit strange for me, as if I go with proportion test, then I need to aggregate all shooters' attempts to derive the proportion. This assumes that each shoot is independent of other shoots, which is wrong (each shooter takes 10 attempts). Any thoughts here?
Answer: As you say in the question, the problem is the multiple tries for each shooter. Without that complication, the data could be presented as a contingency table and some test such as chi-square or Fisher exact test be used.
The usual thing to do here would be using a random effect for each shooter, that is, a (binomial) mixed effects model. You should have enough observations for that to be possible. Illustrating with some R code:
library(lme4)
mod0 <- glmer( success ~ Group + (1 | shooter), family=binomial,
               data=your_data_frame)
summary(mod0)

But, probably, the advice given by @Dave is simpler and would probably lead to the same conclusions.
Answer: A simple way to model this would be to use the (binomial) counts you observe and these are independent across shooters. As in:
nsucces <- c(6,7,8,8,9, 2,3,1,4,6)
group <- c(1,1,1,1,1,0,0,0,0,0)
id <- c(1,2,3,4,5,6,7,8,9,10)

model <- glm(cbind(nsucces,10-shoot) ~ group, family=binomial)
summary(model)

So a random effect across shooters is not immediately required. Since your dependent variable is a count (out of 10, or a proportion if you like), why not analyze it as such? Then you have no issues with whether t is suited here or not.
Comment: But formally, this assumes that the binomial probabilities are constant within each group. If not, that could be seen as overdispersion
Comment: Yes, @kjetil, you are right, that could be tested indeed, but such overdispersion maybe not always exist.


Matching columns from one data frame to another

Question: I have two dataframes (T and S). They both share a column name called ID but S has a latitude and longitude column. I would like to go through both data frames and match each lat and long to their appropriate IDs (station IDs in each DF is not in the same order) in dataframe T. These DFs are not the same size but they are both very large with some duplicates.
Comment: Elaborate on your last 3 words.
Comment: Perhaps start [here](https://stackoverflow.com/questions/1299871/how-to-join-merge-data-frames-inner-outer-left-right).
Answer: <code>print pd.merge(T, S, on='long' 'lat', how='inner')
</code>


How to use views filter on an entity property

Question: I used hook_entity_property_info_alter to add two properties to an existing entity [crm_core_contact].  I find that I can see these two new properties in the "Fields" section of views, and that my views will display the values of those properties, but I cannot see these new properties in either the Sort or the Filter section of Views?  Any ideas on documentation that might tell me what is going on?
Here is the code for one of the properties:
$properties = &$info['crm_core_contact']['properties'];
$properties['notes'] = array(
                'setter callback' => 'entity_property_verbatim_set',
                'setter_permission' => 'Administer wcgopindividualinfo content',
                'label' => 'NotesText',
                'type' => 'text',
                'schema field' => 'notes',
                'getter callback' => 'entity_property_verbatim_get',
                'entity views field' => TRUE,
                'getter_permission' => 'Administer wcgopindividualinfo content',
                );
Although the Trellon documentation does not say this, I'm wondering if I need to add a hook_views_data_alter function to specify the filter and sort handlers for the properties that I added.
Answer: I have now done some experimentation and find that yes, what I needed to do was use hook_views_data_alter to tell views how to handle the properties I had added above.  Here is the code inside my hook_views_data_alter function:
$data['crm_core_contact']['notes'] = array(
            'title' => t('Notes'),
            'help' => t('The notes for the contact'),
         // Information for displaying the notes field
                'field' => array(
            'handler' => 'views_handler_field',
            'click sortable' => TRUE,
  ),

    // Information for accepting a note as a filter
        'filter' => array(
        'handler' => 'views_handler_filter_string',
  ),
    // Information for sorting on a note.
        'sort' => array(
        'handler' => 'views_handler_sort',
  ),
);


UTF-8 and HTML entities

Question: I try to eject text from Word .DOC file with PHP. All seems ok, but the only trouble is something like
СУДОВА БУХГАЛТЕРІЯ

instead of russian text. I've tried to use html_entity_decode and utf8_encode, but they didn't help. Is there any simple solution?
Answer: html_entity_decode should work with the proper parameters (unless you're using PHP 5.3.3 or later):
html_entity_decode($str, ENT_QUOTES, 'UTF-8')

This will convert the character references into UTF-8. Before PHP 5.3.3, the charset parameter's default value was ISO-8859-1. In that case the cyrillic characters can't be converted as the ISO 8859-1 character set doesn't contain them.

UTF-8 and HTML entities


Schur orthogonality relation between equivalent but unequal representations?

Question: The Schur orthogonality relation in coordinate/matrix element form reads
$$\sum_{R\in G}^{|G|} \; \Gamma^{(\lambda)} (R)_{nm}^*\;\Gamma^{(\mu)} (R)_{n'm'} =
\delta_{\lambda\mu} \delta_{nn'}\delta_{mm'} \frac{|G|}{l_\lambda}$$
where $\lambda,\mu$ lable the irreducible representations of group $G$.
But there seems to be a case not specified clearly.
What happens when the two representations $\lambda$ and $\mu=\lambda'$ are equivalent but not identical to each other, i.e., related by a similarity transformation. What the relation would be in this case?
This is not an issue in the orthogonality relation in character form since Tr() is invariant under a similarity transformation. But for the matrix form above, the proof seems to be affected. For instance, when finding the normalization factor, one proof I saw uses (setting $\mu=\lambda$)
$$c_{m'm}l_\lambda=\sum_{R}\sum_n \; \Gamma^{(\lambda)} (R^{-1})_{mn}\;\Gamma^{(\lambda)} (R)_{nm'} = \sum_{R} \; \Gamma^{(\lambda)} (R^{-1}R)_{mm'}.$$
But how about setting $\mu=\lambda'$? I feel it is not immediately true to have the second equality since $\Gamma^{(\lambda)}$ and $\Gamma^{(\lambda')}$ are not identical.
Answer: Suppose $\langle-,-\rangle$ is a complex inner rep on a $G$-irrep $U$. If $u,v\in U$ are two vectors, we say $g\mapsto\langle u,gv\rangle$, as a function $G\to\mathbb{C}$, is a matrix coefficient. If $u,v$ are basis vectors in some ordered basis, this is literally the corresponding entry of $g$ represented as a matrix.
The functions $G\to\mathbb{C}$ form their own complex inner product space $\mathbb{C}^G$ with inner product $\langle f_1,f_2\rangle=\frac{1}{|G|}\sum_{g\in G}\overline{f_1(g)}f_2(g)$. Schur orthogonality says
$$ \big\langle \langle a,gb\rangle,\langle c,gd\rangle \big\rangle=\langle c,a\rangle\langle b,d\rangle/\dim U. $$
An equivalent representation on $U$ uses $TgT^{-1}$ instead of $g$, for some $T\in GL(U)$. Observe
$$ \big\langle\langle a,TgT^{-1}b\rangle,\langle c,gd\rangle\big\rangle =\langle Tc,a\rangle\langle T^{-1}b,d\rangle/\dim U. $$
If we pick $a,b,c,d$ from an orthonormal basis for $U$, the above values are not necessarily $0$ or $1$ over $\dim U$; as we let $a,b,c,d$ be orthonormal and let $T$ vary, the right side can be many kinds of values. This means there's very little to no relation between matrix coefficients of different but equivalent irreps like we see with Schur orthogonality for a given irrep.


What is the limit of this sequence involving logs of binomials?

Question: Define  $$P_{n} = \frac{\log \binom{n}{0} + \log \binom{n}{1} + \dots +\log \binom{n}{n}}{n^{2}}$$ where $n = 1, 2, \dots$ and $\log$ is the natural log function. Find $$\lim_{n\to\infty} P_{n}$$ Using the property of the $\log$, I am thinking to find the product of all the binomial coefficients. But it gets really messy.
Comment: We could rewrite as a set of sums... $\log\binom nk = \log (n!)-\log(k!)-\log((n-k)!)$...
Comment: You can easily get an upper bound the $\limsup$ as $\log 2$ using AM/GM. You get $P_n\leq \log 2-\frac{\log n}{n}$.
Comment: You may also want to either define what happens at $n=0$, or skip that value...
Comment: sorry, $n$ should start at 1
Comment: Since you are looking at $n \to \infty$, it doesn't matter where you start.
Answer: $$Q_n=\prod_{k=1}^{n-1}\binom{n}{k} = \frac{(n!)^{n-1}}{\left(\prod_{k=1}^{n-1} k!\right)^2}=\prod_{k=1}^{n-1}\frac{n!}{(k!)^2}$$
So $$Q_{n+1} =\frac{(n+1)^{n-1}(n+1)!}{(n!)^2}Q_n=\frac{(n+1)^n}{n!}Q_n$$
So $$\log Q_{n+1} =\log Q_n + n\log(n+1)-\log(n!)$$
So:
$$\log Q_n = \sum_{k=1}^n \left((k-1)\log k -\log\left((k-1)!\right)\right)$$
Now $\log (k-1)! = (k-1)\log (k-1) - (k-1) + O(\log k)$ so:
$$\log Q_n = \sum_{k=2}^n (k-1)\left(\log\left(1-\frac{1}{k-1}\right)\right) +\frac{n(n-1)}{2} + O(\log(n!))$$
So $$P_n =\frac{\log Q_n}{n^2}=\frac{1}{n^2}\sum_{k=1}^n \log \left(\left(1-\frac{1}{k-1}\right)^{k-1}\right)+ \frac{n(n-1)}{2n^2} + O\left(\frac{\log n}{n}\right)$$
But $\left(1-\frac{1}{k-1}\right)^{k-1}\to e^{-1}$, so you are done.
So I get $P_n\to\frac{1}{2}$ as the limit.
Comment: Same result as my just entered one. Nice.
Comment: What is the definition of $P_n$?  It suddenly appears for the finale.  Apology in advance if I missed something;  it's getting very late.
Comment: It's in the original question. @Dr.MV But I did have a few instances where wrote $Q_n$ when I meant $\log Q_n$.
Comment: Yes, I thought the latter was the case.  And I missed the designation $P_n$ of the OP and jumped right to the sum.
Answer: The limit is $1/2$.
Here is a proof by authority:
This is copied from here:
Prove that $\prod_{k=1}^{\infty} \big\{(1+\frac1{k})^{k+\frac1{2}}\big/e\big\} = \dfrac{e}{\sqrt{2\pi}}$
$$\prod_{k=0}^n \binom{n}{k} \sim
C^{-1}\frac{e^{n(n+2)/2}}{n^{(3n+2)/6}(2\pi)^{(2n+1)/4}}
\exp\big\{-\sum_{p\ge 1}\frac{B_{p+1}+B_{p+2}}{p(p+1)}\frac1{n^p}\big\}\text{ as }n \to \infty
$$
where
$$\begin{align}
C
&= \lim_{n \to \infty}
\frac1{n^{1/12}}
\prod_{k=1}^n \big\{k!\big/\sqrt{2\pi k}\big(\frac{k}{e}\big)^k\big\}\\
&\approx 1.04633506677...\\
\end{align}
$$
and the $\{B_p\}$
are the Bernoulli numbers,
defined by
$$\sum_{p \ge 0} B_p\frac{x^p}{p!} = \frac{x}{e^x-1}
.$$
If the $n^2$ root is taken,
the only term that
does not go to $1$
is
$e^{1/2}$
(from
$e^{n(n+2)/2}$)
so that
$\left(\prod_{k=0}^n \binom{n}{k}\right)^{1/n^2}
\sim e^{1/2}
$
or
$\dfrac{\sum_{k=0}^n \ln \binom{n}{k}}{n^2}
\sim 1/2
$.
There is probably a relatively simple proof.
It might be easier to find
knowing the answer.
Comment: My mystery downvoter strikes again, twice!
Comment: That's mysterious! But I upvote it so it goes back to zero.
Comment: Nice use of the result.
Comment: I came up with an elementary proof and entered is an a third answer.
Comment: Proof by authority?
Answer: Let's see if I can come up
with a simple proof
that the limit is 1/2.
The log of the numerator
(of the product of binomial coefficients)
 is easy:
$\dfrac{(n+1)\ln n!}{n^2}
\sim \dfrac{(n+1)(n \ln n - n + O(\ln n))}{n^2}
=(\ln n) -1 + o(1)
 $.
For the log of the denominator
(of the product of binomial coefficients)
,
we need
$\begin{array}\\
d_n
&=\sum_{k=0}^n \ln k!\\
&=\sum_{k=1}^n \sum_{i=1}^k \ln i\\
&=\sum_{i=1}^n \sum_{k=i}^n \ln i\\
&=\sum_{i=1}^n (n-i+1) \ln i\\
&=\sum_{i=1}^n (n+1) \ln i-\sum_{i=1}^n i \ln i\\
&=(n+1)\ln(n!)-\sum_{i=1}^n i (\ln (i/n)+\ln(n))\\
&=(n+1)\ln(n!)-\sum_{i=1}^n i \ln (i/n)-\sum_{i=1}^n i \ln(n)\\
&=(n+1)\ln(n!)-\sum_{i=1}^n i \ln (i/n)-\ln(n)n(n+1)/2\\
&\sim (n+1)(n \ln n - n + O(\ln n))-\sum_{i=1}^n i \ln (i/n)-(n^2/2)\ln(n)+O(n \ln n)\\
&\sim \frac12 n^2 \ln(n)-n^2+o(n^2)-\sum_{i=1}^n i \ln (i/n)\\
\end{array}
$
The denominator
is
$\dfrac{2d_n}{n^2}
\sim\ln(n)-2-\frac{2}{n}\sum_{i=1}^n \frac{i}{n} \ln (i/n) + o(1)
$.
Subtracting them,
we get
$1+2\frac1{n}\sum_{i=1}^n \frac{i}{n} \ln (i/n) + o(1)
$.
That sum is a
Riemann approximation
(which is, of course,
what I was trying for)
to
$\int_0^1 x \ln(x) dx
=\frac12 x^2 \ln x - \frac{x^2}{4}|_0^1
=-\frac14
$.
The final result is
$1-2\frac14
=\frac12
$
as it should be.
Answer: Here's an upper bound
(probably not good enough)
for a start:
From the arithmetic-geometric mean inequality,
$\prod_{i=0}^n \binom{n}{i}
<\left(\dfrac{\sum_{i=0}^n \binom{n}{i}}{n}\right)^n
=\left(\dfrac{2^n}{n}\right)^n
=\dfrac{2^{n^2}}{n^n}
$
so
$(\prod_{i=0}^n \binom{n}{i})^{1/n^2}
<\dfrac{2}{n^{1/n}}
< 2
$
or
$\dfrac{\sum_{i=0}^n \ln \binom{n}{i}}{n^2}
< \ln 2
$.
Comment: Technically, you have to skip the $i=0$ term to get that result, but since $\binom{n}0=1$, it doesn't affect the product. (Your product has $n+1$ terms.)


Change the StatusBar text color based on underlying content

Question: In our application we have a page where the StatusBar overlays user generated images. Sometimes these images have a darker top, and sometimes a lighter. This means sometimes the Statusbar on that page isn't visible, or is extremely hard to see. Considering this is the main page of our application, I'm wondering if there's a way to change the color of the StatusBar text based on the underlying content.
(Best font color for the background).
Yes, I'm aware we could show a static background color for the StatusBar, but that would be extremely tacky.
Comment: I am afraid, there is not such a solution, that would work for all the underlaying images. Suppose, your image goes from the black on left to the white on the right. Definitely it is not possible to have multicolor statusbar.
Comment: @pedrouan - That is a very great point which I didn't think about. I guess I'll just put a `rgba(0,0,0,0.3)` overlay on the images so that statusbar can always be seen.
Comment: That's a good idea. Maybe you find the best white/black intensity so it always be visible and universal as well. Or to make blurred background so the visibility would be a bit better. I saw some solutions where all the status bar is disappearing while on the image. After scrolling when a bar is on text, it appears back.
Answer: I have perfect way for this: in top of your view with image create minimal shadow. It will be invisible to the user
Comment: This is a great idea, doesn't answer the question, but still a good idea as a workaround.


Aegir / drush alias issue: profiles specified at command line get forgotten

Question: Note: Aegir is an installation / site management tool for drupal sites & platforms. See http://community.aegirproject.org/ for details.
This question may be down to an Aegir issue or a drush one; thoughts from either angle are welcome:
I've managed to create Aegir/drupal platforms via both the command line (see http://lists.aegirproject.org/pipermail/aegir/2011-January/000026.html) and web interface, and I can get sites to install with a selected profile through the web interface, but when I try to install a site via the command line it keeps resetting to the default profile. Can anyone see what I'm doing wrong here?
I create a site alias:
drush --uri='demo.c.didev.co.uk' provision-save '@site_demo.c.didev.co.uk' --context_type=site --platform='@platform_dennis_generic_20110316b' --profile='myprofile' --db_server='@server_localhost' --email@example.com'

and it creates a valid alias file:
cat .drush/site_demo.c.didev.co.uk.alias.drushrc.php
<?php $aliases['site_demo.c.didev.co.uk'] = array (
'context_type' => 'site',
'platform' => '@platform_dennis_generic_20110316b',
'server' => '@server_master', 'db_server' => '@server_localhost',
'uri' => 'demo.c.didev.co.uk',
'root' => '/var/aegir/platforms/dennis_generic_20110316b/',
'site_path' => '/var/aegir/platforms/dennis_generic_20110316b//sites/demo.c.didev.co.uk',
'site_enabled' => true,
'language' => 'en',
'client_email' => 'firstname.lastname@example.com',
'aliases' =>  array ( ),
'redirection' => false,
'profile' => 'myprofile', );

However, when I run "drush @hostmaster hosting-import @site_demo.c.didev.co.uk" it rewrites the alias file to "profile = default" and installs with the default profile!
Now, this is a pain but not a disaster as I can do the initial site creating via the web interface and it'll work, but I get apparently related errors when trying to migrate on the command line (per instructions at http://community.aegirproject.org/node/41) where it appears to not create an array of profiles and crashes (I'll post on that separately later) and wanted to rule out these problems before I tackle those.
So - am I doing something wrong, or is there just a bug?
Comment: can you do a normal 'drush si' using the profile?
Answer: I tweeted this to Mig - he says:

probably a bug. Workaround is to not hosting-import the site but re-verify the platform & let it autoimport site by itself

HTH! =)
Answer: This shows something akin to what you are doing. One interesting line in it is.

Be sure to install the 3.3 version of
  Drush as any newer versions will cause
  problems with Aegir later (as I found
  out the hard way)

That may be worth trying.


User login doesn't work after server migration

Question: We had a Drupal 7 site running on PHP 5.6. We have moved this site to another server running on PHP 7.4.
When I navigate to /user/login, type my username and password, and click on Submit, I'm redirected to /users/myusername, but it says Access Denied and it doesn't show the top bar to change configuration, content, etc. I had also checked the sessions table and it stores the new session with the user ID.

No session ID has been stored in cookies after I log in.

I had tried so many ways, but nothing helped me.

I checked that mod_rewrite is enabled
I tried with and without Base URL setting in the settings.php file
I tried with and without RewriteBase setting in the .htaccess file
I tried with and without cookie_domain setting in the settings.php file

I am surprised that, when I tried to migrate another website to the same server with another sub-directory, the login worked fine.
They are Drupal 7 sites migrated to the same server but on different sub-directories.
Why doesn't the login work in one of the sites?
Answer: After a lot of debug I found the issue in settings.php file
ini_set('session.cookie_secure', 1);

for HTTPS site the session cookie must be secure but as the current site is HTTP, so we need to turn off this feature by
ini_set('session.cookie_secure', 0);

Now, login is working fine.


addition vs comparison

Question: Let say I have an array of 1,000,000 elements with about 90% of 0s and 10% of 1s.
In order to count of 1s, I can do
sum=0;
for(int i=0;i<size;i++) {
    sum+=x[i]
}

But I thought maybe comparison is cheaper than addition so this would be better.
sum=0;
for(int i=0;i<size;i++) {
    if(x[i]==1)
        sum++;
}

But I am not sure. Which one is faster?
Comment: Even without profiling, I can almost guarantee that the first option is faster unless `sum` happens to be `volatile` or something stupid like that. The second case could also suffer from [branch prediction](http://stackoverflow.com/q/11227809/922184).
Comment: Have you tried profiling your code?
Answer: It is hard to say which one is going to be faster without trying it, but a even a slightly slower instruction without a branch will usually be faster due to pipelining and branch prediction.
In your case, the branch predictor will be wrong 90% of the time, reducing the speed quite a bit.
Comment: `wrong 90% of the time` That's not how predictors work.
Comment: I agree with @scientiaesthete here; the branch predictor should get it right 90% of the time. Otherwise it's a lousy predictor. However, the more interesting point is that comparing a number to 1 is essentially the same as adding the number to something. So compare and optionally increment is more work than unconditionally add.

addition vs comparison


Access remote folder with credentials in Ruby

Question: in Sinatra I'm generating an excel file and I should copy it to some remote folder with credentials.
Does anyone have idea how to access folder which are credentials restricted?
Thank you
Comment: How should you copy the folder? Any Idea what the remote destination provides ?

SSH, FTP, SFTP,. ....
Comment: Just FileUtils.mv. Should be possible, right?
Comment: Depends on your definition of remote then....
Comment: I got an address like this: \\remote-folder
Comment: Can you give more detail on what this "remote service" is? For example, if you're using AWS S3 storage then you could use a bucket policy.
Comment: Remote folder (not service) is just a folder on remote server. For example *192.168.0.0\some-folder*. But credentials are needed.
Answer: I have used a Sambal if anyone need this.


Erro ao armazenar byte na db mysql

Question: estou tentando armazenar que recebo na db mysql, porem esta dando esse erro creio que seja type da coluna erro:

26/02/2018 09:25:14 User connected
26/02/2018 09:25:14 Login : Skell
26/02/2018 09:25:14 Error: System.FormatException: Input string was not in a correct format.
   at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
   at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
   at System.Byte.Parse(String s, NumberStyles style, NumberFormatInfo info)
   at System.Convert.ToByte(String value)
   at libcomservice.Game.inventory.GetInventoryInfo(Session PLAYER) in D:\SkelletonX\GC\GC IV GC Nexus 2018\GameServer\Server\Request\Tables\Inventory.cs:line 101

linha 101 do meu code:
RequiredLevel = Convert.ToByte(DBAcess_0.Tables[0].Rows[i]["RequiredLevel"].ToString()), //?

na minha tabela tem uma coluna 'RequiredLevel' o type dela eu coloquei como
blob, porem mesmo assim da erro. Como posso resolver?
Answer: Tente usando o Encoding.GetBytes()
byte[] bytes = Encoding.ASCII.GetBytes(DBAcess_0.Tables[0].Rows[i]["RequiredLevel"].ToString());

Nessa resposta você pode ver um exemplo de uso do Encoding, convertendo para byte[] e de volta para string.
Comment: e na data type da coluna  eu deixo como blob ?
Comment: acredito que não tem problema. Como você tem um array de bytes, pode salvá-lo em uma "coluna _blob_"
Comment: @Guilherme, deu certo?!

Erro ao armazenar byte na db mysql


Why are an even number of flips required to get back to the original list?

Question: Consider the list of numbers $[1, \cdots, n]$ for some positive integer $n$. Two distinct elements $i$ and $j$ of the list can be switched in a so-called flip. For example, let $f$ be a flip that switches $2$ and $4$. Then $f([1,2,3,4]) = [1,4,3,2]$. Now consider a sequence of $k$ flips $f_1, \cdots, f_k$ of the list $[1, \cdots, n]$ such that $f_1(f_2(\cdots f_k([1,\cdots,n])\cdots)) = [1,\cdots, n]$, i.e. performing all flips gives the original list. Then $k$ must be even.
I would like to find a proof of this proposition that is elementary as possible. I already came up with a justification using permutation groups which goes as follows:
Each flip $f_i$ corresponds to a transposition of the list $[1, \cdots, n]$. Since the composition $f_1f_2\cdots f_k$ results in the identity, it must be an even permutation. Thus any representation of $f_1f_2\cdots f_k$  as a product of transpositions must contain an even number of transpositions. In particular, since each $f_i$ is a transposition, it follows that $k$ must be even.
This "proof" trivializes the problem statement as it is by using relatively high-powered facts about permutation groups. Is there a lower-level proof that avoids using theses results? (Ideally such a proof would avoid permutation groups altogether and be understandable to the layman.)
Edit: to clarify (since this question hasn't been getting as much attention as I had hoped), any proof that avoids re-deriving these powerful results about permutations would suffice. Basically I would want a proof that does not prove much more than the question requires, i.e. doesn't have a part where it says "in particular".
Comment: I think user3313320's answer is the best you can do. It completely avoids any algebra and involves only counting the number of inversions.
Answer: Here is a combinatoric proof (which I am not sure if it is from permutation group).
Count the number of 'reversed pair' in the list. What I mean by reversed pair is pair of numbers which the one bigger in value comes before the smaller one. For example, in $[2,1,3,4]$, $(2,1)$ is a reversed pair but $(1,3)$ is not.
Now observe the change of the number of reversed pair when a flip is taken. Let's say the list is $[\cdots,a,\cdots,b,\cdots]$ and we flip $a,b$, turning it into $[\cdots,b,\cdots,a,\cdots]$. It should be obvious that those in front or behind does not contribute any changes. Also, for those in between, lets call one of it $c$, will only contribute if $a<c<b$ or $a>c>b$. $+2$ for the former and $-2$ for the latter. And finally, the $a,b$ pair. $+1$ if $a<b$ and $-1$ if $a>b$. Anyway, the total number changes by an odd number. Since you have total number of $0$ at beginning and you want $0$ at the end, you have to flip even number of times.
Hope this helps you.
Comment: This is the answer I was going to give. Beat me to it.
Comment: This is exactly the type of proof I was looking for! Great explanation, thank you.
Comment: You're very welcome. Cheers!
Answer: Your flips of $[1,\ldots,n]$ are precisely transpositions of $\{1,\ldots,n\}$, so proving your statement about flips is immediately equivalent to proving the powerful statement about permutation groups that the identity is not the product of any odd number of transpositions. So it is inevitable to either rely on these powerful results or rederive them. I'll try to rederive them in an elementary way.

Let $f_1,\ldots,f_k$ flips of $[1,\ldots,n]$ such that $f_1\circ\cdots\circ f_k$ is the identity. We want to show $k$ is even. This is evidently true for $k=2$, and we proceed from here by induction, so let $k>2$ and suppose the above holds for all $k'<k$. I'll use cycle notation here and there for brevity.
A key observation that can be illustrated to the layman clearly by example, are the identities
$$(cd)(ab)=(ab)(cd)\qquad\text{ and }\qquad(bc)(ab)=(ac)(bc),$$
meaning that a flip that does move $a$ followed by a flip that doesn't move $a$ has the same result as some flip that doesn't move $a$ followed by a flip that does move $a$. A picture illustrates this:

$$\texttt{These aren't the most illustrative pictures.}$$
In the identities above it is important to observe that the number of flips stays the same, and the number of flips that move $a$ also stays the same, while pushing the flip that moves $a$ to the left.
Let $a$ be a number switched by $f_1$. Because the sequence of flips results in the identity there must be another flip that switches $a$. Let $f_i$ be the next one, i.e. the one with the lowest $i$. Using the identities above we can push this flip left to get a sequence starting with $f_1$ followed by another flip that moves $a$, which still results in the identity. All the while keeping the same total number of flips, and the same number of flips switching $a$. If now the first two flips are distinct then the identity
$$(a\ b)(a\ c)=(a\ c)(b\ c),$$
which holds for distinct $a$, $b$, $c$, yields a sequence of the same length with one less flip switching $a$, and still starting with a flip switching $a$. We can repeat this process for the next flip $f_j$ switching $a$, and keep repeating it until the first two flips are not distinct. Every time we repeat this process the number of flips moving $a$ decreases by $1$, and this number cannot be $1$, so we will get a sequence starting with two flips that are not distinct. This means the first two flips cancel, and hence that the remaining sequence of $k-2$ flips also results in the identity. Then by induction hypothesis $k-2$ is even, and therefore $k$ is even.
Answer: Let $\ell=(x_1,x_2,\ldots, x_n)$ be a list of the numbers in $[n]$. For each $k\in[n]$ denote by $p_k$ the number of $x_i\ (1\leq i<k)$ with $x_i>x_k\,$, and call $\beta(\ell):=\sum_{k=1}^n p_k$  the badness of $\ell$. It is easy to convince oneself that a transposition ("flip") $\tau:\>\ell\mapsto\ell'$ changes the badness by $\pm1$. It follows that an odd number of flips cannot restore a given $\ell$ to its original version.
Answer: The complete transposition graph $X_n$ is defined to be the graph whose vertex set is the symmetric group $S_n$ and two vertices are adjacent whenever they differ by a transposition.  It is easy to see that this graph is bipartite, with bipartition the set of even permutations and the set of odd permutations.  You want to prove that any walk in this graph that starts at the identity vertex and returns to the identity vertex has even length (this is true for any initial vertex, not just the identity permutation).   This is clear because a bipartite graph does not contain odd cycles, but the proof that the complete transposition graph is bipartite uses the notion of even and odd permutations.
Perhaps you can draw (to the layman) such a complete transposition graph in the form of a bipartite graph (for small values of $n$), and then explain that in a bipartite graph if one starts from a vertex in the left vertex set and returns back to a vertex in the left vertex set (it can even be a vertex which is different from the initial vertex), then one must have traversed an even number of edges.
Instead of using the concept of even permutations, perhaps you can use the concept of the number of inversions of a permutation.  You can restrict yourself to doing swaps of just adjacent elements.  Each adjacent swap changes the number of inversions by 1.  And so returning back to the same permutation must have used an even number of adjacent swaps. The corresponding graph on vertex set $S_n$ is called the bubble-sort graph and it is bipartite (in fact, it is a subgraph of the complete transposition graph), with bipartition the set of permutations having an even number of inversions and those with an odd number of inversions.   Now you can show that any arbitrary (ie including non-adjacent) swap changes the number of inversions by an odd number and therefore corresponds to going from one part of the bipartition to the other in this bubble-sort graph.  (You are essentially using the fact that a permutation is even iff it has an even number of inversions.)
Answer: The value of k will be positive since to get back two numbers back to its position we have to do two flips.
For ex - for[1,2,3,4,5] we have first flip it once i.e.2 and 5 now to get back the original set again we again have to flip 2 and 5.
Now if we use k flips then it must be even since the have to be reversed that are reversed by k-1 flips.
Comment: Yeah no this is incorrect, sorry. When you add in different flips, it is no longer obvious why the number of flips has to be even. For instance, 1,2,3,4 -> 2,1,3,4 -> 3,1,2,4 -> 3,2,1,4 -> 1,2,3,4 needs 4 flips.


the enter key does not work

Question: the enter key does not work. After filling out the form does not work.I do not want to use the form tag.

     Name:
    <input type="text" class="span2" name="loginname" id="loginname"  />
     password
    <input type="password" class="span2" name="loginpass" id="loginpass" />
    <button type="submit" class="btn btn-success" autofocus onclick="login()">enter</button>

because i used ajax with codeginiter.

  function login(){
          var usr = $('#loginname').val();
          var pass= $('#loginpass').val();
         $.ajax({
                      type: "POST",
                      url: "http://localhost/ci/index.php/user/register",
                       data: {          "isim": usr,
                                        'pass' : sifre,
                                      },
                      success: function(msg){
                        if (msg=="ok") {
                         window.location = "http://localhost/ci/index.php/user/main";

                         }else{

                              new Messi(msg, {title: 'ERROR', modal: true});
                         }
                      }
                    });
     }
        }

}
Comment: Why would you not use tags that are specifically designed for your purpose?
Comment: What do you mean you do not want to use the `form` tag? How else will your values be submitted?
Comment: add your js function login() in question.
Comment: Without a form tag you can't submit a form with Enter key. Sorry.
Comment: try `onsubmit` instead on `onclick`
Comment: i used ajax and with codeigniter.
Comment: @osmansert have u got ur answer?
Answer: try this

<title>title</title>

  <form action="" method="post">
  Name: <input type="text" name="name"/>

  Pwd: <input type="password" name="password"/>

  <input type="submit"/>
</form>

JS file
function divClicked() {
$(this).html("Clicked");
//Do form submission
}

$(function() {
    $("input[type=submit]").addClass("hidden");
    $("form").append($(document.createElement("div")).html("My div").click(divClicked));
});

css file
input.hidden {
    border: 0 none;
    height: 0;
    width: 0;
    padding: 0;
    margin: 0;
    overflow: hidden;
}

This is the JSFIDDLE  http://jsfiddle.net/Suyw6/1/
Comment: i am editing question.i dont form because  i use ajax.
Answer: In order to use enter you need to have a form and on form add event onSubmit. then it will work for both submit button and enter.
Answer: If you don't want use form tag you can use ajax
try this:
this is javascript/jquery for your login() function that you use in onclick
function login(){
    loginName = $('#loginname').val();
    loginPass = $('#loginpass').val();
    $.ajax({
        url: 'yourActionUrl?cmd=login&loginname=' + loginname + '&loginpass=' + loginPass,
        type: "GET",
        dataType: "html"
    }).done(function(data){
        alert(data);
    });
}

see ajax website for more information
Comment: thanks. but enter button dont work.
Answer: Try something like this:
$(document).keypress(function(event){
    var keycode = (event.keyCode ? event.keyCode : event.which);
    if(keycode == '13'){
        alert('You pressed "enter" somewhere');
            //you login call goes here
    }
});

You can also change that to grab keypresses from either textboxes

the enter key does not work


Why I can't get URL in webView

Question: Why i can not get the URL in the textView url? thanks so much for the help xP
public class Browser1Activity extends Activity {

TextView url;
WebView ourBrow;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.main);

    ourBrow = (WebView) findViewById(R.id.wvBrowser);
    url = (TextView) findViewById(R.id.tvURL);
    // cancel the web intent that default in android setting
    ourBrow.setWebViewClient(new WebViewClient());

    // webView seeting
    ourBrow.getSettings().setJavaScriptEnabled(true);
    ourBrow.getSettings().setLoadWithOverviewMode(true);
    ourBrow.getSettings().setUseWideViewPort(true);

    try {
        ourBrow.loadUrl("https://www.google.com.au");
    } catch (Exception e) {
        e.printStackTrace();
    }
    url.setText(ourBrow.getUrl());
}

    }

Comment: is an error being thrown?  Does ourBrow.getUrl() return the value you expect?  is url pointing to a valid object?
Answer: Can you try something like this?
TextView url = new TextView(this);

Maybe something was going wrong with the way the TextView was being created.
For your WebView, try this:
    WebView ourBrow = (WebView) findViewById(R.id.wvBrowser);
    ourBrow.setWebViewClient(new WebViewClient());
    ourBrow.loadUrl("https://www.google.com/");

Comment: the TextView was setted in correct, but it seems I can't get anything from "ourBrow". any idea??
Comment: if this doesnt, work it's possible you may have to edit your wvBrowser file, but let me know if this works!
Answer: you can get Url any time when page finished or page started
        WebView web=new WebView(this);
    web.setWebViewClient(new WebViewClient(){

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            // can get Here
            view.getUrl();
            //Now set to TExtView
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            // can get Here
            view.getUrl();
            //Now set to TExtView
        }
    });

Why I can't get URL in webView


Using a QGLWidget as the viewport for QGraphicsView results in black screen

Question: I have a QGraphicsView displaying a QGraphicsScene which I would like to use a QGLWidget as the viewport for. The Qt documentation leads me to believe that it is a simple as giving my QGraphicsScene a QGLWidget as a viewport, however I get a black screen when I try.
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QGraphicsPixmapItem>
#include <QGLWidget>

class View : public QGraphicsView
{
  Q_OBJECT
public:
  explicit View(QWidget *parent = 0) :
    QGraphicsView(parent)
  {
    QGraphicsPixmapItem *pixmapItem = new QGraphicsPixmapItem(QPixmap(":/images/chart.png"));

    QGraphicsScene *scene = new QGraphicsScene();
    scene->addItem(pixmapItem);
    setScene(scene);

    setViewport(new QGLWidget());
  }
};

If I comment the last to lines pertaining to the QGLWidget then my pixmap displays fine, however with them in I only see a black screen. I have also noticed that the CPU usage is significantly higher when the QGLWidget is in. I have successfully used QGLWidgets in the past (never with a QGraphicsView though) so I think that OpenGL itself is working correctly. I have tried changed the gl clear color to try to see a change but it remains black. I have also tried it using both Qt 4 and Qt 5.
Answer: When drawing a QPixmap to a QGLWidget, OpenGL textures are used.  The OpenGL platform will have a maximum texture size, and most likely your image is exceeding this limit.
An easy fix is to subdivide the pixmap into smaller tiles, add them to the QGraphicsScene, then group them:
QPixmap pixmap(":/images/chart.png");
QSize tileSize(512, 512);
QList<QGraphicsItem *> tiles;
for(int y = 0; y < pixmap.height(); y += tileSize.height())
{
    for(int x = 0; x < pixmap.width(); x+= tileSize.width())
    {
        int w = qMin(tileSize.width(), pixmap.width() - x);
        int h = qMin(tileSize.height(), pixmap.height() - y);

        QGraphicsItem *tile = scene->addPixmap(pixmap.copy(x, y, w, h));
        tile->setPos(x, y);
        tiles.append(tile);
      }
 }
 QGraphicsItem *pixmapItem = scene->createItemGroup(tiles);

This results in pixmapItem pointing to a group of pixmaps that can be treated as a single unit. Be sure to choose a suitable tile size smaller than the maximum texture size.
Answer: Try OpenGLES with version and surface format specification:
QCoreApplication::setAttribute(Qt::AA_UseOpenGLES);
QSurfaceFormat format;
format.setVersion(2, 0);
format.setProfile(QSurfaceFormat::NoProfile);
format.setSwapInterval(1);
format.setSwapBehavior(QSurfaceFormat::DoubleBuffer);
QSurfaceFormat::setDefaultFormat(format);


Styling in D3 with a loop?

Question: I wonder if it possible to use styling actions on the same element many times? I got this Array called A which stores 3 colours and I want to go through a loop that fills my element link.
var A = ["blue", "red", "green"]

    for ( var i = 0; i < A.length; i++){

                link.style("stroke", function(d)
                {

                   return A[i];

                 }
                 )
                };

Comment: So, have you run the code and tested if it is possible?
Comment: Yes, it is possible. But I feel that this is an x,y problem. Your code will style the nodes in `link` three times in a row, but fast enough you will just see them as green, no? Or are you trying to achieve something different?
Comment: yep, only the color of the last element (green) of the Array is shown on screen. Why is that?
Comment: @ Teemu: It works, but only the last element of the Array gets active. That means, all links get green.
Comment: It shows as green because each time it loops through it changes the color of all the nodes in `link`, and each time that color replaces the color from the previous iteration of the loop. Are you trying to style links sequentially? ie: First link is blue, second red, and third green?
Comment: yes, I try to do it sequentially, but don't know how?
Answer: To style each link a different style based on the index of that element/datum in the selection. As with many things in d3, this does not require a loop. You can access the index of each datum with code like:
selection.attr("property",function(d,i) {
  return array[i];
})

For sake of ease, I've used some circles and fill rather than links and stroke, but the method is identical. The snippet below will color links sequentially based on the colors array.

var svg = d3.select("body")
  .append("svg")
  .attr("width",500)
  .attr("height",300);

var data = [[50,50],[100,50],[200,50],[300,100]];
var colors = ["steelblue","orange","pink","red"]

// create some circles:
var circles = svg.selectAll("circle")
  .data(data)
  .enter()
  .append("circle")
  .attr("transform",function(d) { return "translate("+d+")"; })
  .attr("r",10)

// to style sequentially, you can use the datum's index:
circles.attr("fill",function(d,i) {
  return colors[i];
})

Comment: That line just positions the circles in one line of code (rather than with cx, cy), it is based on the data in the data array. If using the index, it is based not on the data, but on data order as done here: `circles.attr("fill",function(d,i) { return colors[i]; })` where `i` is the index of each element(circle in this case) in the selection.
Comment: Thanks Andrew. Which part of the code makes it possible? Is it `.attr("transform",function(d) { return "translate("+d+")"; })`?

Styling in D3 with a loop?


What is the fastest way to $\pi$?

Question: There are many known sequences convergent to $\pi$ with different convergence accelerations. For example both of the following sequences are convergent to $\pi$ when $n$ goes to $\infty$:
(a) $a_n=2^{n+1}\times\sqrt{2-\underbrace{\sqrt{2+\sqrt{2+\sqrt{2+\sqrt{...+\sqrt{2}}}}}}}$ which the under brace part repeats $n$ times. More clear:
$a_0=2\sqrt{2}$
$a_1=4\sqrt{2-\sqrt{2}}$
$a_2=8\sqrt{2-\sqrt{2+\sqrt{2}}}$
$a_3=16\sqrt{2-\sqrt{2+\sqrt{2+\sqrt{2+\sqrt{2}}}}}$
$...$
(b) $b_n=4\times\sum_{i=0}^{n}\frac{(-1)^i}{2i+1}$
More clear:
$b_0=4$
$b_1=4(1-\frac{1}{3})$
$b_2=4(1-\frac{1}{3}+\frac{1}{5})$
$b_3=4(1-\frac{1}{3}+\frac{1}{5}-\frac{1}{7})$
$...$
It seems the first sequence goes to $\pi$ faster than the second one.
Question: What is the fastest known explicit sequence convergent to $\pi$? Please introduce a list of known sequences convergent to $\pi$ and their convergence accelerations.
Comment: How about $\pi, \pi,\pi,...$? (Hmm, I'm hungry now.)
Comment: There is a huge literature. [This](http://en.wikipedia.org/wiki/Approximations_of_%CF%80) will give a start.
Comment: @copper.hat: Cool answer! :-)
Comment: Some good series that converge at an exponential rate can be found here: http://www.math.uiuc.edu/~berndt/articles/monthly567-587.pdf
Answer: The fastest (by steps/iterations) is Gauss - Legendre algorithm (see AGM method too) and its modifications.
$25$ iterations to get  $45$ million correct digits of $\pi$...
But this algorithm is very expansive in time, because each step uses square root calculating (very-very slow operation for huge number of digits).
Release A: (by Brent $-$ Salamin, modification) :
\begin{array}{llll}
a_0 = 1, & b_0 = \frac{1}{\sqrt{2}}, & u_0 = 0, & v_0 = 1;\\
a_{n+1} = \frac{a_n+b_n}{2}, &
b_{n+1} = \sqrt{a_n b_n}, &
u_{n+1} = \frac{u_n+v_n}{2}, &
v_{n+1} = \frac{a_nv_n+b_nu_n}{2b_{n+1}}
\end{array}
and
$$
\pi_n = 2\sqrt{2} \frac{a_n^3}{v_n}  \approx \pi.
$$
First steps:
\begin{array}{|l|l|l|r|}\hline
n & p_n & \pi-p_n & \log_{10}(\pi-p_n) \\
\hline0) & \color{gray}{2.828427...} & 3.13165... \times 10^{-1} &  -0.50422... \\
1) & \color{gray}{2.95807...} & 1.83515... \times 10^{-1} &  -0.73632... \\
2) & \underline{3.14}\color{gray}{066686...}  & 9.25783... \times 10^{-4} &  -3.03349... \\
3) & \underline{3.1415926}\color{gray}{465191...}  & 7.07059...\times 10^{-9} & -8.15054... \\
4) & \underline{3.141592653589793238}\color{gray}{28322...} & 1.79413... \times 10^{-19} & -18.74614... \\
5) & \small{\underline{3.1415926535897932384626433832795028841971}\color{gray}{15228...}} & 5.41713... \times 10^{-41} & -40.26623... \\
6) & ... & 2.39409...\times 10^{-84} & -83.62085...
\end{array}
Each iteration multiplies number of correct digits by $\approx 2$.
Release B: (by Brent $-$ Salamin):
\begin{array}{llll}
a_0 = 1, & b_0 = \frac{1}{\sqrt{2}}, & t_0 = \frac{1}{4};\\
a_{n+1} = \frac{a_n+b_n}{2}, &
b_{n+1} = \sqrt{a_n b_n}, &
t_{n+1} = t_n-2^n(a_n-a_{n+1})^2, &
\end{array}
and
$$
\pi_n = \frac{(a_n+b_n)^2}{4t_n} \approx \pi.
$$
First steps:
\begin{array}{|l|l|l|r|}\hline
n & p_n & \pi-p_n & \log_{10}(\pi-p_n) \\
\hline0) & \color{gray}{2.91421...} & 2.27379... \times 10^{-1} &  -0.64324... \\
1) & \underline{3.14}\color{gray}{05792...} & 1.01340... \times 10^{-3} &  -2.99421... \\
2) & \underline{3.1415926}\color{gray}{46213...}  & 7.37625... \times 10^{-9} &  -8.13216... \\
3) & \underline{3.141592653589793238}\color{gray}{27951...}  & 1.83130...\times 10^{-19} & -18.73723... \\
4) & \small{\underline{3.1415926535897932384626433832795028841971}\color{gray}{14678...}} & 5.47210... \times 10^{-41} & -40.26184... \\
5) & ... & 2.40612... \times 10^{-84} & -83.61868...
\end{array}
Each iteration multiplies number of correct digits by $\approx 2$.
Release C: (by Borwein brothers) : (see http://www.cecm.sfu.ca/~jborwein/Kanada_50b.html):
\begin{array}{ll}
y_0 = \sqrt{2}-1, & a_0 = 6-4\sqrt{2};\\
y_{n+1} = \frac{1-\sqrt[4]{1-y_n^4}}{1+\sqrt[4]{1-y_n^4}}, &
a_{n+1} = (1+y_{n+1})^4a_n - 2^{2n+3}(1+y_{n+1}+y_{n+1}^2), &
\end{array}
and
$$
\pi_n = \frac{1}{a_n} \approx \pi.
$$
First steps:
\begin{array}{|l|l|l|r|}
\hline
n & p_n & \pi-p_n & \log_{10}(\pi-p_n) \\
\hline
0) & \color{gray}{2.91421...} & 2.27379... \times 10^{-1} &  -0.64324... \\
1) & \underline{3.1415926}\color{gray}{46213...} & 7.37625... \times 10^{-9} &  -8.13216... \\
2) & \small{\underline{3.1415926535897932384626433832795028841971}\color{gray}{14678...}} & 5.47210... \times 10^{-41} & -40.26184... \\
3) & ... & 2.30858... \times 10^{-171} & -170.63665...
\end{array}
Each iteration multiplies number of correct digits by $\approx 4$ (in fact, it is interlined release B).

Collection of such algorithms: http://www.pi314.net/eng/algo.php.

But, in general, there are no "the fastest" sequence, because if the sequence $\{s_n\}$ converges very fast, then the sequence $\{t_n\}$, where $t_n= s_{2n}$ converges faster.
Answer: The provably fastest convergence, in fractions, is given by the continued fraction:
$$[3;7,15,1,292,1,1,1,2,1,3,1,\ldots]$$
This corresponds to the sequence $$3,\frac{22}{7}, \frac{333}{106}, \frac{355}{113}, \frac{103993}{33102},\ldots$$
Answer: One of the astounding formulae for $\pi$ is surely
https://crypto.stanford.edu/pbc/notes/pi/ramanujan.html

What is the fastest way to $\pi$?