Intuition behind the choice of the trace-function in character theory

Question: I have recently been studying representation theory of finite groups and hence also character theory, so I'm quite new in the field and maybe my question is a bit silly: On the first glance, the choice of the trace-function to define the character of a representation seems pretty arbitrary, so I was wondering whether there is a deeper reason for choosing the trace to define the character. Why did the inventors of character theory pick the trace function, and why did it work out so well?
I have heard of other representation theories, for example of Lie Algebras or Lie Groups (but I don't understand those yet unfortunately), so a (perhaps) related question would be whether we have a character theory for those representation theories as well, and if so what the common properties of those characters and the character of the representation theory of finite groups are...
Answer: Let's recall that, concretely, the data of an $n$-dimensional representation of a finite group $G$ is a collection $\rho(g)$ of $n \times n$ matrices, one for each element $g \in G$. Classifying such things up to isomorphism amounts to classifying collections of such matrices (satisfying the group relations) up to simultaneous conjugacy.
So, what invariants of square matrices up to conjugacy are there? We can consider eigenvalues, or equivalently we can consider the coefficients of the characteristic polynomial, which include the trace as well as the determinant. These are in fact the only conjugacy invariants of a square matrix which are well-behaved in various reasonable senses: for example, every polynomial conjugacy invariant of a square matrix is a polynomial in the coefficients of the characteristic polynomial. If we want to talk about simultaneous conjugacy things are more complicated; we can consider functions of the eigenvalues of various products, e.g. $\text{tr}(AB)$ is also an invariant of $A$ and $B$ up to simultaneous conjugacy, but since for a group representation a product of two of the matrices involved is another of the matrices involved this doesn't really buy us anything.
So it's at least reasonable to consider some function of the coefficients of the characteristic polynomial. Among these, the trace is distinguished by behaving particularly nicely with respect to both direct sums and tensor products: we have both
$$\chi_{V \oplus W}(g) = \chi_V(g) + \chi_W(g)$$
and
$$\chi_{V \otimes W}(g) = \chi_V(g) \chi_W(g).$$
So that's very nice: abstractly what this implies is that taking the character of a representation defines a ring homomorphism from the representation ring $R(G)$ of $G$ to the ring of class functions $G \to \mathbb{C}$, and standard results in representation theory of finite groups implies that this ring homomorphism is in fact an isomorphism, which is great.
From this perspective it may be a little surprising that the trace captures the isomorphism class of a representation since we only consider the sum of the eigenvalues and not e.g. their product, but as an exercise you can show that for a matrix $M$ over a field of characteristic zero, knowing the traces $\text{tr}(M^k)$ of all powers of $M$ is equivalent to knowing all coefficients of the characteristic polynomial of $M$; this is an exercise in symmetric function theory. So the character of a representation tells you, at the very least, the eigenvalues of every matrix $\rho(g)$.
The character theory of Lie groups also involves taking traces, while the character theory of Lie algebras is a bit more complicated but basically involves taking traces as well.
Answer: Schur's lemma tells that $\dim \text{Hom}(\rho,\pi)$ is 1 if $\rho,\pi$ are isomorphic irreducible representations, and 0 if $\rho,\pi$ are non-isomorphic irreducible representations. Thus $\dim \text{Hom}(\bullet,\bullet)$ behaves somewhat as an inner product on representations, where irreducible representations form an orthogonal basis. Writing out $\dim \text{Hom}(\rho,\pi)$ differently as in here: Is it true that $\langle \psi, \omega\rangle$ is the dimension of $Hom(V,W)$? makes characters pop out completely naturally. From this "orthogonality relation" (and the implicitly-used decomposition results, like representations over a characteristic 0 algebraically closed field decompose uniquely into a direct sum of irreducibles) one can get $\rho \simeq \pi \iff \chi_\rho = \chi_\pi$.
So at least in the "finite group representation theory over a nice field" story, traces show up and are so nice because traces are very related to dimensions of projections, and (from the decomposition theorem) dimensions of projections are very related to the uniquely determined numbers of copies of a given irreducible inside a given representation.


TO check response of particular id should be diff through jmeter

Question: MY response for api is:-
"data":{"shortId":"lu131559"}}

Now i wants to check short id is different for every virtual user.
mns if second hit gone response data is
lu131560

So i want to validate that after 1000 request from virtual user every time i am getting diff id.
Answer: If you know the "current" value of the shortId and expect it to be incremented by 1 each time you call your API you can go for Response Assertion and use __intSum() and __counter() functions combination in the pattern like:
lu${__intSum(131559,${__counter(,)},)}

Each time the Assertion will be called it will expect the value to be incremented by one, i.e.

lu131560 - for 1st user or iteration
lu131561 - for 2nd user or iteration
lu131562 - for 3rd user or iteration
etc.

More information: Apache JMeter Functions - An Introduction
Comment: HI Dmitri,
Actually i initially i dont know the shortid number. it may vary.any 6 digit number may come. all i need to check wether i am getting diff response in 1000 virtual user hit. I just paste the first response. may be next it may come lu427665.or any 6 digit. but i need to sure they are distinct for every hit


How can I modulate the distance of a tritone using 3 secondary dominant chords?

Question: So, I have been composing this "Requiem for String Quartet" on and off for a few weeks now. I call it a Requiem because of its dramatic arc through lamenting melancholy, painful harshness, solemn peace, and a majestic feel. And to reinforce the fact that it is a Requiem, I have been using the Gregorian chant "Dies Irae" as a melodic basis for quite a bit of the piece. I have however been treating it differently in different parts, some parts more contrapuntal and others more solo. Some parts, I wrote the melody as close as possible to the chant and others I took some liberties with, but kept the overall direction the same. And I'm at the point where the chant goes from the Tuba Mirum to the Rex Tremendae. I intend to treat the melody in yet another way here in the Rex Tremendae, having the strings in a rhythmic unison, giving a sort of chorale harmonization of the melody.
I'm currently in the key of Ab major and I'm wanting to modulate to D major. I figured, since I have 2 question phrases followed by an answer phrase, I could do 3 little tonicizations instead of 1 big modulation without tonicizations. So like I would go from Ab major to a second key, keeping things quieter and maybe having the last chord of the phrase, the dominant seventh be staccato. Then I would go from that second key to a third key, again quiet and possibly ending staccato. Then I would go from that third key to D major, with a confirmatory crescendo.
So basically, I would be after something like this harmonically:
Pre-Modulatory Phrase |    Phrase 1   |   Phrase 2   |       Phrase 3      | Post-Modulatory Phrase
Ab:I -> chords -> V7 -> I -> Sec. Dom.
                           1: V7   ->  I -> Sec. Dom.
                                             2: V7  ->  I -> chords -> V7/D
                                                                      D: V7 -> I -> chords

And I put numbers 1 and 2 for the keys that I don't know yet because I couldn't really use letters, or it would look like I decided on the keys when I haven't. Anyway, the distance that I have to modulate is the largest distance I could possibly modulate, the tritone axis. This makes things a bit tricky if I don't want to use the very quick diminished seventh modulation(which I'm not wanting to do here) or the Tritone Substitution(I think it will sound too abrupt to use Eb7 as a Tritone Substitution after all the material that has come before in F minor, C minor, and Ab major).
Is it even possible to string 3 dominant seventh resolutions across a tritone axis to get this smooth modulation via 3 tonicizations? If so, is there more than one possibility or is there just 1?
Comment: You might enjoy the very short book Modulation, by Max Reger.  It does many sneaky modulations to distant keys through the Neapolitan chord.
Comment: Btw, you associate D major with majesty for a good reason; in the Renaissance and early baroque, it was the key of trumpets and kettledrums, [whose use was restricted to](https://music.stackexchange.com/questions/117567/why-can-you-not-play-metal-in-major-keys/117576#117576) nobility and their militaries.
Comment: What is it that made you decide to go from Ab to D? When I write, the music dictates where it goes far more than me making decisions, otherwise it starts to sound contrived.
Comment: @Tim Well, I was wanting to do a majestic chorale harmonization after a solemn section with legato solo vs pizzicato in the other strings. And when I think majestic, I think D major. I think every Maestoso or almost every Maestoso I have ever played on the piano has been in D major, so I have a very strong association between D major and the feeling of majesty.
Comment: Yes, D is a traditional key for 'majesty'. But the reasons for that tradition no longer apply, and you don't need to be bound by them. I suggest you write the music you want to hear, rather than setting an artificial target of D major. And try to think melodically, not in terms of chord symbols.
Comment: I agree with Laurence. The _harmonic_ effect of modulating by a tritone will probably be stronger than any historic association of D with majesty.
Answer: We can go considerable modulatory distances by using secondary dominants of closely related what would be minor keys as secondary dominants of major keys instead.
One such example that gets you from A flat major to D major with 2 intermediate keys would be this:
A♭: I -> V7/iii = C: V7 -> I -> V7/vi = A: V7 -> I -> V7/IV = D: V7 -> I
As you can probably tell by the order of the use of V7/iii and V7/vi, this is obviously not the only such way, and you can pick another way if you like.
Answer: Consider that a commonly used key change, or probably modulation here, is up a semitone. That's easily achieved, and used often, as the pivot V of the new 'key' contains one of the old tonic notes - the tonic itself.
That would take us to key A major. That happens to be the V of the target key - D, so it's quite simple to move into that. Thus, two simple, easily listened to changes, and we're there - aren't we?
So - starting in A♭, V(7) of next key would be E(7), taking us into key A. Which could then go ii-V-I, meaning Em, A, D, into the target of D major. I think the two changes would work, instead of the requested three, but there are so many different ways to get from A♭ to D, in so many different stages, I felt this is what would work well.
And, of course, there's always the diminished chords which always ease any 'strange' modulations.
Comment: True, but the question asks for three changes, doesn't it?
Comment: An actual list of the chords suggested would make this a good answer.
Comment: @ToddWilcox - good idea. Is that what you mean? We're not sure how long each transition is, though. The longer the easier, I reckon.
Answer: We can re-write the question as how one makes x+y+z=6 mod 12 then reinterpret the numbers as scale steps. A quick answer is -2-2-2 or 2+2+2 moving the harmony by whole steps. Another is 1+2+3 (in some order) making moves of a minor second, a major second, and a minor third; this can be done as -1-2-3.
Other possibilities are +4+5-3 or 4-3+5, etc.
Comment: Mathematically this works, however, how it translates musically is what OP needs. As in dropping by a semitone doesn't usually sound good.
Comment: The 2+2+2 idea is the first one I had, but since this is Music.SE I was thinking of a chromatically ascending bassline with every other chord diminished. Add a musical strategy like that to this answer and I think it would become a pretty good answer.
Answer: There are many ways!
Quite stereotypical is using any tone as dim7/V to I46-V-I. With this we can go directly from Ab to G#dim7 (=vii°7 of A)  instead of A you take A46 - A7 - D. (Note that the V46 chord is the same as the 2nd inversion of the tonic.)
But with this trick you can try any other way like e.g.

Tonization of Ab: Ab-Fm-Ddim7-Eb46-Eb7-Ab

Modulation to F:  Ab-Bdim7-C46-C7-F

Modulation to D:  F-G#dim7-A46-A7-D

another proposition would be using ii7-V7 (iv-V/I as secondary chords:

Ab-Bbm-Eb7-Ab

Ab-Bbm-C7-F

F-Gm-A7-D

As we can see ii is reinterpreted as iv-V/ of the next tonic
Answer: As I mentioned in an earlier comment, check out Max Reger's book Modulation.  In it you'l learn that you can travel just about any distance by modulating through the Neaopolitan chord.  In your target key of D major, the Neapolitan chord is an E-flat major triad with G in the bass (first inversion).  This chord would likely be followed by either an A major chord by itself, or preceded by a D major chord in second inversion.  I'll leave it to you to decide how to get there, but E-flat is easily reached from A-flat major.  You could try something like this;
1st statement: Stay in A-flat
2nd statement: Use the modulation to D described above
3rd statement: Confirm the modulation with a strong cadence in D.
If you keep the main melody line as similar to itself as you can in all three statements the somewhat surprising modulation will be less jarring to the singers and audience.
Answer: In A♭ major you have possible borrowed chords ♭III C♭ major and ♭VI F♭ major. The parallel minor key, Ab minor, source of the borrowed chords, is a lot simpler to read as enharmonic G♯ minor where the two borrowed chords would become B major and E major.
The target key is D major. Descending fifths to that key would be B E A D.
So your point of departure could be through borrowed chords in A♭ major reinterpreted as a series of secondary dominants leading to D major.


Two xmlHttpRequests in a single page

Question: I'm fairly new to ajax but am trying to implement two simple calls to dynamically changes two separate divs on a page using javascript. I have no problems using one call at a time, but when I use two it seems like the second xmlhttprequest takes over the first and writes into both divs.
I've read and tried using the fixes listed on these two other posts both neither seem to work in my case:
Sending two Ajax requests to two different PHP scripts from single javascript function
Using two xmlhttprequest calls on a page
And here is my relevant code:
function request_handler(url, params, changed_div) {
    if(window.XMLHttpRequest) {
            try {
                    req = new XMLHttpRequest();
            }catch(e) {
                    req = false;
            }
    }else if(window.ActiveXObject) {
            try {
                    req = new ActiveXObject("Msxml2.XMLHTTP");
            }catch(e) {
                    try {
                            req = new ActiveXObject("Microsoft.XMLHTTP");
                    }catch(e){
                            req = false;
                    }
            }
    }

    if(req) {
              req.onreadystatechange = function(){
                    if (req.readyState == 4 && req.status == 200){
                                    document.getElementById(changed_div).innerHTML = req.responseText);

                    }
            }

            req.open("POST", url, true);
            req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            req.send(params)
            return true;
    }

    return false;
}

Here is the basic format of each request using the function above:
request_handler("sample.php", parameters , "sample_div");

Apologies if I'm passing something simple up here, I just can't seem to get it to work.
Answer: This question
Using two xmlhttprequest calls on a page
does answer your question.
In your request_handler function, you're using a global variable req that gets overwritten every time you call that function.
If you change it to start:
function request_handler(url, params, changed_div) {
    var req;
    // Rest of your function
}

you should find that it works. In this case req has a local scope and so is not overwritten when you call request_handler for the second time.
Can I also suggest that you strongly consider using the likes of jQuery, Prototype or Dojo, if you're planning on writing Ajax scripts? Writing scripts that work cross-browsers is hard to do well and these frameworks do a lot of the legwork for you.
Comment: changed_div is still local to function, then why is it getting overwritten?
Comment: maybe because of synchronous nature of ajax request and onreadystatechange  is getting called later, or something like that, still no idea...
Comment: I don't know the details of how `onreadystatechange` handlers are connected to the requests themselves, so I couldn't tell you. However, the rest of my answer still holds
Answer: Your req is a global variable as it is defined without the var keyword, keep that in mind.
What I think happens is that the second call overwrites the first one. This is because of the (default) asynchronous nature of the XMLHTTPRequest. Your first function call will end, but the fetching of the page is still going. The second function call then overwrites the previous request.
This however does not explain why both div get filled with the result of the second call. I must say I'm a bit lost on that one.
Comment: This is still correct, but I chose Dancrumb's response because it is a little more clear with the code and how to fix it.
Answer: This is a pretty common problem, especially if you don't want to take additional measures to block further calls until the first has finished loading. Its a bigger subject that I can cover in a post but there are several examples on the web of an "Ajax Queue" that effectively manages the order of requests received.
jQuery has a plugin for managing queues and I'm certain that most other JavaScript frameworks such as Prototype and MooTools will as well. If you're wanting to stick with raw JavaScript I would take a look at this web page:
http://www.cmarshall.net/MySoftware/ajax/index.html
He implements a queue very effectively and has an excellent example of its use.

Two xmlHttpRequests in a single page


msgraph powershell filtering variable

Question: i'm trying to get devices where the IMEI matches to the IMEI's in my list.
The variable $item does have a value, but this command doesn't show me any result
Get-IntuneManagedDevice -Filter "imei eq '$item'" | Get-MSGraphAllPages

if i'm checking instead of the variables with the actual value, it gives me a return
Get-IntuneManagedDevice -Filter "imei eq '123456789'" | Get-MSGraphAllPages

i'm importing the values from a csv file
Comment: Hi , could you please provide me the headers for csv file? after that we will help you with the correct query .
Answer: If the header is imei, you can try with
Get-IntuneManagedDevice -Filter "imei eq '$($item.imei)'" | Get-MSGraphAllPage
Hope this help , please let us know if you have any query
Thanks

msgraph powershell filtering variable


Parse text file to fill images in an array using Jquery

Question: I need to parse a text file after retrieving it from an Ajax call. I have the file but have no idea how to parse it.
Basically I want to parse the image files from the text file and push it into an array so that I can use these images for further processing.
Here is the text file
0310|14A0697JY|COMPACTOR|READY TO WORK|RAYGO RASCAL|420C|DETROIT DIESEL (GMC)|80%|READY      TO WORK|yQ8kE7BUEHY|SOLD|Raygo_Rascal.JPG|Raygo_Rascal..JPG|EXCELLENT COMPACTOR, ENCLOSED CAB, AND
PUSH BLADE EQUIPED, 84 INCH SMOOTH VIB.
DRUM. READY TO WORK!!!|NO|Compactor|ALL
0315|50G1042|RIPPER|USED|CATERPILLAR|FOR D9'S|SINGLE|SHRANK||NyopEXWbApQ|16,000|RIPPER.jpg|RIPPER....jpg|1 SHRANK CATERPILLAR RIPPER TO FIT CAT D9'S
DOZER, LIKE NEW CONDITION.|NO|Parts|ALL
0317|2LC677|FORK-LIFT|EXCELLENT COND.|CATERPILLAR|T50D|LP POWERED|SOLID||LTwA1Bw7c_4|11,000|cat_fork_lift..JPG|cat_forklift.JPG|EXCELLENT CAT FORK-LIFT LP(GAS) POWERED, 5,000 Lbs. READY TO WORK|NO|Miscelaneous|ALL
0335|RIPPER FOR CAT D8H-K.|RIPPER|USED|CRC-ATECO|CAT D8H-K|SINGLE|SHRANK||NyopEXWbApQ|9,000|ripper_d8_1.JPG|ripper_d8_2.JPG|SINGLE SHRANK RIPPER TO FIT CAT D8H OR K,
READY TO BE INSTALLED.|NO|Parts|ALL
0349|OVER|HYDRAULIC|TURN|TRACK|PRESS|YOUR|PINS & BUSHINGS||QHzQJ1EablM|AND RE-USED'EM|6a7c019bd33a9492b747fb05e9064563.jpg|402f99590af07da0b7c707f355ebc442.jpg|HYD. TRACK PRESS, TO TURN THOSE PINS &
BUSHINGS OF YOUR EXCAVATOR OR BULL-
DOZER, ANY BRAND, ANY SIZE.  LET US HELP,
GETTING YOU BACK IN TRACK, AT LOW COST!!|YES|Excavator|ALL
0361|NEGOCIO|BALNEARIO|MORELOS|WATER-PARK|CUERNAVACA|MEXICO|SUPER||C_u7vup5p4Q|CALL ME!!|logo.png|logo.png|EXCELLENTE LUGAR PARA INVERTIR,
NEGOCIO
LOS 365 DIAS DEL ANO. MUCHAS ALBERCAS,
TOBOGANES, ATRACCIONES Y DIVERCIONES.
PARA MAS INFORMACION, POR FAVOR VISITE:
www.parqueacuaticoojodeagua.com  SE
VENDE
Y/O PERMUTA. POR NO PODER ATENDER.
"BARATO"    GREAT PLACE TO INVEST,
INCOMING PROFIT, ALL YEAR AROUND. NEED
TO GO, CAN NOT MANAGE IT FROM U.S. |YES|Miscelaneous|ALL
0366|433B-481.|WHEEL-LOADER|EXCELLENT LOADER|MICHIGAN -CLARK|55B|CUMMINGS|80%|READY TO WORK|7glgUUCjtBI|18,000|2012-07-19_16-01-11_445.jpg|2012-07-19_16-02-13_560.jpg|MICHIGAN CLARK 55B. WHEEL LOADER. IN
EXCELLENT WORKING CONDITION. "NO" LEAKS
OF ANYKIND, ENCLOSED CAB, 80% TIRES ALL
AROUND, VERY POWERFULL AND READY TO
WORK!!!!|YES|Loader|ALL
0373|LOCATION: MEXICO, CITY.|GEN-SET|100 KiloWatts.|STAMFORD AC GENERATORS|NEWAGE LTD.||||NyopEXWbApQ|5,500|IMG_0122.JPG|IMG_0122.JPG|100 KILOWATTS, GENERATOR SET, ENCLOSED
AND SILENT GEN-SET. LOCATION: MEXICO,
CITY. READY TO WORK. E-MAIL FOR PICS!!!|NO|Miscelaneous|ALL
0377|GRUAS POR||AT THIS|NO|CRANES|TIME|NO||NyopEXWbApQ|EL MOMENTO|IMG_0122.JPG|IMG_0122.JPG|SORRY NO CRANES AT THIS MOMENT & LO
SENTIMOS NO TENEMOS GRUAS POR EL
MOMENTO!!|NO|Crane|ALL
0379|M100-1060|MOTOR-GRADER|1964|ALLIS-CHALMERS|ACM-100|127HP-AC-10000|60%|N/A|DG5gKp4iQ1Q|6,500.|2013-02-01_14-48-07_985.jpg|2013-02-01_14-50-32_338.jpg|OLDIE BUT GOODIE MOTOR-GRADER. ENCLOSED
CAB, DIRECT DRIVE. STILL A LOT A POWER TO
GIVE!!!|NO|MotoGrader|ALL
0383|N/A|ARMY TRUCK|N/A|N/A|N/A|INTERNATIONAL (GAS)|95%|N/A|NyopEXWbApQ|10,000.|KIMG0038.JPG|KIMG0040.JPG|ARMY TRUCK, IN GREAT STATE, READY TO
CLIMB HILLS, 4 WHEEL DRIVE, WINCH, NO RUST
AT ALL, MICHELIN TIRES, GASOLINE
INTERNATIONAL ENGINE.|NO|Trucks|ALL
0385|1FXBS1625J18800380|TRAILER|1988|CHAPARRAL|BUMPER PULL|EXCELLENT|90%|READY TO HAUL|NyopEXWbApQ|3,900.|KIMG0024.JPG|KIMG0026.JPG|1988 "CHAPARRAL" LIVE-STOCK, BUMPER PULL
TRAILER, IN GREAT SHAPE, NO RUST, BRAKES
AND LIGHTS WORKING, READY TO HIT THE
ROAD!!!!|NO|Miscelaneous|ALL
0386||DIESEL -MOTOR|2003|NISSAN|SD-22|4 CYL.|DIESEL|LOW|NyopEXWbApQ|1,500|KIMG0020.JPG|IMG_0099.JPG|2003 NISSAN 4 CYL. DIESEL ENGINE. IN GREAT
SHAPE, AND READY TO BE INSTALLED. WORKING
100%.|NO|Engines|ALL
0394||BULL-DOZER|2007|CATERPILLAR|D6N XL|CAT|75% U/C.|8,200 HRS.|2E5DYwgtJnY|SOLD|2007CATD6NXL2.jpg|2007CATD6NXL4.jpg|2007 CATERPILLAR D6N BULL-DOZER.
AWESOME LOOKING DOZER, YOU WONT FIND A
DOZER LIKE THIS UNDER 100 GRAND. 6 WAY
BLADE, CAB W/COLD A/C, 3 SHANK CAT RIPPER,
WILL BE HERE SOON.|NO|BullDozer|ALL
0395|FWV409702|DUMP-VOLTEO |1979|FRUEHAUF|28 Ft. T/A ALUMINUM|HYD.|60%|2 AXLE|NyopEXWbApQ|9,500.|KIMG0092.JPG|KIMG0096.JPG|1979 FRUEHAUF 28 FT. T/A ALUMINUM
QUARTER FRAME, END DUMP TRAILER. SPRING
SUSPENSION, 100% ALUMINUM BOX, CLEAN
TITLE IN HAND. WORKING
FINE WITH NO HYD. LEAKS AND READY TO HIT
THE ROAD!!!!!!|NO|Miscelaneous|ALL
0396|1V5BB182411133971|GOOSE-NECK TRAILER|2001|MAGNUM|18 Ft. X 6 Ft.|SPRING SUSP.|75%||NyopEXWbApQ|4,900.|64a78134-b508-49fe-b56f-7151a3ece00d.jpg|e45435a9-841d-4fb8-b45a-e43e74fd254f.jpg|2001 MAGNUM 18 Ft. X 6 Ft. 10 In. T/A
GOOSENECK EQUIPMENT TRAILER, WITH RAMPS,
SPRING SUSPENSION, CLEAN TEXAS TITLE IN
HAND AND READY TO WORK.|NO|Miscelaneous|ALL
0397|4P5GF2820Y1035499|GOOSENECK TRAILER|2000|PJ|3 AXLE|FLAT BED|90%||NyopEXWbApQ|5,900|2013-03-18_12-42-56_716.jpg|2013-03-18_12-43-32_232.jpg|2000 YEAR MODEL, PJ BRAND, 28 Ft. X 8 Ft . 5
In. FLAT BED, 3 AXLE, ELECTRIC BRAKES, WITH
RAMPS, SPRING SUSPENSION, CLEAN TEXAS
TITLE IN HAND.|NO|Miscelaneous|ALL
0399|0004T22507|BACK-HOE|2007|ALLMAND BROS|TLB-225|KUBOTA|70%||GukWO40hkh8|9,900.|KIMG0115.JPG|KIMG0114.JPG|2007 ALLMAND BROS BACK-HOE. WITH A 3 CYL.
KUBOTA ENGINE, READY TO WORK, NO LEAKS
OF ANY KIND, IN GREAT WORKING CONDITION. |YES|Backhoe|ALL
0400|26594-003|BROOM|2000|LAY-MOR|6HB|KUBOTA 4 CYL.|70%|1,199|b_oF-lxMfsA|7,500|photo_1.JPG|photo_2.JPG|LAY-MOR "BROOM" MODEL: 6HB. YEAR: 2000. 6'
BROOM, KUBOTA 4 CYL. DIESEL ENGINE, IN
GREAT SHAPE AND READY TO WORK.  |NO|Miscelaneous|ALL
0402|TODAS|RECONSTRUCCION|EXCAVADORAS|DE CADENAS|BULL-DOZER|CUALQUIER|TAMANO||2E5DYwgtJnY|LAS MARCAS|images-8.jpeg|images-12.jpeg|SOMOS LOS UNICOS EN EL VALLE EN OFRECERTE
LA PRENSA HIDRAULICA PARA VOLTEAR LOS
PERNOS Y LOS BUJES DE TU CADENA USADA, Y
ASI PUEDAS USAR EL OTRO 50% DE TUS
CADENAS, SIN TENER QUE COMPRAR CADENAS
NUEVAS. POR FAVOR LLAMANOS, SOMOS TU
MEJOR OPCION PARA AHORRAR MILES DE
DOLARES EN CADENAS NUEVAS.|YES|BullDozer|ALL
0403|41X02797|FORK-LIFT||CATERPILLAR|V80D|4 CYL. DIESEL|NEW|820|o62D5K1frOg|12,900|photo_1.JPG|photo_2.JPG|7,550 lbs. Max. Weight Capacity, 2 Stage Mast,
163" Max Lift Height, 108" Lowered Height, 71
1/4" Forks, Side Shift,     Fork Positioner, 4
Cylinder Engine, Diesel, Enclosed Cab. READY
TO WORK!!!!!|YES|Miscelaneous|ALL
0404|1S9M114141L358796|LED SIGNAL BOARD|2001|NATIONAL SIGNAL|VU POINTE|ELECTRIC & SOLAR|80%||NyopEXWbApQ|4,900|photo_4.JPG|photo_3.JPG|2001 NATIONAL SIGNAL, ELECTRIC OPERATED &
SOLAR OPERATED, SINGLE AXLE TRAILER, LED
BOARD SIGNAL, WITH HYD RAISE            BOARD.|YES|Miscelaneous|ALL

Any help is appreciable
Comment: Is your ajax call returning an actual file, or a string? You'll likely want loop through each line and then for each line you can use `.split("|")` to break out the columns into an array and request the object that you need using its index.
Answer: If you're not asking about ajax - I assume you already got the file contents in some variable... lets say it is named "csvData":
var rows = csvData.split('\n');         // rows now keeps an array of rows
var rowsData = {};                      // This will be your object where you will keep all data for further processing

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

  var cols = rows[i].split('|');      // Here you have array of cols for every row

  if (cols.length > 0) {
    rowsData[ cols[0] ] = cols;           // keep for further processing
  }

}

// now your images are easily accessible with:  imgFileName1 = rowsData["row id"][11];
// and: imgFileName2 = rowsData["row id"][12];   (these two columns contains image filenames so i wrote [11] and [12] but you can access other data also if needed)

example:
when you need the name of the 1st image from third row you will find it under
rowsData["0317"][11]

here is the working code example: http://jsfiddle.net/GbcmL/1/
Answer: You can try this, it will parse the file into an array based on the "|" then loop through all the items, if the item is a .jpg then it will add it to a new array.
var jpg = [];
for (var i = 0, len = fileStr.length;i < len;i++) {
    if (fileStr[i].indexOf(".jpg") != -1) {
        jpg.push(fileStr[i]);
    }
}
alert(jpg);

fiddle example here
Comment: You are deadly scary.
Answer: Well this is what exactly worked for me
 var jpgRegex = /\S*(\.jpg|\.gif|\.jpeg|\.png)/i;

            var results = [];
            var imageName = "";
            var arrayCounter = 0;

            parts = data.split("|");

            for (var i = 0; i < parts.length; i++) {
                imageName = parts[i].match(jpgRegex);

                    if (imageName !== null) {
                    results[arrayCounter] = imageName[0];
                    arrayCounter++;

                }
            }

Now have the images in the results array. Thanx for your help guys .


Erro ao tentar colocar JCheckBox em uma coluna da JTable

Question: Estou tentando acrescentar uma coluna em uma DefaultTableModel, mas parece está dando alguns problemas. Segue código!
JCheckBox jcheck;
DefaultTableModel modelo = new DefaultTableModel(null, new String[]{"Data", "Hora", "SAP", "BPCS", "Etiqueta", "Min", "Max", "MV", "Min", "Max", "T5", "Min", "Max", "TS2", "Min", "Max", "T90", "Min", "Max", "Densidade", "C-Chart", "Blooming","Aprovar"}) {
    @Override
    public boolean isCellEditable(int row, int col) {
        return true;
    }
};

jcheck = new JCheckBox();
TableColumn coluna_um = jTable1.getColumnModel().getColumn(22);
coluna_um.setCellEditor(new DefaultCellEditor(jcheck));

Alguém poderia da uma força?
Comment: Não é no tablemodel, ele serve para modelar dados, apenas isso. Para exibir combo na tabela, precisa criar um celleditor e um cellrenderer. Forneça um **[mcve]** do seu código para que possamos te ajudar.
Comment: Não vou manjar :(
Comment: Espera, no titulo você diz **ComboBox**, mas no código é **CheckBox**? Qual componente você está tentando adicionar afinal?
Comment: é check, estou ficando maluco já
Answer: JCheckBox é um componente que pode ser considerado "booleano", ou seja, ou está marcado, ou não está. Como ele tem apenas dois estados, quando você define uma coluna com este tipo no DefaultTableModel, o proprio renderer utiliza esse componente como representação de uma coluna booleana, e seu único trabalho é definir qual coluna deverá ser deste tipo. Veja no exemplo abaixo:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

public class JTableCheckboxTest extends JFrame{

    public void createAndShowGUI() {

        Object[][] rowData = {null, null, null};
        Object[] columnNames = { "Currency Column ", "Column Two",};

        DefaultTableModel model = new DefaultTableModel(rowData, columnNames){
            @Override
            public Class<?> getColumnClass(int columnIndex) {
                return columnIndex == 0 ? Boolean.class : super.getColumnClass(columnIndex);
            }
        };

        JTable table = new JTable(model);

        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane, BorderLayout.CENTER);
        setPreferredSize(new Dimension(300, 150));
        pack();
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }

    public static void main(String args[]) throws IllegalAccessException {
        EventQueue.invokeLater(() -> new JTableCheckboxTest().createAndShowGUI());
    }
}

Repare que no método getColumnClass() eu faço uma verificação para saber se o índice da coluna é 0, quando for, a coluna será do tipo booleana, o que fará dela uma coluna de Checkboxes:

Um ponto do seu código que vale ressaltar é que, por padrão, todas as colunas de um DefaultTableModel são editáveis, logo, sobrescrever o método isCellEditable() para retornar true é redundante.
Comment: Nossa @Articuno, perfeito cara..
Comment: @Lucas16 é mais simples do que parece ne :p
Comment: Muito haha.. agora quero só ver como vou fazer para percorrer essas colunas e salvar aprovado para quando estiver marcado :S
Comment: Faça um laço percorrendo todas as linhas, mas restringindo apenas a coluna booleana no `getValueAt`, assim você recupera o valor dessa coluna.
Comment: vc comentou sobre o iscelleditable, mas e se eu quiser deixar apenas a coluna 22 pra ser editada?
Comment: @Lucas16 supondo que 22 seja o indice correto da coluna: `return col == 22;`
Comment: Manja demais :D
Comment: eu fiz um laço, mas estou com várias duvidas.. será q vc n poderia me ajudar em algum chat, alguma coisa?
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/68697/discussion-between-articuno-and-lucas16).
Comment: você teria um exemplo pra combobox na jtable agora? vc me explicou no checkbox e deu certo, mas preciso de um comobbox na jtable agora.
Comment: @Lucas16 https://stackoverflow.com/q/3256086/5524514


create binary search function to find the position to insert the element

Question: Task: write a function binary_search that has O(log n) time complexity to find the position to insert the element such that:
binary_search(42, (-5, 1, 3, 5, 7, 10))

gives 6.
Please help me with this question. How do i approach it?
Comment: ... Who wrote `search()`?
Comment: 1. Discard `search()`. 2. Write `binary_search()`.
Comment: Avoid slicing such as `seq[:1]`. That can turn something that looks O(log n) into O(n)
Answer: Here is something that might help:
This solution has a O(log(n)) runtime.  Similar to Binary Search
Binary Search Wiki
def rec(nums, target, lower, upper):
    if (lower > upper):
        return lower
    mid = int((upper + lower) / 2)
    if (nums[mid] > target):
        return rec(nums,target,lower,mid-1);
    elif (nums[mid] < target):
        return rec(nums,target,mid+1,upper);
    else:
        return mid
class Solution:
    def searchInsert(self, nums, target):
    """
    :type nums: List[int]
    :type target: int
    :rtype: int
    """
    return(rec(nums, target, 0,len(nums)-1));

Answer: This is a variant problem of binary search, it is the same as looking for the largest element in the sequence that is smaller than k(the element to be inserted) or the smallest element that is greater than k.
def binary_search_insert(target, seq):
    U = len(seq) - 1
    L = 0
    result = 0
    if target <= seq[0]:
        result = 0
    elif target >= seq[len(seq) - 1]:
        result = len(seq)
    else:
        while L <= U:
            M = (L + U)/2
            if seq[M] <= target:
                L = M + 1
            else:
                result = M
                U = M -1
    return result

#test case
In [34]: seq
Out[34]: [1, 2, 3, 4]

In [35]: k = 2

In [36]: binary_search_insert(k, seq)
Out[36]: 2

In [37]: k = 2.5

In [38]: binary_search_insert(k, seq)
Out[38]: 2

In [39]: k = 3.5

In [40]: binary_search_insert(k, seq)
Out[40]: 3


Invoke a camera to start in Drupal 7 Forms API

Question: I am currently developing a module which must be capable of taking a picture. I dont know how will I make it? How will I invoke a camera to open just by clicking a button? Any idea?
Answer: Have you tried the webcams module ? Even if it's dev I'd say it's worth trying.
Do a search on webcam on Drupal and try out some of the modules listed.
Else if you want to develop your own module then the best way is probably doing the integration of an existing webcam jquery module. (See some jquery plugin examples here)
Comment: For webcams you have a dev version for D 7. Do try it and see how it goes.
Comment: Else the Kaltura module has a D 7 release and is actively maintained. Also the Webcam field module has a dev D 7 version. - I'd try them three (webcams, kaltura, webcam field), just to beging with.
Comment: If you are planning on developing your own module I would recommend to watch this basic tutorial on how to created a basic webcam that takes pictures using HTML5 and JavaScript. http://www.tinkernut.com/2013/03/19/html5-photo-booth/


Programmatically remove exposed filter in a view

Question: I would like to remove a certain exposed filter on the taxonomy term view when certain conditions in the URL are met.
For example, I want to remove the "Color" exposed filter when the user is seeing the /color/red taxonomy term page, leaving only the "Shape" filter available.
Or remove the "Shape" exposed filter on the /shape/square page, leaving only the "Color" one.
The only code I could come up with is this, which is ugly and doesn't even work.
function hook_views_pre_render(&$view){
      if( CONDITIONS_ARE_MET ) {
         unset($view->filter['field_color_tid']);
         unset($view->exposed_data['field_color_tid']);
         unset($view->exposed_raw_input['field_color_tid']);
      }
}

Any ideas?

UPDATE
This is the code in mmo_views_alters:
function mmo_views_alters_views_pre_build(&$view){
    //dpm($view);
    unset($view->filter['field_tipologia_tid']);
}

This is the exported view: http://pastebin.com/JrYDmtZQ
It has 4 filters, and 3 of them are exposed.
I'm using BEF for displaying them, which generated another warning (undefined index filter-field_tipologia_tid) that I solved by patching better_exposed_filters_exposed_form_plugin.inc, line 896:
if( isset($form['#info']["filter-$label"]['value']) )
        $field_id = $form['#info']["filter-$label"]['value'];
else continue;

The warnings that I'm not able to solve are:

Notice: Undefined index: field_tipologia_tid in
  views_handler_filter_term_node_tid->exposed_validate() (linea 258 di
  /var/www/drupal/sites/all/modules/views/modules/taxonomy/views_handler_filter_term_node_tid.inc).
Notice: Undefined index: field_tipologia_tid in
  views_handler_filter_term_node_tid->exposed_validate() (linea 259 di
  /var/www/drupal/sites/all/modules/views/modules/taxonomy/views_handler_filter_term_node_tid.inc).

They appear even with BEF disabled.
Answer: Implement hook_views_pre_build() and unset using unset($view->filter['field_color_tid']);
Else, you can also try altering the exposed form in hook_form_alter() using the code $form['field_tipologia_tid']['#access']=FALSE;
Comment: thanks, that works, although I get 2 similar warnings:

Notice: Undefined index: field_tipologia_tid in views_handler_filter_term_node_tid->exposed_validate()

Notice: Undefined index: field_tipologia_tid in views_handler_filter_term_node_tid->exposed_validate() (line 259 in /var/www/drupal/sites/all/modules/views/modules/taxonomy/views_handler_filter_term_node_tid.inc)
Comment: can you share the code written in `hook_views_pre_build()` and how many filters you have and how many you are exposing .
Comment: sure, I've edited the original post.
Comment: @Sifro I have updated the answer, try it


A Sequence converges or diverges

Question: I wanted to also ask about this one
the sum of (1 +sin^2(n))/n from n =1 to n=00. I tried the divergence test and got infinity. But the graph of the functions shows it converges to zero. Any suggestions?
Does the sequence $\left\{\frac{1}{n}\right\}_{n=1}^\infty$ converge or diverge?
The same question for the sequence $\left\{\arctan(n)\right\}_{n=1}^\infty$. I know how to prove it diverges when it is a series. I used the divergence test. But when it is a sequence, how do I deal with it?
Comment: To prove a sequence converges, a common technique is to prove it's either bounded below and decreasing, or bounded above and increasing.
Comment: A sequence $(x_n)$ converges to $a\in\mathbb{R}$ if $\forall\epsilon>0,\exists N\in\mathbb{N}\ \text{such that} \forall n>N,|x_n-a|<\epsilon.$ Use this to prove the convergence.
Answer: The sequence with terms $1/n$ converges with limit 0. This is not hard to show. Use the definition of limit as suggested by @Janitha357. The sequence with terms $1+\sin^2(n)$ is bounded between 1 and 2 (Why?). So, the sequence you are interested in lies term-by-term between $\{1/n\}$ and $\{2/n\}$. As each of these sequences has limit 0, "the Squeeze Theorem" yields the result.
As for your second question, keep in mind that $\arctan(n)$ is the angle strictly between $-\pi /2$ and $\pi /2$ whose tangent is $n.$ If the tangent of an angle is getting very positive, which angle is that angle approaching. The answer is obvious if you look at a table of values for the tangent (an advantage those of us of a certain generation have over the "calculator generation").
Comment: Thank you for your solutions. However, please note that the 1 + sin^2 (n) /n is not a sequence. But it is a series. So, the Squeeze Theorem won't work here. Right?
Comment: @BigBoy - In your question, you specifically asked what to do with $(1+ \sin ^2(n))/n$ as a sequence
Comment: I stated that he sum of (1 +sin^2(n))/n from n =1 to n=00 and so it is a series not a sequence. Note the word SUM.
Comment: @BigBoy - Sorry. I was still concentrating on the $\arctan$ question. The series diverges by comparison with $\sum 1/n.$ You cannot use the divergence test because the terms of the series go to 0. I assume when you sum from $n=1$ to $n=00$ you mean $n=0$ to $n=\infty$?
Comment: I do not think that the comparison test will work though. Since the sum of (1+ sin^2(n))/n is less than or equal to 2/n and 2/n diverges, we can't draw any conclusion about the one we are looking for. So the C.T. is inconclusive. So, the question is still open. I tried the limit comparison test with no luck and the Integral test is not easy and probably not applicable..
Comment: Yes, but it is at least as large, term-by-term, as $\sum 1/n$ which diverges.
Answer: Terminology: The sequence $\{1/n\}_n=(1,1/2,1/3,...)$ converges to $0.$ The series $\sum_n1/n$ diverges. That is, the sequence $(s_n)_n ,$ where $s_n=\sum_{j=1}^n1/j,$ does not converge. $$1+1/2+(1/3+1/4)+(1/5+1/6+1/7+1/8)+...>$$ $$>1+1/2+(1/4+1/4)+(1/8+1/8+1/8+1/8)+...=1+1/2+1/2+1/2+...\to\infty.$$

A Sequence converges or diverges


Executable Started From Named Pipe?

Question: Can someone please tell me how this was done? Take a look at the "Command Line" for SmcGui.exe. You will notice that it's a Named Pipe string... The full string is:
\\.\pipe\SygateSecurityAgentR41T67564 \\.\pipe\SygateSecurityAgentW18467T67564

Comment: Looks like they are just command line arguments; same as vcpkgsrv.exe.  Whoever is launching the process is not following the convention of including the process name as the first argument of the command line (e.g. via CreateProcess).
Comment: If the process name was not the first argument, then how could the application have started?
Comment: It is a fluke of CreateProcess(), two ways to specify the .exe name.
Answer: From the MSDN docs on [CreateProcess][1]
BOOL WINAPI CreateProcess(
  __in_opt     LPCTSTR lpApplicationName,
  __inout_opt  LPTSTR lpCommandLine,
  __in_opt     LPSECURITY_ATTRIBUTES lpProcessAttributes,
  __in_opt     LPSECURITY_ATTRIBUTES lpThreadAttributes,
  __in         BOOL bInheritHandles,
  __in         DWORD dwCreationFlags,
  __in_opt     LPVOID lpEnvironment,
  __in_opt     LPCTSTR lpCurrentDirectory,
  __in         LPSTARTUPINFO lpStartupInfo,
  __out        LPPROCESS_INFORMATION lpProcessInformation
);

lpApplicationName [in, optional]
The name of the module to be
  executed. This module can be a Windows-based application. It can be
  some other type of module (for example, MS-DOS or OS/2) if the
  appropriate subsystem is available on the local computer.
The string
  can specify the full path and file name of the module to execute or it
  can specify a partial name. In the case of a partial name, the
  function uses the current drive and current directory to complete the
  specification. The function will not use the search path. This
  parameter must include the file name extension; no default extension
  is assumed.
The lpApplicationName parameter can be NULL. In that case,
  the module name must be the first white space–delimited token in the
  lpCommandLine string.
Comment: After testing a call to CreateProcess specifying the `ApplicationName` attribute, I was able to replicate that. Apparently the "Command Line" property in the process viewer does not behave the way I understood it to.

Executable Started From Named Pipe?


How to do a Growl or Gargle-like sound

Question: I've been trying to learn how to do a growl. I trued to use keyword searches in google but I never could construct my question well so I'd like to use examples instead.  Most answers and questions relate to Heavy Metal singing and whatnot but I don't think I'd like to head that way.
Here are some example voices that I am referring this type of growl to:
Various versions of Master of the House from Les Miserables. At least listen to the first 1:30 mins of each:

TJ Miller's Fred from Big Hero 6 (Skip to 0:45 where he says "Rocket Ship")

and lastly, Tom Kenny's Ice King from Adventure time

Anyway,
How do you learn how to do this? Are there some exercises and techniques I should know? What should I avoid when doing this that is vocally-damaging? An insightful answer is very much appreciated cause I'm not really that much literate when it comes to technical terms in music. I'm also aware I can't compare my voice to 30+ year old people's voice which I'm tryna imitate but I hope you can help get me a 20 year old version of that..
Thank you very much. :)
Comment: Isn't this some variation of "vocal fry"? That might help for searching.
Comment: @ToddWilcox It was the Zen of Screaming by Melissa Cross.
Comment: As always, take lessons.  If you try to do it yourself, you'll almost certainly destroy your vocal cords -- and they're difficult to repair.
Comment: There was a DVD around several years ago that was considered the ultimate guide to getting these kinds of sounds without hurting your voice. I believe it was a series of lessons taught by a woman, but I have no idea what it was called. There **is** a technique and way to do this that is safe for your voice.
Answer: From the examples you've given, it sounds like you're not necessarily looking to scream, just add a raspy tone, correct?

Starting out with soft, but persistent, practice is key here; short of taking up smoking or recording with a chest-cold. (haha). You're learning to push your diaphragm and vocal chords. You're stretching your vocal chords in the same manner as when you clear your throat but, pushing more air through them than usual with your diaphragm.
It's fun and easy to practice this in a recording environment... Turn your vocals way down and everything else way up. You'll naturally be singing with more gusto just to be able to hear yourself in the mix. Once the recording's done, mix the levels to your preference and listen. You may be surprised at the tones you produce!
It is true that professional lessons are a good idea, as well as the fact that not all voices can emulate the same tones, or reach the same frequencies, as others.

How to do a Growl or Gargle-like sound


Click to show CSS tooltip

Question: I am new to working with CSS and HTML I have been trying to create a tool tip using CSS and HTML so Far has been successful. But now want to know if possible how to make this tooltip only Appear when clicked on. And disappear when clicked again.
Below is the HTML code i have used.
If someone could suggest some CSS that enables me to create the desired outcome that would be brilliant
HTML
class='tooltips' style ='color:#585858; text             decoration:none;'> desktop NG     information
Thanks in advance
Comment: OP, please edit your question with the full code
Comment: read this article http://tympanus.net/codrops/2012/12/17/css-click-events/
Comment: So what do you have to click on so it appears? You can't click on the tooltip if it isn't already there. I think that you have to use javascript for that.
Comment: i think this link might help you http://jsfiddle.net/GQE4k/1/
Comment: .fadeToggle(); would have been much more smart since you already use jQuery
Comment: Going off of @Rohit Batham's answer (can't add as a comment since my rep is too low), if you want to have it as a persistent tooltip when you click, use the `focus` selector instead of active.
Answer: To toggle a tooltip you can use the :checked pseudo class of a checkbox.

.tooltip {
  position: relative;
  border-bottom: 1px dotted black;
}
.tooltip span {
  visibility: hidden;
  width: 10em;
  background-color: #000;
  color: #fff;
  text-align: center;
  border-radius: 6px;
  padding: 5px 0;
  position: absolute;
  z-index: 9;
  top: -1em;
  left:  100%;
  margin-left:1em;
  opacity: 0;
  transition: opacity 1s;
}
.tooltip span::after {
  content: "";
  position: absolute;
  top: 1.5em;
  right: 100%;
  margin-top: -5px;
  border-width: 5px;
  border-style: solid;
  border-color: transparent black transparent transparent;
}
.tooltip input {
  display:none;
}
.tooltip input:checked+span {
  visibility: visible;
  opacity: 1;
}

Hello world<input type="checkbox">and this is the tooltip text displayed on click.! I am greeting you.

Answer: HTML Code
Link

CSS Code
.tooltip{display:inline;position:relative}
.tooltip:hover{text-decoration:none}

.tooltip:hover:after{
   background:#111;
   background:rgba(0,0,0,.8);
   border-radius:5px;
   bottom:18px;
   color:#fff;
   content:attr(title);
   display:block;
   left:50%;
   padding:5px 15px;
   position:absolute;
   white-space:nowrap;
   z-index:98
  }
.tooltip:hover:before{
    border:solid;
    border-color:#111 transparent;
    border-width:6px 6px 0 6px;
    bottom:12px;
    content:"";
    display:block;
    left:75%;
    position:absolute;
    z-index:99
   }

Try this will work properly and onlcik event doesn't support in css.
Comment: _"onlcik event doesn't support in css."_ I think you forgot `:active` pseudo class ;)
Comment: @Bluedayz I tried your fiddle, but tooltip only appears when you click on the link and then dissapears automatically.. how can be fixed that?
Comment: If you want to use active: http://jsfiddle.net/Z7GM6/1/
You have to hold your mouse button on that hyperlink
Comment: I tried it via  jsfiddle.net/Z7GM6, but the title also appears after a second.  I switched the attribute to be "tip" and content to "attr(tip)", is there a better option?

Click to show CSS tooltip


Analyzing Ryuichi Sakamoto "Merry Christmas, Mr. Laurence"

Question:

The original song is not in C Maj key
but the sheet I Have is in C Maj so let just see as the key is in C maj

(The [B] part starts 1:50)
How does the Gm (Vm) come about?
Is it a modal interchange chord Vm (sub dominant) from the Mixolydian scale?
And if I'm right about Gm being a modal interchange chord from Mixolydian, how does this connect to Dm?
Comment: Btw, this is clearly inspired by Debussy's "Claire de Lune", so analysis of that may help you to figure out what Sakamoto is doing, and why.
Comment: @YourUncleBob which part of "Claire de Lune" should I look ?
Comment: It seems to be built around the underlying theme of Clair de Lune. E.g. in this recording: https://www.youtube.com/watch?v=4fvo_iOuSck it's most recognisable between 0:26 and 0:44, but the theme crops up in various guises throughout the piece.
Answer: Your intuition about the Gm is absolutely correct: it's just a result of mode mixture, also called modal interchange.
Before this Gm9, we have FM7–G7–Am7, which is really a IV7–V7–vi7 progression in C major. The Gm9 is then just a chord borrowed from C Mixolydian; instead of a V9 chord, we now have a v9 chord. I think borrowing from Mixolydian is better than borrowing from the parallel minor of C minor. If we were borrowing from C minor, we'd likely have an A♭ as well, which we don't.
At this point, the Gm9 moving to Dm is simply a v–ii progression in C. (You could also think of these as being brief i–v motions in Gm, but I don't hear G as tonic here). There's no chromaticism or fancy chord motion, it's just a minor dominant moving to the supertonic (ii) chord.
Comment: what do you mean by "the music being more centered in Gm or Dm"? are you talking about key change ?
Comment: @HyunYooPark Yes, I'm talking about a key change. I mean that it's unclear to me whether G is tonic there or if D is. If I had to guess, I would say D is tonic, and thus my reading would align with (2) above.
Comment: But what made you think the key has changed ? how could you define that ? I mean , from IVM7 V7 vi7 and all of sudden key change to dm ? doesn't it have to have more certain connection to make it happen ?
Comment: @HyunYooPark Only because I no longer hear C as tonic, although I do hear C as tonic in the FM7–G7–Am7 progression. Key changes can happen in all sorts of ways, but in short, if you feel like tonic is a different pitch than it was previously, then it's a key change.
Comment: @HyunYooPark But now, listening to the piece with better speakers, I hear that section in C (that is, neither Gm or Dm). I'll edit accordingly!
Comment: So if saying the [B] part is in C Maj key, how could you explain that chord progression ? Vm to ii ?
Comment: @HyunYooPark Yep! See my prior edit.
Comment: but how could I see this as a brief "i-v" if Gm i's actually v in this section ? and what do you mean by "it's just a minor dominant moving to the supertonic (ii) chord" ? didn''t you agree with me that the "v" is sub dominant "v" from Mixolydian scale ? then how could I see this as a dominant ? and also isn't ii also a sub dominant chord ?
Comment: Actually for me this song is in A minor! "VIb VIIb i" is all I see.
Comment: @HyunYooPark I'm saying that, if one hears Gm as a temporary tonic, then Gm temporarily becomes i, and therefore the Gm–Dm is i–v. As for "subdominant," are you using that term to mean "substitute dominant" or "the IV chord"?
Comment: @coconochao All you see, or hear? :-)
Comment: @Richard Ok I see..so is about my perspective I guess ?? and about the subdominant, I mean the IV and ii Chords function not the substitute dominant
Comment: @HyunYooPark In that case, I don't understand your question "and what do you mean by "it's just a minor dominant moving to the supertonic (ii) chord" ? didn''t you agree with me that the "v" is sub dominant "v" from Mixolydian scale ? then how could I see this as a dominant ?"
Comment: @Richard in my main text, I said I analyzed the v as a "Sub dominant" chord from mixolydian, and you said on your answer that my intuition about the Gm is absolutely correct. So that means you agreed with me that the v is functioning as a sub dominant. but on your answer at the last part your saying it's a  "minor dominant" moving in to the supertonic ii chord. so that confuses me
Answer: everyone. I am from the country where Sakamoto was born. I suppose that Gm9->Dm9 should be interpreted as IIm->VIm in F Major, not in C Maj! Besides, Gm9->Bm7->E7 should be as IIm(in F Maj)->IIm(in A Minor)->V7(in A Minor) Hope this helps.


OOV (Out Of Vocabulary) word embeddings for Fasttex in low RAM environments

Question: Is there a way to obtain the vectors for OOV (Out Of Vocabulary) words using fasttext but without loading all the embeddings into memory?
I normally work in low RAM environments (<10GB of RAM) so loading a 7GB model into memory is just impossible. To use word embeddings without using that much RAM one can read a .vec (which is normally a plain-text) file line by line and store it into a database (which you later access to request a word vector). However to obtain OOV vectors with fasttext you need to use the .bin files and load then into memory. Is there a way you can avoid loading the whole .bin file?
Comment: A difficult question. Some hints might be here. https://www.quora.com/How-does-fastText-output-a-vector-for-a-word-that-is-not-in-the-pre-trained-model
Comment: Not necessarily. The word vectors are created by adding the vectors for the ngrams. So what you see in the vec file is the final vectors, not the individual ngrams. In case you have the ngrams as well then you are in luck.
Comment: Thanks for the link! From the description there I think it's still possible to do it, however I guess a custom implementation must be made (as I've failed to find one that does this). Also, performance will certainly suffer :(
Comment: Then the question should be: Is there a way to extract all ngrams from the `.bin` file?
Answer: What did work for me was to set up a huge swap partition to allow the model to load, then I reduced the size of the vectors from 300 to 100 to make the model fully fit in memory.


Desenvolvimento ágil e atualização da documentação

Question: Levando em consideração a segunda premissa do manifesto ágil:
"Software em funcionamento mais que documentação abrangente"
Conforme as práticas ágeis, scrum, XP, etc..., se durante o desenvolvimento, após termos feito o desenho UML das classes, verificarmos a necessidade de criar um atributo novo para uma das classes devemos programar o atributo em nossa classe e banco de dados após e atualizamos a UML? Ou deixamos o desenho UML para traz e seguimos planejando as iterações?
Lembrando que metodologias ágeis não descartam documentação, mas gostaria de saber até qual ponto trabalhamos em conjunto com ela.
Answer: A questão é...

Quando sua equipe faz reunião ou você discute alguma funcionalidade com um colega desenvolvedor, você usa os diagramas?

Em caso afirmativo, então o uso deve ser cotidiano, portanto é recompensador o trabalho de manter a documentação atualizada.
Em caso negativo, provavelmente os diagramas foram feitos apenas para um entendimento inicial ou para cumprir uma expectativa do cliente ou da gerência, logo não vale a pena, pois o trabalho é mais que o benefício colhido.
Considerações
Se o arquivo-fonte dos diagramas é versionado junto com o código-fonte, então é fácil que qualquer membro da equipe atualize o diagrama e sincronize o projeto com o SCM.
Por outro lado, se a equipe costuma trabalhar com documentos impressos, simplesmente risque o documento a lápis e será suficiente para usar nos próximos sprints (desde, é claro, que ninguém brinque de basquete com os papéis e um cesto de lixo).
Diagramas UML não precisam ser um reflexo 100% preciso do código. Em muitos casos, evito colocar atributos em classes para não comprometer a estrutura interna.
Mas o que ocorre frequentemente é usar a UML para representar o modelo de banco de dados do sistema. Não concordo muito com isso. Existem ferramentas mais adequadas que permitem fazer um MER (Modelo Entidade-Relacionamento) e já sincronizar o diagrama com o banco de dados.
Answer: O meio mais fácil (e barato) seria fazer as alterções nas classes (software em funcionamento primeiro) e depois fazer a engenharia reversa dela para gerar diagramas de classes e afins. Há várias ferramentas no mercado que fazem isso pra você.
Acho que cabe aqui apontar algo para reflexão que já foi descrito em vários artigos, que UML não é documentação.
Comment: O que estou dizendo é que as fontes que o artigo linkado cita não comprovam a ideia passada, nem o autor fornece uma definição apropriada de *documentação*. Aliás, a definição padrão da documentação segundo os principais autores de Engenharia de Software envolve justamente a *comunicação*, então ou o autor quis ser um tanto polêmico, ou ele usou uma definição alternativa de documentação.
Comment: Apesar do título do artigo citado (não tenho o artigo completo), nenhuma das fontes (Fowler, Ambler) sugere que UML não seja documentação. Pelo contrário: *Again the UML is useful here, providing the diagrams are selective to help communication.*
Comment: Sem dúvidas ela ajuda a comunicar, mas isso não implica em ser documentação. Isso está descrito no artigo linkado.
Answer: No conceito de desenvolvimento "ágil" a documentação é um mero coadjuvante no processo (user story é um ótimo exemplo).
Se você está no "ágil" a ideia é que a documentação seja colaborativa, ou seja, ela vai crescendo de acordo com a necessidade e com a colaboração de todos após interações da equipe (daily scrum ou sprint planing por exemplo).
O importante é entregar valor ao cliente. Se a documentação é um artefato a ser entregue também, fatalmente você terá que atualiza-la, mas não necessariamente no exato momento em que foi identificada uma alteração.
Se a mudança impactará nas próximas sprints, então é interessante que você faça a atualização na documentação.
Agora, se a documentação não é um artefato entregável e se as mudanças não impactarem no que ainda será desenvolvido, sugiro toma-la apenas como lição aprendida.
Lembre-se que o foco na metodologia ágil é entregar valor ao cliente. Por isso eles não abordam documentação, apesar de que a documentação pode sim ser um entregável que gere valor.
Faça seu próprio julgamento.


How to populate value 'qty' key of one array based on the 'id' key of another array in PHP?

Question: I have two variables. $inventoryOfCategory and $myInv. The two arrays are like the following:-
$inventoryOfCategory = array(
                           [0] => array(
                                      'id' => 1,
                                      'title' => 'Book'
                                  ),
                           [1] => array(
                                      'id' => 1,
                                      'title' => 'Copy'
                                  ),
                           [2] => array(
                                      'id' => 1,
                                      'title' => 'Pen'
                                  ),
                       );

$myInv = array(
                  [0] => array(
                            'id'  => 1,
                            'qty' => 10
                         ),
                  [1] => array(
                            'id'  => 3,
                            'qty' => 20
                         )
         );

The id on each row is unique. Now, I want to load the data of $inventoryOfCategory in a table. On each row, there will be a checkbox, the name of the inventoryOfCategory and a textbox. When the id of each $inventoryOfCategory in each row will match with an id of $myInv, the checkbox will be checked and the textbox will contain the qty of the $myInv corresponding to the id. Here is my following code:-
<?php
if(isset($inventoryOfCategory) && !empty($inventoryOfCategory))
{
    foreach($inventoryOfCategory as $inventory)
    {
    ?>

    <input type="checkbox" name="inventory[]" value="<?php echo $inventory['id'];?>" <?php if(array_filter($myInv, function($item) use($inventory) {return $item["id"] === $inventory['id']; })) echo "checked";?>/>
    <?php echo $inventory['title'];?>
    <input type="textbox" name="inventory_qty[]" class="form-control" style="width: 120px;" value="<?php if(array_filter($myInv, function($item) use($inventory) {if($item["id"] == $inventory['id']) echo $item["qty"]; }));?>"/>

    <?php
    }
}
?>

The data are saved accurately, and hence the checkboxes are checked accurately. The problem is with the qty value that are populated in the textbox.
How can I fix this?
Answer: Try this.
 <?php

    if(isset($inventoryOfCategory) && !empty($inventoryOfCategory))
    {   $i=0;
        foreach($inventoryOfCategory as $inventory)
        {
         $qty= $myInv[$i]['qty'];
         $id= $inventory['id'];
         $title= $inventory['title'];

         //HERE you can put your existing TR and use above values

        $i=$i+1;
        }
    }

    ?>


Configuring drupal in a virtual directory

Question: I am running drupal using apache on redhat linux.  Currently drupal is running at the root of the apache site.  However, I want to put drupal in a sub-directory/virtual folder, because it's possible other sites will be on this server in the future.
The sub-folder I want to use is /fr.  I can easily setup apache to use this alias, but how do I configure drupal to know that it's running in a subfolder? I currently have URLs like /agent/dashboard.  If I configure apache for the /fr subfolder, drupal loads but it doesn't recognize /fr/agent/dashboard.
Do I just make a subfolder in the drupal install folder?  I'm not too familiar with apache so I really don't know.  Do I have to redefine all my routes (i'm using Drupal 8).  I really hope not.  I'm looking just for a setting in drupal or apache where I can set this.
Answer: Running Drupal in a subdomain and changing the document root of Apache virtual server are two different things.
To change document root you would set new paths in two Apache configuration lines for the given website:
DocumentRoot /home/username/public_html
<Directory /home/username/public_html>

Change the above two records to whatever you like, for example to:
DocumentRoot /home/username/public_html/sub-directory/sub-sub-directory
<Directory /home/username/public_html/sub-directory/sub-sub-directory>

and it wouldn't matter for Drupal as long as the following directive stays same:
ServerName example.com

In other words, whatever document root you set for a website, it will be still accessible through its domain name typed in the browser's address bar, set as ServerName in Apache configuration file, and Drupal will behave accordingly.
However, if you want to just place Drupal in a sub-directory, then you do not have to meddle with Apache configuration at all.


How to do string replace using if else condition

Question: I am doing a this project on the page about:blank on chrome, meaning there is no other code except for JavaScript involved.
I am trying to make an encryption algorithm with the knowledge that I have. Here is the code so far:
function main() {
    var input = prompt("Enter a string")
    if (input.substring(0, 1) == "a") {
      var _01 = "a"
      var _01new = _01.replace("a", "1")
    }
    else if (input.substring(0, 1) == "b") {
      var _01 = "b"
      var _01new = _01.replace("b", "2")
    }
    else if (input.substring(0, 1) == "c") {
      var _01 = "c"
      var _01new = _01.replace("c", "3")
    }
    else if (input.substring(0, 1) == "d") {
      var _01 = "d"
      var _01new = _01.replace("d", "4")
    }
    else if (input.substring(0, 1) == "e") {
      var _01 = "e"
      var _01new = _01.replace("e", "5")
    }
    else if (input.substring(0, 1) == "f") {
      var _01 = "f"
      var _01new = _01.replace("f", "6")
    }
    else if (input.substring(0, 1) == "g") {
      var _01 = "g"
      var _01new = _01.replace("g", "7")
    }
    else if (input.substring(0, 1) == "h") {
      var _01 = "h"
      var _01new = _01.replace("h", "8")
    }
    else if (input.substring(0, 1) == "i") {
      var _01 = "i"
      var _01new = _01.replace("i", "9")
    }
    else if (input.substring(0, 1) == "j") {
      var _01 = "j"
      var _01new = _01.replace("j", "10")
    }
    else if (input.substring(0, 1) == "k") {
      var _01 = "k"
      var _01new = _01.replace("k", "11")
    }
    else if (input.substring(0, 1) == "l") {
      var _01 = "l"
      var _01new = _01.replace("l", "12")
    }
    else if (input.substring(0, 1) == "m") {
      var _01 = "m"
      var _01new = _01.replace("m", "13")
    }
    else if (input.substring(0, 1) == "n") {
      var _01 = "n"
      var _01new = _01.replace("n", "14")
    }
    else if (input.substring(0, 1) == "o") {
      var _01 = "o"
      var _01new = _01.replace("o", "15")
    }
    else if (input.substring(0, 1) == "p") {
      var _01 = "p"
      var _01new = _01.replace("p", "16")
    }
    else if (input.substring(0, 1) == "q") {
      var _01 = "q"
      var _01new = _01.replace("q", "17")
    }
    else if (input.substring(0, 1) == "r") {
      var _01 = "r"
      var _01new = _01.replace("r", "18")
    }
    else if (input.substring(0, 1) == "s") {
      var _01 = "s"
      var _01new = _01.replace("s", "19")
    }
    else if (input.substring(0, 1) == "t") {
      var _01 = "t"
      var _01new = _01.replace("t", "20")
    }
    else if (input.substring(0, 1) == "u") {
      var _01 = "u"
      var _01new = _01.replace("u", "21")
    }
    else if (input.substring(0, 1) == "v") {
      var _01 = "v"
      var _01new = _01.replace("v", "22")
    }
    else if (input.substring(0, 1) == "w") {
      var _01 = "w"
      var _01new = _01.replace("w", "23")
    }
    else if (input.substring(0, 1) == "x") {
      var _01 = "x"
      var _01new = _01.replace("x", "24")
    }
    else if (input.substring(0, 1) == "y") {
      var _01 = "y"
      var _01new = _01.replace("y", "25")
    }
    else if (input.substring(0, 1) == "z") {
      var _01 = "z"
      var _01new = _01.replace("z", "26")
    }
    else (input.substring(0, 1) == " ")
    {
      var _01 = " "
      var _01new = _01.replace(" ", "27")
    }

    alert(_01new)
}

main()

I know that there is a lot of code, and I am going to simplify it, but first I am trying to get this to work.
What I am trying to do, is when the user enters a string (1 letter currently) it will find the value of the first letter, detect what it is, and set the value of _01 to whatever the user put in, then use _01.replace to replace the the letter with its assigned value (currently the letters numerical value).
Comment: You haven't asked a question.
Comment: `_01.replace("a", "1")` why don't you simply `var _01new  = 1` ? :) (I still don't know that's you idea behind such algorithm...)
Comment: You may want to google "switch case javascript".
Comment: I already see a **problem you'll soon encounter** . If you encode `mm` to `1313` tell me, how would you possibly know the decode characters? it could be decoded as `acac` ... (and that's only one out of 4) I suggest you to go back to the whiteboard.
Comment: Why don't you just replace all of that code with `rot13`?  https://stackoverflow.com/a/41627755/362536
Comment: Btw, doing 27 `if...else if...else` is the point where even the dumbest guy must have noticed that you actually **need** an algorithm, not that you *have* one.
Comment: `else (input.substring(0, 1) == " ")`.... else statements do not have a condition part, take that out and try again or change it to `else if`. That is going to act as the code for the else block. The rest is just going to act like a normal block of code and going to be executed no matter what
Comment: @Brad He could as well replace that code by `void(0)` with regard to encryption value.
Comment: @RokoC.Buljan he should go for powers of 2...
Comment: @EduardoRocha or use an Array? ... The point is clear :)
Comment: @RokoC.Buljan I see... seems good to me :p
Comment: @RokoC.Buljan When I actually make the characters random, I plan on starting every variable with a capital and then random lowercase letters for example, Wgfb = a and Wfbg = b.
Answer: Your logic will fail for multiple characters.
Your idea of encode(/decode) can only work exclusively if and only if a user enters one character.
What if a user enters say "mm" as string. It's encoded as "1313" and you'll never know how to decode it correctly (well, unless you use array [13,13] or some other ciphering sorcery ;) )
I'll leave this to you.
Now, the answer/suggestion for one character - to - number...

// Create an Object literal with mapped character replacements
var map = {
  "a" : 1,  // Or use some other fancy UTF8 characters or shuffle the order
  "b" : 2,
  "c" : 3,
  // and so on...
  "y" : 25,
  "z" : 26,
  " " : 27
}

function main() {

    var input = prompt("Enter a character!");
    var encrypted = -1; // Fallback number. (If no replacement found in our `map`)

    // check if `map` has this "character" property
    if ( map.hasOwnProperty(input[0]) ) {
        // get the value from our map,
        // where `input[0]` represents the first character
        encrypted = map[input[0]];
    }

    alert( encrypted ); // Will alert the replacement number or log -1 as fallback
}

main()
TRY USING ONLY ONE OF: "a b c y z (space)"

Here's Something much simpler - but not much secure as-well ;)
You could convert a string to base64 using btoa()MDN - and than when you want to read the "secret message" you can simply do btoa()MDN over the encoded string

function main() {

    var input = prompt("Enter a string!").trim();
    var encode = btoa( input ); // String to base64
    var decode = "";

    if ( !encode )  return; // Do nothing if nothing valid was entered

    alert( encode );

    // Whenever you want to reveal your secret message:
    decode = atob( encode );
    alert( "Hey I can also decode! Here you go:\n"+ decode);

}

main()

I see your interest toward this kind of stuff... so google, learn about cyphers and other encryption algorhitms. Start by exploring the basic ones:

https://en.wikipedia.org/wiki/Caesar_cipher
https://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher


Notifications vs Subscriptions?

Question: I have enabled both modules for D6 but I'm going to disable one to tidy up my Drupal stack. So wondering what are exactly the differences between the two modules, in terms of  functionality. Are they interchangeable for basic task of allowing users to subscribe to posts and send notification updates? If so, which one is preferred?
P.S. there is relevant thread here some other people may find useful.
Thanks
Answer: I have successfully used notifications on 2 Drupal 6 sites. I like it. Subscriptions had a good reputation but Notifications looked to be more modular and extensible; however, what tipped me towards notifications was the fact that it seemed that the Organic Groups developers were keen to support it and I was looking at putting OG onto my sites (which I subsequently did)
I have the 6.x.2 version of notifications, which seems stable and does what I want.  Very limited experience of the 6.x.4 version suggested it was not stable so I did not persist with that and it remains in beta after 2 years.
Now I have recently been involved in the development of a Drupal 7 site. Although it is over 18 months since D7 was released there is no full Notifications version yet and the module is flagged as Seeking new developer and has been for a significant length of time.  Apparently a quick upgrade was done when Dr7 was released with some limited functionality (what though?) and there is an Alpha2 version which seems to have been receiving some considerable attention (but last updated June).
On this basis, you might be safer to go with Subscriptions which now has a full Dr7 release if you have any thoughts of migrating to Dr7 or developing other sites that might use Dr7. That is mainly to avoid the difficulties in mastering two admin UIs and to protect you in case Notifications really is moribund.
Subscriptions is in the hands of a very experienced developer who has been maintaining it for a long time.
Please note that I have not done a systematic comparison of Subscriptions and Notifications for Dr6 though I did spend quite a while investigating the two at one time several years ago.  See my contribution here:
http://groups.drupal.org/node/12645
(This contains contributions by many others and is useful for an insight into the position in 2008! But Subscriptions and Notifications will both have been enhanced since those posts were written).

Notifications vs Subscriptions?


Is conjugate transpose the "unique" way to define an involution on $M_n(\mathbb C)$?

Question:

Definition: An involution on an algebra $A$ is a conjugate-linear map $a \mapsto a^*$, such that $a^{**}=a$, and $(ab)^*=b^*a^*.$

I can't think of any other ways to define the involution on $M_n(\mathbb C)$(all $n\times n$ matrices), so I feel like it should be unique in some sense. Let
$$f:M_n(\mathbb C) \to M_n(\mathbb C)$$
be an involution, then is $f$ necessary a conjugate transpose or having a standard form closely related to a conjugate transpose?
Thanks in advance!
Comment: He specified "conjugate-linear".
Answer: Yes, actually the involutions you describe are in bijective correspondance with similarity classes of non-degenerate hermitian forms on $\mathbb{C}^n$.
Precisely, let $h:\mathbb{C}^n\times \mathbb{C}^n\to \mathbb{C}$ be a non-degenerate hermitian form. Then you have the adjunction relative to $h$ : $h(u(x),y) = h(x,u^*(y))$, and $u\mapsto u^*$ is a semi-linear involution on $M_n(\mathbb{C})$.
Conversely, any involution is of this form, and two hermitian forms define the same involution iff they are similar, ie there is $\lambda\in \mathbb{C}$ such that $h=\lambda h'$.
How to see this : suppose in general you have two involutions (that is involutive anti-automorphisms) on $M_n(\mathbb{C})$, say $\sigma$ and $\tau$. They restrict to involutions on the center $\mathbb{C}$. Suppose $\sigma_{|\mathbb{C}} = \tau_{|\mathbb{C}} = \iota$. Then $\theta = \sigma\circ \tau$ is an automorphism of $\mathbb{C}$-algebra of $M_n(\mathbb{C})$ (because the actions of $\sigma$ and $\tau$ on the center cancel each other out). But it is ver standard that any automorphism of $M_n(\mathbb{C})$ is inner : so $\theta(M) = H^{-1}MH$. This means that $\sigma(M) = H^{-1}\tau(M)H$.
Conversely, given $\tau$, if $H\in GL_n(\mathbb{C})$, you can define $\sigma(M) = H^{-1}\tau(M)H$, which gives you an anti-automorphism of $M_n(\mathbb{C})$ such that $\sigma_{|\mathbb{C}} = \iota$. Now it's not hard to see that $\sigma^2 = Id$ iff $\tau(H) = \lambda H$ for some $\lambda\in \mathbb{C}$. It requires a somewhat subtle argument to see that by replacing $H$ with a scalar multiple (which doesn't change $\sigma$) you can always take $\lambda = 1$ (this follows from an easy case of the Hilbert 90 theorem).
The link with hermitian forms is the following : suppose you choose $\tau$ the usual conjugate-transpose, so in particular $\iota$ is the complex conjugation. Then the condition $\tau(H)=H$ says that $H$ is a hermitian matrix. It is the matrix of a hermitian form $h$ in the standard basis of $\mathbb{C}^n$, and $\sigma$ is the adjunction for $h$.
Comment: No, it's quite easy : if you compose any two such involutions, it gives you a $\mathbb{C}$-linear automorphism of the algebra $M_n(\mathbb{C})$, and it is a standard undergrad exercise to show that any such automorphism is inner. So any semi-linear anti-automorphism of $\mathbb{C}$ is the composition of the usual conjugate-transpose and the conjugation by some matrix (and it's not hard to see that for the anti-automorphism to be involutive is equivalent to the matrix being hermitian (modulo a scalar constant).
Comment: Thanks for your answer! By definition, we require $**=id$. But $M \mapsto H^{-1}M^* H \mapsto H^{-1}H^{-1}M HH=M$?
Comment: Your formula is not the right one : the square of the involution above is $M\mapsto H^{-1}(H^{-1}M^*H)^*H = (H^{-1}H^*)M(H^{*-1}H)$, so it is involutive when $H = H^*$ ie $H$ is hermitian, as announced.
Comment: Oh sorry, I mixed up unitary matrices and Hermitian matrices. But it still take me some time to digest your answer.
Comment: I edited a bit to make it (hopefully) clearer.


How to use open() in irb console to print out basic text from .txt file? #Ruby

Question: Basically, I'm really stuck.
I've got this text where I need to do like this:
    *print prompt
    file_again = STDIN.gets.chomp()
    txt_again = File.open(file_again)
    puts txt_again.read()*
and basically get text from .txt file printed on my console!
Using File.open() directly from irb, but then attempting:
 File.open("ex15_sample.txt")

^ I assume it opens but I still end up nowhere. I mean, it's not marked as a variable and I can't print it.
If I'll use:
txt = File.open("ex15_sample.txt")

I'll get some error in the first place, so I can't use print txt later on.
Exercise is from http://ruby.learncodethehardway.org/book/ex15.html and I'm trying to do optional stuff so I don't end up nowhere as with codeschool beginners lesson I did earlier on.
Comment: Hi. "some error" is difficult to help with - if you can be more specific you should get an answer
Comment: Are you running irb from the same directory that the `ex15_sample.txt` file is in? You'll need to `cd` to that directory in the terminal first before you can call `txt = File.open("ex15_sample.txt")` in irb. Or you can use the full path to the file.
Comment: It actually doesn't. It actually doesn't do anything at all. The code is like $ txt = File.open("ex15_sample.txt"); puts txt.read(); all the irb does is increases it's number oh and after 2 enters afterwards it change > to * at it's end. Whatever that means
Comment: it's because of your trailing semicolon
Comment: I laughed when I read hashtag Ruby :)
Comment: See also http://stackoverflow.com/questions/13837722/what-is-the-class-of-if-unless-etc/13839206#13839206
Answer: I have created a file ex15_sample.txt in .../Ruby/zintlist/irb.
1.8.6 :082 > File.open("ex15_sample.txt")
Errno::ENOENT: No such file or directory - ex15_sample.txt
    from (irb):82:in `initialize'
    from (irb):82:in `open'
    from (irb):82
    from :0
1.8.6 :086 > Dir.getwd
 => "/.../Ruby/prod/spec"
1.8.6 :087 > Dir.chdir('../../zintlist/irb')
 => 0
1.8.6 :088 > Dir.getwd
 => "/.../Ruby/zintlist/irb"
1.8.6 :089 > File.open("ex15_sample.txt")
 => #<File:ex15_sample.txt>
1.8.6 :090 >

attempting File.open("ex15_sample.txt") I assume it opens

Within irb, usually you don't need to assume, you have an immediate answer.
1.8.6 :090 > txt = File.open("ex15_sample.txt")
 => #<File:ex15_sample.txt>
1.8.6 :091 > puts txt.read()
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.
 => nil
1.8.6 :092 >

Answer: 1.8.6 :090 > txt = open("ex15_sample.txt")
 => #<File:ex15_sample.txt>
1.8.6 :091 > puts txt.read
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.
 => nil
1.8.6 :092 >

Comment: Welcome to Stack Overflow!  While you may have solved the asker's problem, code-only answers are not very helpful to others who come across this question.  Please edit your answer to explain why your code solves the original problem.


Upgrade Webpack from 3.12 to latest

Question: I'm a part-time React guy and need to upgrade from React 16.13.1 to the latest (17.x). It seems I need to upgrade WebPack first. This seems harder than I hoped. My Webpack.config looks like this:

I'm unsure of the order of upgrades.
Simply trying: npm install webpack@latest
results in:

It seems to want babel-loader updated to the latest?
But then I do npm upgrade -D babel-core@latest, it says I am at latest.
Maybe that's the latest for React16?
Any guidance would be great.
Doing Webpack 3 to 4, results in errors as well. npm install --save-dev email@example.com
Comment: Roll back to the start, upgrade 3.12 to 4.0.0, update all the libraries that now need updating too, as well, and then you fix all the code that broke. Then you commit those changes, push your v4 branch, and then upgrade Webpack to the latest 4.x available. Upgrade all the libraries that need upgrading now too, again. And fix anything that broken. Commit _those_ changes. Then you do 5.0.0; then the latest 5.x; you don't jump the entire river, you'll drown. Cross the bridges from one island to the next until you're across.
Comment: Thanks @Mike'Pomax'Kamermans - that makes a lot of sense, So some form of npm upgrade webpack@4 ? See edit. Similar errors.
Comment: "and the libraries that need it" is pretty crucial. You can't just update webpack and call it a day, anything that web uses (web pack plugins, babel, babel plugins, etc) need updating in tandem, which is why you update webpack and all webpack associated libraries in lockstep, using small steps. The npm log is literally telling you which libraries are now in conflict due to version requirement mismatching, so just read the log (treat it like normal text: it's telling you everything you need to know) and then update the libraries it tells you have version mismatches to "just high enough" too.
Answer: From your current webpack version to latest there were majors changes in webpack config itself and dependencies, like some got deprecated and replaced by another one. I did upgrade from v4 to v5 and the process was similar as commented, updating the packages and fixing the changes related to them, also checking the things that were updated/deleted in my webpack file.
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).

Upgrade Webpack from 3.12 to latest


How to add or remove spaces depending on user input (Ascii to hex, binary...)

Question: I am trying to make it so you can convert user input (ASCII to hex, binary and more). My problem is when the user input has spaces I want the output also to have space and vise versa when there are no spaces also have no spaces.
<code>    function asciiConverter(asciiInput) {
    var hexArray = [];
    var binArray = [];
    var decArray = [];
    for (var i = 0, length = asciiInput.length; i < length; i ++) {
        var hex = asciiInput.charCodeAt(i).toString(16);
        hexArray.push(hex);
        var binary = asciiInput.charCodeAt(i).toString(2);
        binArray.push(binary);
        var dec = asciiInput.charCodeAt(i).toString(2);
        decArray.push(dec);
    }
    // /g is a global match with regex
    var hexPrint = hexArray.toString().replace(/,20/g, " ").replace(/,/g, " ");
    document.write(hexPrint);
}
asciiConverter("123");
</code>
Output:  31 32 33
answered my own down below
Answer: Answered my own again:
<code>var hexPrint = hexArray.toString().replace(/,20/g, " ").replace(/,/g, "");
</code>
change
    .replace(/,/g, " ");
to
    .replace(/,/g, "");


java program to check duplicate value from a given string

Question: I got a question states that, "we will give you a string ex:Most of the people are living in apartments and they are rich too. In this given string we have to remove "are" and we have to display the rest things...
I don't know what to do???
Comment: I would refrain from asking most homework questions online. it will bite you in the butt in the future
Comment: at least give a try before you actually ask it here
Answer: By simply using : <code>"Most of the people are living in apartments and they are rich too".replaceAll("are","");</code>
Answer: see the documentation
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replaceAll(java.lang.String, java.lang.String)
use
<code>"Most of the people are living in apartments and they are rich too".replaceAll("are","")
</code>


How to redirect xargs -P output to individually named files

Question: Fundamentally, I want to do something like:
find . -type f -print0 | xargs -0 -P 3 blahblahcommand > `mktemp`.blah

(not sure where the backticks went around mktemp.)
or perhaps blahblahcommand allows the specification of an output file:
find . -type f -print0 | xargs -0 -P 3 blahblahcommand -o `mktemp`.blah

So that as the 3 processes are running (or max of 3 rather), each individual blahblahcommand output is going into a unique file.  But mktemp is evaluated once, and of course, the output of blahblahcommand is stomped on.
blahblahcommand does not have support to generate a uniquely defined filename unfortunately.
Is there an easy way to do this in bash?
Individually is trivial, but I am not enough of a shell programmer to figure out how to make this work like I want.  Any tips appreciated.
Answer: You can use GNU parallel instead of xargs:
readarray -t files < <(find . -type f -print0 | parallel -0 -X -P3 --files blahblahcommand)

will save the output of executions of blahblahcommand file1 file2 file3 ... fileN in temporary files and store their names in the files array for further use.
Comment: That looks like it would work.  Unfortunately, GNU parallel doesn't seem to be installed in this environment (synology NAS).  I'm going to look for a package and see if it can be added with Entware or something.


Find an equivalent condition to $\operatorname{tr}(A^{\ast}B)=0$ for two complex hermitian matrices $A, B$ with rank of $B$ 1.

Question: I have two matrices $A,B$ given that both are positive semi-definite, complex. Another given is that $B$ has rank $1$ and is hermitian.
Additionally $B=ww^{\ast}$ where $w\in \mathbb{C}^{m}$ with $w_k=e^{-2\pi i u k}$.
Now I want to find a condition that implies (or better still is equivalent to) $\operatorname{tr}(A^{\ast}B)=0$. Here $\ast$ stands for the complex cunjugate transpose. This condition should if somehow possible be only dependent on $A$.
Originally I thought maybe $\det(A)=0$ would suffice but have not been able to prove this.
Comment: $\det(A) = 0$ is a necessary but not sufficient condition
Comment: $A^*B = vw^*$ for  $w$, $v=A^*w$ and its trace is $w^*v$, soooo
Answer: Note that
$$
\operatorname{tr}(A^*B) = \operatorname{tr}(Aww^*) = \operatorname{tr}(w^*Aw) = w^*Aw.
$$
So of course, this trace is zero iff $w^*Aw = 0$. Moreover, because $A$ is positive semidefinite, it can be shown that $w^*Aw = 0 \iff Aw = 0$ (I give some proofs of this result in my earlier post here).
That is, we can say that $\operatorname{tr}(A^*B) = 0$ if and only if $w \in \ker(A)$.  That is, this trace is zero iff we have
$$
\sum_{k=1}^n a_{jk}e^{- 2 \pi i uk} = 0 \quad j = 1, \dots, n,
$$
where $a_{jk}$ denotes the $j,k$ entry of $A$.


Is the negative power of a matrix defined?

Question: I had a matrices exam last week and I wrote $A^{-2}$ to refer to $(A^{-1})^2$ (A being an invertible matrix). Initially, I was given the question wrong, but I told the professor that I saw in a book that $(A^{-1})^n = A^{-n} = (A^n)^{-1}$ and gave me the point.
He said that $A^{-n}$ isn't defined for matrices, which I may believe since I haven't seen it in this forum yet, but I would find having to write $(A^{-1})^n$ or $(A^n)^{-1}$ very annoying just for the fact that it isn't defined.
So, is it (defined)?
P.D.: The book is Linear Algebra by Paul Dawkins 1.
Comment: Yeah, it's accepted notation. Of course, one must be careful to only use this on invertible matrices, but otherwise, all the usual integer exponent rules hold.
Comment: It would be easier to diagonalize the matrix first.
Answer: Yes, $A^{-n}$ is defined to be $(A^{-1})^n$ when the matrix is invertible.
For example for $$A=\begin {bmatrix}3&2\\4&5\end {bmatrix}$$
We have $$ A^{-1} = \begin {bmatrix}5/7&-2/7\\-4/7&3/7\end {bmatrix}$$
Thus  $$ A^{-2} =\begin {bmatrix}5/7&-2/7\\-4/7&3/7\end {bmatrix}^2= \begin {bmatrix}33/49&-16/49\\-32/49&17/49\end {bmatrix}$$
Answer: You are correct that they are the same, at least for integers (rational powers of matrices are a whole other mess I'm not going to go into here).
By definition: $$(A^n)^{-1}A^n = I,$$ where $I$ is the appropriate-dimensional identity matrix. Since $A$ is square and invertible, $A^-1$ exists and it is also square. We can therefore right-multiply both sides with $(A^{-1})^n$, apply sequentially the inverses to each copy of $A$, and the result follows.

p.s., while thinking about the problem, I also found a nice (partial) proof by induction, which I thought would be nice to include:
$\require{cancel}$
Assume you take the $n$th power of the inverse, i.e., $(A^{-1})^n$, we can show that it is the inverse of $A^n$: The base case, $n=1$, is true by definition. Now, assume that $(A^{-1})^k$ is $(A^k)^{-1}$. Then,$$(A^{-1})^{k+1} A^{k+1} = (A^{-1})^k \bcancel{A^{-1} A} A^k,$$ by definition of the matrix power. Now, by the induction hypothesis, the right-hand side is the identity. It follows that the $(A^{-1})^{k+1}$ on the left-hand side is the inverse of $A^{k+1}$, as required.


Should the Azure Key Vault URL be hidden?

Question: In the Microsoft Docs they store part of the name for the Azure Key Vault as an Environment variable, and then use it like this:
string keyVaultName = Environment.GetEnvironmentVariable("KEY_VAULT_NAME");
var kvUri = "https://" + keyVaultName + ".vault.azure.net";

var client = new SecretClient(new Uri(kvUri), new DefaultAzureCredential());

I get how it works, but I cannot figure out why they are doing it this way?

I don't get why the URL for the vault needs to be hidden, since you cannot enter it unless it is explicitly configured in Access Policies. You simply get a 403 Forbidden (see screenshot).

Even if it were a secret, why not use the appconfig.json file? Isn't that what you usually use - and why they split it in a release and Development (appsettings.Development.json) version?
Comment: As you already mentioned it's not about keeping it a secret. The reason why they use an environment is mostly just convenience. As you mentioned an `appconfig` or `appsettings` would also work, but for a short console app demo running on various platforms this is as easy as it gets.
Comment: If an attacker gets on your server and is able to read environment variables, or the file on disk if you store in with appsettings.json, then that's one less hurtle for them to get over because they know _where_ your secrets are stored.
Comment: Just because somebody doesn't have your house key doesn't mean it's a good idea to tell random strangers your full home address.
Comment: @gunr2171, is it that difficult for an attacker to know that KeyVaultName needs a suffix of .vault.azure.net and prefix of https ?! are we talking about people here or machine that scrap files for URLs to try ?!
Answer:
I don't get why the URL for the vault needs to be hidden, since you
cannot enter it unless it is explicitly configured in Access Policies.

Basically, keyvault uris are needed to be hidden because they may attract unneccessary attention of bruteforce attackers and hackers and they may try to get in your keyvault using the uri which has been shared in public . Incase access to the keyvault is not correctly configured, It might be vulnerable to misuse and as the  keyvault name which mentioned in the  uri which is supposed to be private thus it is hidden .

Even if it were a secret, why not use the appconfig.json file? Isn't
that what you usually use - and why they split it in a release and
Development (appsettings.Development.json) version.

You can normally use the secrets stored in keyvault in appsettings.json file by calling the access key to that secret and providing the correct permissions for the usage of that secret in key vault.
When running the application the appsettings.json file split into two parts where secrets are loaded in development and values are in production due to which there are two versions of appsettings.json file one for production and one for release version.
For more information please refer the below links:
SO THREAD :- Access azure key vault secret with application client secret
MICROSOFT DOCUMENTATION:- Azure Key Vault configuration provider in ASP.NET Core


Can I program a check on a save on an admin page?

Question: Take for example the CKEditor admin page, where at file browser settings you can choose IMCE at file browser type. Then  you click Save.
Can you program this? I mean in PHP; because I could also find out which SQL query is done, and use drush sql-query, but that is not what I mean. I want to program it because I have a multisite with about 70 sites.
Thanks,
Eric J.
Answer: Yes, use hook_form_FORM_ID_alter()
function MYMODULE_form_FORM_ID_alter(&$form, &$form_state, $form_id) {
  $form['#validate'][] = 'MYMODULE_some_validate_function';
  $form['#submit'][] = 'MYMODULE_some_submit_function';
}

function MYMODULE_some_validate_function($form, &$form_state) {
  if ($form_state['values']['foo'] !== 'bar']) {
    form_set_error('foo', t('Foo must be bar'));
  }
}

function MYMODULE_some_submit_function($form, &$form_state) {
  // Do something.
}

It's not possible to be any more specific than that as 'admin' pages vary in their structure. Most are created using a system_settings_form(), though, so there's a reasonable amount of consistency.
It's also worth noting that a form created with system_settings_form() saves its data in the variables table, so you can accomplish the same thing in a lot of cases with variable_set():
variable_set('site_name', 'New name');

Comment: Thanks. In my_form_alter I said $form_state["values"]["filebrowser"]="imce". But I do not know how to program what you do on the UI page: click the Save  submit button. Think about all the post        data, how do I do that?