Trying to delete a line from a CSV file, my code deletes a line and half of the following line

Question: Hi I need to be able to delete a line in a CSV file. My code currently deletes a line and up to the first comma of the following line.
I've tried changing the scanner delimiter but I can't get it to work how I need it to.
public void deleteRecord() {
        String filePath = "marks.txt";
        System.out.println("Enter the StudentID of the record you wish to delete: ");
        Scanner in = new Scanner(System.in);
        String removeTerm = in.nextLine();
        String tempFile = "temp.txt";
        File oldFile = new File(filePath);
        File newFile = new File(tempFile);

        try {
            FileWriter fw = new FileWriter(tempFile,true);
            BufferedWriter bw = new BufferedWriter(fw);
            PrintWriter pw = new PrintWriter(bw);
            Scanner scan = new Scanner(oldFile);
            scan.useDelimiter("[,]");

            while (scan.hasNext()) {
                String ID = scan.next();
                String Mark = scan.next();
                if (!ID.equals(removeTerm)) {
                    pw.println(ID + "," + Mark);
                }
            }
            scan.close();
            pw.flush();
            pw.close();
            oldFile.delete();
            File dump = new File(filePath);
            newFile.renameTo(dump);
            System.out.println("Record successfully deleted.");

        } catch(IOException e) {
            System.out.println("Error has occured.");

        }
    }

B00987,58
B00567,43
B00343,59
B00653,25
B00757,31
B00876,40
B00421,62
B00568,78
B00826,79
B00126,93
B00862,62
B00999,12
B00237,68
B00762,85
B00864,49

This is the file before deleting a line.
I will try delete the first line.
43
B00343,59
B00653
25
B00757,31
B00876
40
B00421,62
B00568
78
B00826,79
B00126
93
B00862,62
B00999
12
B00237,68
B00762
85
B00864,49

This is what happens.
I need it to look like this.
B00567,43
B00343,59
B00653,25
B00757,31
B00876,40
B00421,62
B00568,78
B00826,79
B00126,93
B00862,62
B00999,12
B00237,68
B00762,85
B00864,49

Could someone help me fix this problem?
Comment: By the way, for real work (not homework), I suggest letting a library such as [*Apache Commons CSV*](https://commons.apache.org/proper/commons-csv/) handle the drudgery of reading/writing CSV or tab-delimited files.
Answer: Your input file only contains 1 comma per record, though you scan 2 times to get the ID and mark. So the first scan will give you ID 'B00987' and mark '58
B00567'.
You could use the scanner and add multiple delimiters like this:
s.useDelimiter(",|\\n");

This way the scanner would scan up to comma's and new lines.
I don't use scanners very often though, in your case I would even prefer to use a BufferedReader:
  public void deleteRecord() {
        String filePath = "marks.txt";
        System.out.println("Enter the StudentID of the record you wish to delete: ");
        Scanner in = new Scanner(System.in);
        String removeTerm = in.nextLine();
        String tempFile = "temp.txt";
        File oldFile = new File(filePath);
        File newFile = new File(tempFile);

        try {
            FileWriter fw = new FileWriter(tempFile,true);
            BufferedWriter bw = new BufferedWriter(fw);
            PrintWriter pw = new PrintWriter(bw);
            BufferedReader reader = new BufferedReader(new FileReader(oldFile);

            String line = "";
            while((line = reader.readLine()) != null) {
              if(!line.startsWith(removeTerm)) {
                pw.println(line);
              }
            }
            reader.close();
            pw.flush();
            pw.close();
            oldFile.delete();
            File dump = new File(filePath);
            newFile.renameTo(dump);
            System.out.println("Record successfully deleted.");

        } catch(IOException e) {
            System.out.println("Error has occured.");

        }
    }

Also using autocloseables or at least manage the resources properly would be a nice optimization.
Comment: Altered my original comment with some more context and an alternative solution.


python:why whis code only loop one time?

Question: I tend read two csv files and print specific column by key name.
First, I have a list of my key name like key = [a,b,c]
and I these following code:
with open('./file/report.csv', 'rb') as csvfile,open('./file/all.csv','rb') as csvfile2:
    reader2 = csv.DictReader(csvfile)
    reader3 = csv.DictReader(csvfile2)
    for i in key:
         for row in reader2:
             for row2 in reader3:
                 if row['Case Id'] == i and row2['name'] == i:
                     a=row['Status']
                     b = row2['result']
                     print a,b

two csv files:
report.csv:                         all.csv:
Case Id       Status                 name           result
  a             111                   a               1111
  b             222                   b               2222
  c             333                   c               3333

my expected result is it will loop three times because there are three elements in key list.expected result should look like:
111 1111
222 2222
333 3333

But actual result is:
111 1111

it only loop one time. I am new on coding things, need some help! Thanks!!
Answer: Readers are one-time iterators and are depleted after one iteration.
This means that in the second time around you don't have anything in reader3 since you've already depleted it.
Try this:
reader2 = list(csv.DictReader(csvfile)) # optional
reader3 = list(csv.DictReader(csvfile2)) # must

If you're using big files use more sophisticated matching or just re-open the file each time.
Answer: Think of a CVSReader as a one-time iterator over the file. Once you read a line, you cannot go back, and one the reader is exhausted, you cannot read any more data from the file without re-creating it. A good practice would be to read both readers in to memory and then going over them. E.g.:
list2 = list(reader2);
list3 = list(reader3);

for i in key:
     for row in list2:
         for row2 in list3:
             if row['Case Id'] == i and row2['name'] == i:
                 a=row['Status']
                 b = row2['result']
                 print a,b


BaseAdapter vs CursorAdapter

Question: I would like to know when to use each Adapter. According to my experience, and this article BaseAdapters are useful when I am getting data from an API for example, and I store it in a Collection object.
However a CursorAdapter is used to query contents from a database, phone agenda...In general, contents which have also a content provider to query the info out of them.
So basically a BaseAdapter is used to queries that dont have a content provider to access them, because in that case a CursorAdapter will be the best choice. Is that right?
Answer: BaseAdapter,ArrayAdapter,SimpleAdapter etc are mostly used if you are getting dynamic data from a remote connection (like a web service or API) and can be modified as your wish.
CursorAdapter is mostly used for local files or database to query the database and the content of it.
In your case CursorAdapter seems like the one to go.
Answer: @serdar explaination is almost right, if you are dealing with any database either your own or device(like contacts, sms etc) CursorAdapter is used, and if you want to make your custom list with Images and Textviews etc, then BaseAdapter is generally used. Any if your dealing with more complex custom listview like sorted contacted list along with seprater like A,B,C... then you have to use EfficientAdapter.
Comment: Suppose you have to develop an application that wants to show all the contacts saved in your phone, then you'll query contacts database, contacts and sms are saved in the form of SQLite table and by passing parameter while query you can get those contacts in either Ascending or descending order.
Comment: What about if you want to show the contacts agenda sort by name? Is it still possible to use the CursorAdapter?

BaseAdapter vs CursorAdapter


How to find maximum/minimum of $y=\frac{x(x^2-x+2)}{x^2-9}$?

Question: How can I find minimum and maximum of $y=\frac{x(x^2-x+2)}{x^2-9}$?
In other words, points, where $y'=0$.
My current steps are:
$$y=\frac{x(x^2-x+2)}{x^2-9}=x-1+\frac{11x-9}{x^2-9}$$
$$\frac{dy}{dx}=1+\frac{11(x^2-9)-2x(11x-9)}{(x^2-9)^2}$$
\begin{align}
y'=0 &\Rightarrow 1+\frac{11x^2-99-22x^2+18x}{(x^2-9)^2}=0 \\
&\Rightarrow\frac{11x^2-99-22x^2+18x+(x^2-9)^2}{(x^2-9)^2}=0 \\
&\Rightarrow 11x^2-99-22x^2+18x+x^4-18x^2+81=0 \\
&\Rightarrow x^4-29x^2+18x-18=0
\end{align}
Mathematica 8 gives me two complex and two real roots, but I have no idea how to solve 4th order polynomial equations, nor I am sure if I really have to do this, considering that nothing this ''complex'' should be done in second semester calculus homework.
Comment: There is no (absolute) max or min.
Comment: How is that possible if there is two real x values where $\frac{dy}{dx}=0$?
Comment: Is it asking for the max/min on a bounded domain or the whole real line?
Comment: It is hard for me to translate from my native language, as I do not know the proper terms, but those are critical points, where $y'=0$ and where $y'(x_1)$ changes its sign, e.g. $y'(0.99)<0$, $y'(1)=0$ and $y'(1.01)>0$
Answer: Consider $$f(x)=\frac{x(x^2-x+2)}{x^2-9}$$
as $x \to \pm \infty$. Note the $x^2$ terms from the numerator and denominator cancel out, so you are left with
$$
f(x) = \frac{x(x^2-x+2)}{x^2-9} \approx x \text{ for very large } x.
$$
As a result,
$$\lim_{x \to \pm \infty} f(x) = \pm \infty$$
and it is unbounded on both ends.
Comment: Also, there is a problem when $x = \pm 3$.
Comment: @Cherufe As $x \to \pm \infty$ there cannot be problems with any finite values of $x$...
Comment: He was asking about min and max.
Comment: @Cherufe both min and max are unbounded
Answer: You can use partial fractions here $$\frac{11x-9}{x^2-9}=\frac A{x+3}+\frac B{x-3}=\frac 7{x+3}+\frac 4{x-3}$$ so that $$y=x-1+\frac 7{x+3}+\frac 4{x-3}$$ and $$y'=1-\frac 7{(x+3)^2}-\frac 4{(x-3)^2}$$
Then you should be able to sketch the functions to see what is happening, and to see that any real zeros of the derivative will be at local extrema.
Once your sketch shows you what is going on, you should be able to find suitable values of $x$ on either side of the zeros of $y'$ - the intermediate value theorem then tells you zeros exist (stay away from $x=\pm 3$), and you can use standard numerical methods to estimate the roots.
Splitting the function into simpler components greatly simplifies sketching, and sketching greatly helps if the situation looks a bit complicated.


When does a jazz tune actually modulate?

Question: I am getting into Jazz harmonic analysis, and have watched a few analysis videos to start me off. I will be referring to the analysis that one youtuber (Justinguitarsongs) has made of the tune 'Misty', by Erroll Garner. I have posted a photo of the song, with Roman numerals pertaining to the sections in question.
Bars 2 and 3
ii-V-I in A flat M. A flat M is also acting as the IV chord in E flat M. Despite its IV function, the Eflat7 is not described as a secondary dominant chord leading to IV (V7/IV). Is this because the ii-V-i cadence is seen as a key change?
Bars 7/8 (first time bar)
Here, we have a ii V in F linking with a ii V in E flat. This time, the dominant chord IS described as a secondary dominant chord. Is this because the G-7 that precedes it is part of the key? (chord iii).
Bars 13-16
(for this one, justinguitar made a couple of alterations to the Real Book harmony, as he believed it to be a more accurate representation of the harmony- this can be seen in pencil (A-7-D7, C-7-F7, G-7- C7, F-7, Bflat7).
Here, we have a bunch of interlinking ii-V progressions. The first being in G, then B flat, then F, then E flat. Do these count as modulations, even though they are incomplete? The C-7- F7-G-7 can be seen as a back door progression in G minor, but the G minor itself is the ii chord in F, so it doesn't really 'arrive' in that key.
I also do not understand the relationship between the first two in this sequence (A-7 -D7-- C-7-F7)?
so in short:
ii-V-I cadences: These are seen as modulations, even if the I chord is in key ( and as long as the ii chord isn't in key, otherwise the V is seen as a secondary dominant)?
interlinking ii-V cadences: these are not complete modulations until they resolve? (even arriving at i chord does not count as a modulation if it is also the ii chord of the next ii-V?)

Many thanks for any time spent on this!
Ed
Comment: I don't think ii V I works all over. In key Eb, getting to Ab is pretty simply I>IV, even though it looks like ii V I *in* Ab.
Answer: First, thanks for the great question and all the homework you put into the song before posting a question, we get way too many "can you analyze this song for me?" questions, which are off topic on this site.
In regards to your title question, analysis in general and when any song modulates in particular can be open to interpretation and discussion although sometimes it is clear cut. Now let's get to it.
Bars 2-3 in my book are a secondary ii-V to the IV chord. The Eb7 is a dominant to Ab which makes this obvious. Jazz and pop harmony will often interject a ii chord along with a secondary dominant to have more harmonic motion. Some may call this a modulation but the Ab chord is brief and also functions in the key of Eb so there isn't enough there to call it a modulation. I hear, I, ii/V/IV, IV.
In bars 7-8 the Gm7 is both the iii and part of a ii-V/ii so it's a toss up. You wouldn't be wrong to all it either or. To me it functions as both.
Bars 13-16 (or 15-18 if you're counting from the top) unfortunately are wrong in the Real Book. They do not match with either Erroll Garner's or Johnny Mathis's versions. This is a pet peeve of mine because I have played this song on gigs hundreds of times and I have to tolerate hearing them played incorrectly 95% of the time.
Justin's chords, based on the Mathis version are right for the the first two bars. The second two are actually Fm11 to Bb13b9, one bar each. Either way, these ii-V's are not modulations. ii-V's alone are not thought of as modulations since they never reach home base. To me the term "modulation" is overused. A passage has to go to a key, briefly or not, and establish itself melodically and harmonically as a new key to be considered a modulation. In jazz, sometimes ii-V's do not resolve or have a delayed resolution or even sometimes no obvious harmonic function. I think of them as a "scenic route" back to the tonic.
Here is a sheet with 4 versions and my basic analysis, original Real Book, Justin, Mathis and Garner. Remember Garner wrote the song and his version is NOTHING like the first three, which have some similarities:

You can see the Garner version is very simple, just ii-V/V to ii-V/I. Everything beyond that is just a reharmonization done by arrangers. To me the Gm7 C7 in the third bar of the first two is what wrecks it. It kills the harmonic flow. It should be a ii chord with an 11th in the melody like it is in both the Mathis and Garner versions.
Comment: @EdB123 By "either or", in bars 7-8 what I mean is the Gm has a double function in my book, it is both the iii chord of Eb and also the ii chord of the ii-V/ii. There definitely is no modulation in those two bars.
Comment: @EdB123 As for your question about soloing, and using the bar 7 Gm7-C7 as an example, when 2-5's are part of a cycle like this, my advice would depend on how advanced a soloist someone is. To a beginning level soloist I would say treat it like a 2-5 to a regular I chord, which would be playing an F scale over those two chords which works out to G Dorian over the first and C Mixolydian over the second. As a more advanced soloist I would suggest introducing altered tensions like b9 and b13 into the C7 since it does resolve to an F minor chord. Hope that makes sense.
Comment: @EdB123 I almost always use Dorian over ii chords in ii/V's because the natural 6 of the Dorian scale becomes the leading tone of the V chord in the next scale and ties them together nicely. In this case the F Dorian is also native to the key of Eb too.
Comment: @EdB123 ...now in the case of the Gm7, because it also is the iii chord of Eb you can also play Eb major (G Phrygian) over that chord as an option. Use your ears and see what sounds good to you. They both will work.
Comment: thanks so much! youve been very illuminating!
Comment: Maybe it's a consequence of the alternate tuning I use to play it, which has an open low D string to yield a wonderful rich D chord, and yields good chord voicings for the Real-book chords (G g bb d' f' / c g bb e' g' / F f ab c' eb' / Bb f ab d' f') but like the way the RB version sounds at least as I play it.
Comment: @supercat funny you mention playing it in D, Mathis recorded it in Eb but has been playing it live in D for many years now. Nothing wrong with a nice 3-6-2-5 but in this case I much prefer going directly to the Fm from the F7 like Mathis does.
Comment: No, I play it in Eb, but the D chord sounds awesome.  Incidentally, the tuning also makes the EbM7 sound much better than would be possible in Standard (voiced Eb-eb-gb-bb-d')
Comment: Played many, many incarnations of this - often using G7 C7 F7 Bb7 in bars 7&8. Just dug out the last big band version  I played, and bars 13-16 are as follows - I like the arrangement. Am7  _   D7#9   _   Gm7/Gb9   _   Fm7/Gm7 /Ab6/Bb13b9. Last bar 3 triplets,/ minim Bb. Sorry, impossible to print properly in comments, but sure you'll translate!
Comment: @Tim That works, I'm not a fan of a Gm on the third bar but it is better here because it's not preceded by an F7 or C-7-F7. Funny how absolutely no one plays the Erroll Garner changes there and he wrote the song! That often happens with standards, a reharm becomes popular and no one knows what the original change is. Case in point: Stella By Starlight. In Bb everyone plays Em7b5-A7b9 in the first two bars but it is actually a Bbdim7 for 2 bars.
Comment: Yes, in Stella, if you sitck to Bb on bass, then it's near enough for jazz - k'bds will bung just about anything over that - and often get away with it. I'm still waiting for someone to come up and question what I might have done!
Comment: I just checked my recording at https://www.youtube.com/watch?v=yHHw2x4p0To and I mostly use the RB arrangement, but omit the F7 after the D7.  I instead hold the D7 for a whole measure, and then proceed to the Gm7/C7/Fm7/Bb7 as notated in RB.  I guess I can see why I think of myself as liking the RB arrangement, but why others would hate it.  Playing an F7 between the D7 and Gm seems wrong on just about every level, but I think the RB arrangement works nicely with that chord omitted.
Comment: thanks for such a great answer. Just a couple of questions: You see the cadence to AflatM as a secondary ii-V which I totally get. You then say that you see the Gm-CM Fm (iii-V7/ii-ii) as 'either or'. does this mean ''it is either a secondary cadence or a key change?''. you can view it as both? If this is what you mean, im a bit confused, as if the first one (to Aflat) cant be considered a key change, how could that one? (I'm probably misunderstanding though!).the ii-Vs:  when playing over a ii V whose I is also the ii of the linking ii V, do you treat it as a I or a ii when soloing over it?
Comment: brilliant- thanks so much for the info. With regards to the Fm chord itself in the interlinking ii-Vs, do you basically have a choice of playing either Dorian (ii chord in the key) or aeolian (treating it as i in Fm)?  I suppose if you use the altered scale over the V, you kind of have to go back to aeolian ?
Comment: @supercat Sounds very cool, nice video. The thing that gets me is F7 to Gm7 in the Real Book chart. If you either eliminate the F7 and go to Gm7 or play it like the Mathis version, Cm7 F7 / Fm11 I'm ok with either one. I have to say my preference is the Fm7 over the Gm7 because Gm7 has a tonic quality and I like delaying the tonic sound till the next A section.
Comment: just one more question regarding your bridge examples! in the cases where the resolution chord is delayed, must the chord that follows straight on from the unresolved dominant chord have a relationship with it? (eg 'real book'- D7-F7-G-7) Both the D7 and F7 resolve to G-7, but D7 does not traditionally resolve to F7, yet they are next to each other. so, what is the relationship here? or does it not matter? Similarly, the 'Justin' example (D7-C-7-F7-G-7)- the relationship between D7 (V/iii) and C-7 (vi). is this a bit like VII (equivalent of V7/III) moving to vi? but even that isn't common?
Comment: That's more than one question, lol! It's ok, first, no, there never HAS to be a relationship between two adjacent chords. We can choose to look for one or just accept it and decide if it sounds good or not to us. In the case of the D7-F7, I never thought that particular change sounded good. Pertaining to that and also the Justin/Mathis versions, it is not uncommon to have m3 parallel motion between chords or groups of chords (D7-F7 or Am7-D7-Cm7-F7). We can interpret them as brief modulations or delayed resolutions, etc. It isn't always clear cut, it just has to make sense to you.
Answer: An unusual and beautiful tune.    Unusual in that the basic key (Eb) barely has a chance to establish before we go off on a ii-V-I excursion to Ab, then on what could have been another one to Gb, diverted however home to the tonic.   The rest of the section is standard 'cycle of 5ths'.
'Modulations' or 'temporary tonal centres'?  Perhaps 'modulation' should be reserved for a change of centre that sticks around for more than one bar!
It's well-established in jazz harmony that a ii-V-I progression is so strong that you can use it to get just about anywhere.  (Try!)  The use here is pretty tame, sticking close to the home key.  'Giant Steps' takes it rather further!
The middle 8 starts with the same trick, a ii-V-I to Ab.  Then an even more extended 'cycle of 5ths' journey home to E♭ extending right back to Am7-D7-Gm7-C7-Fm7-B♭-E♭!   Leave that D7 right where it is - it's the F7 which is the interloper, dirtying up the nice clean cycle of 5ths as a - very pretty - chromatic alternative to the basic D7. (I'm not sure it's authentic, but it's still pretty!)
Don't forget it's a song, not just a chord sequence.  The melodic imitation of 11-14 and 15-18 contribute a lot to it all hanging together.
Listen to Erroll Garner completely fail to appreciate what a beautiful tune he'd written - obscuring it with gratuitous filigree.

Here's the classic interpretation:

This version is sacrilege, but somehow it's hard to dislike it!
Answer: It is very common to modulate to the IV even in classical and renaissance music.  Probably one of the most common devices in my experience.  Don't focus on the chords as there are many choices that could be used to harmonize a song.  Look at the melody and you will see an accidental in the second measure, specifically a b7 of the key signature.  This is all it takes to move up a 4th in key.  At the end of the day it doesn't matter how you harmonize it, the key change is there.  Not all accidentals indicate a key change but this one is quite obvious, and you can hear it without the chords.  If I see a #5 (and possibly #4 with it) I'm going to hear a modulation to the relative minor.  Think of the E7 in the second bar of All of Me, that forces the ear to want to hear A (M or m).  Then they land on A7 which makes you think D-, the next chord in the sequence.  Jazz has a tendency to overuse strings of cycle extensions but that is what makes it sound cool.  These devices are sometime inserted even when the melody does not indicate a key change.
Answer: Love this song! Played it for years - in key C on piano, but E♭ on guitar.
For what it's worth, I've never considered that this song modulates anywhere. It's solidly in E♭ (as writ), and when the first A♭ comes along, well, that's standard I>IV. Even when D♭ appears, that doesn't implicate a modulation to key A♭, it's just a re-harmonisation of A♭ minor - or VII if you like.
Modulation, to me, is a temporary key change. If that continues for more than a few bars, then it is a key change, but there's nowhere in Misty that feels like it's left E♭ for more than a bar or two. The middle eight moves towards A♭, but that's a common enough transition, coming back onto E♭ for the next verse. So, I believe there's no proper modulation going on here.
Comment: Misty is one of my favorite songs to play chords for on guitar in my alternative tuning which has a low D string.  What sort of arrangement do you play?
Comment: @supercat - depends a lot on the instrumentation. Solo, small jazz band, big band arrangements, ad hoc ensembles, whatever. Sometimes dead straight, sometimes with a slight swing, but 12/8 doesn't seem to do it any justice.
Comment: Do you find any arrangement of the guitar chords for Misty satisfying without either a bass or a low D string?
Comment: @supercat - no, in a word! Stuff in Eb isn't good for guitar in my world. Spent years in big bands playing stuff i Eb, and considering permanently tuning down a semitone. But then when it came to the pop section of the gig, I'd have to go standard again! Really don't know why I learned it in Eb, although it wouldn't take much to notch it up to E, but then it usually gets played in Eb, so I'm stuffed playing with others. It's nice on bass, though - the 5 string comes out to play!
Comment: I like the way the chords sound in my alternative tuning.  https://www.youtube.com/watch?v=yHHw2x4p0To  That EbM7 right on the start has a nice compact top (total compass on that chord is just under an octave), and then the D7 in the bridge is huge (total compass on that chord is two octaves and a third).  What do you think?


How are template definitions matched to template declarations?

Question: How exactly is a template declaration matched to a template definition? I found some text in the standard about template-ids referring to the same function if "their template-names [...] refer to the same template and [...]" (14.4 [temp.type] p1) but I can't find a definition for template-names or when template-names refer to the same template. I'm not sure if I'm on the right track anyway because I haven't deciphered the grammar well enough to tell if a template-id is part of the definition/declaration of a template, or just a use of a template.
For example, the following program works fine.
#include <iostream>

template<typename T>
T foo(T t);

int main() {
    foo(1);
}

template<typename T>
T foo(T t)
{ std::cout << "A\n"; return 0; }

If I change the way I use the template parameters in the template definition the names apparently no longer refer to the same template, and linking fails.
#include <iostream>

template<typename T>
T foo(T t);

int main() {
    foo(1);
}

template<typename T>
int foo(T t) { std::cout << "A\n"; return 0; }

// or

template<typename T>
struct identity {
    typedef T type;
};

template<typename T>
typename identity<T>::type
foo(T t) { std::cout << "A\n"; return 0; }

Next, if I move the template definition to another translation unit, for my implementation of C++ (MSVC 11 beta) the program works no matter how I say the types.
//main.cpp

template<typename T>
T foo(T t);

int main() {
    foo(1);
}

//definition.cpp
#include <iostream>

template<typename T>
struct identity {
    typedef T type;
};

template<typename T>
typename identity<T>::type
foo(T t) { std::cout << "A\n"; return 0; }

template int foo<int>(int);

or
//definition.cpp
#include <iostream>

template<typename T>
int foo(T t) { std::cout << "A\n"; return 0; }

template int foo<int>(int);

or even if the definition isn't a template at all:
//definition.cpp
#include <iostream>

int foo(T t) { std::cout << "A\n"; return 0; }

Obviously linking is succeeding because the signature/mangled name is the same regardless of the template that was instantiated to create the symbol. I think this undefined behavior  because I'm violating:

§ 14.1 [temp] p6
A function template, member function of a class template, or static
  data member of a class template shall be defined in every translation
  unit in which it is implicitly instantiated (14.7.1) unless the
  corresponding specialization is explicitly instantiated (14.7.2) in
  some translation unit; no diagnostic is required.

But then say I try to fulfill those requirements by putting a definition of the template in the second translation unit, and including an explicit instantiation at one of two locations:
#include <iostream>

template<typename T>
T foo(T t) { std::cout << "A\n"; return 0; }

// Location 1

template<typename T>
int foo(int t) { std::cout << "B\n"; return 0; }

// Location 2

What are the rules about disambiguating what template an explicit instantiation refers to? Putting it at Location 1 causes the correct template to be instantiated and that definition to be used in the final program, while putting it at Location 2 instantiates the other template, and causes what I believe is undefined behavior under 14.1 p6 above.
On the other hand an implicit instantiation of two templates definitions picks the first template no matter what, so it seems like the rule for disambiguating the templates is different in these circumstances:
#include <iostream>

template<typename T>
T foo(T t) { std::cout << "A\n"; return 0; }

template<typename T>
int foo(int t) { std::cout << "B\n"; return 0; }

int main() {
    foo(1); // prints "A"
}

The reason this came up is related to this question where the questioner discovered that a single forward declaration
template<typename T>
T CastScriptVarConst(const ScriptVar_t& s);

could not act as a declaration of multiple template definitions:
template<typename T>
typename std::enable_if<GetType<T>::value < SVT_BASEOBJ,T>::type
CastScriptVarConst(const ScriptVar_t& s) {
    return (T) s;
}

template<typename T>
typename std::enable_if<!(GetType<T>::value < SVT_BASEOBJ)
                        && std::is_base_of<CustomVar,T>::value,T>::type
CastScriptVarConst(const ScriptVar_t& s) {
    return *s.as<T>();
}

And I wanted to better understand the relationship between template definitions and declarations.
Comment: Pick up a copy of "C++ Templates: The Complete Guide" for the full-fledged story. And yes, it's more digestible than the standard ... a lot actually ;)
Answer: OK, let's start from the beginning. The "template-name" of a template is the actual name of the function or class being templated; that is, in
template<class T> T foo(T t);

foo is the template name. For function templates, the rule for deciding whether they are the same is quite long, described in 184.108.40.206 "Function template overloading". Paragraph 6 of that section (I'm quoting from C++03 here, so the wording and paragraph numbers might have changed in C++11) defines the terms equivalent and functionally equivalent, when applied to expressions involving template parameters.
In short, equivalent expressions are the same apart from possibly having different names for template parameters, and functionally equivalent expressions are the same if they happen to evaluate to the same thing. For example, the first two f declarations are equivalent, but the third is only functionally equivalent to the other two:-
template<int A, int B>
void f(array);
template<int T1, int T2>
void f(array<T1 + T2>);
template<int A, int B>
void f(array< mpl::plus< mpl::int, mpl::int >::value >);

It goes on in paragraph 7 to extend those two definitions to whole function templates. Two function templates that match (in name, scope, and template parameter lists) are equivalent if they also have equivalent return types and argument types, or functionally equivalent if they only have functionally equivalent return types and argument types. Looking at your second example, these two functions are only functionally equivalent:-
template<typename T>
T foo(T t);

template<typename T>
typename identity<T>::type foo(T t);

Paragraph 7 closes with the dire warning that, "If a program contains declarations of function templates that are functionally equivalent but not equivalent, the program is ill-formed; no diagnostic is required." Your second example is, thus, not valid C++. Detecting errors like that would require each declaration and definition of a function template to be annotated in the binary with an AST describing the template expression each parameter and the return type came from, which is why the standard doesn't require implementations to detect it. MSVC is justified in compiling your third example how you intended, but it would be just as justified to break.
Moving on to explicit instantiation, the important section is 14.7, "Template instantiation and specialization". Paragraph 5 disallows all of the following:

Explicitly instantiating a template more than once;
Explicitly instantiating and explicitly specializing the same template;
Explicitly specializing a template for the same set of arguments more than once.

Again, "no diagnostic is required" as it's quite hard to detect.
So to expand your explicit instantiation example, the following code breaks the second rule and is illegal :-
/* Template definition. */
template<typename T>
T foo(T t)
{ ... }

/* Specialization, OK in itself. */
template< >
int foo(int t)
{ ... }

/* Explicit instantiation, OK in itself. */
template< >
int foo(int t);

This is illegal regardless of the locations of the explicit specialization and the explicit instantiation, but of course because no diagnostic is required, you may get useful results on some compilers. Note also the difference between explicit instantiation and explicit specialization. The following example is ill-formed because it declares an explicit specialization without defining it:-
template<typename T>
T f(T f)
{ ... }

template< >
int f(int);

void g(void)
{ f(3); }

but this example is well-formed, because it has an explicit instantiation:-
template<typename T>
T f(T f)
{ ... }

template f(int);

void g(void)
{ f(3); }

The < > makes all the difference. Be warned also that even when you do define an explicit specialization, it has to be before you use it, otherwise the compiler might already have generated an implicit instantiation for that template. This is in 14.7.3 "Explicit specialization" paragraph 6, just below where you were reading, and again, no diagnostic is required. To adapt the same example, this is ill-formed:-
template<typename T>
T f(T f)
{ ... }

void g(void)
{ f(3); } // Implicitly specializes int f(int)

template< >
int f(int) // Too late for an explicit specialization
{ ... }

If you weren't confused enough yet, take a look at your last example:-
template<typename T>
T foo(T t) { ... }

template<typename T>
int foo(int t) { ... }

The second definition of foo is not a specialization of the first definition. It would have to be template< > int foo(int) to be a specialization of template<typename T> T foo(T). But that's OK: function overloading is allowed, and it's allowed between function templates and normal functions. Calls of the form foo(3) will always use the first definition, because its template parameter T can be deduced from the argument type. The second definition does not allow its template parameter to be deduced from the argument type. Only by explicitly specifying T can you reach the second definition, and only then when the call is not ambiguous with the first definition:-
f<int>(3); // ambiguous
f<string>(3); // can only be the second one

The whole process of doing overload resolution for function templates is too long to describe here. Read section 14.8.3 if you're interested and ask more questions :-)


JavaScript not showing red cross

Question: Hi guys so i am getting back search results using javascript and i am struggling to make a Red cross appear on the right hand side.
So when the user searchs through my db and the result appears i would like an X to appear to the right of it.So example :
Search result 1              X

I have made the X in CSS:
    #markx {
        color: Red;
        font-family: 'Helvetica', 'Arial', sans-serif;
        font-size: 2em;
        font-weight: bold;
        text-align: center;
        width: 40px;
        height: 40px;
        border-radius: 5px;
    }

My code:
         $(".result li").click(function(){
            var text= $(this).text();
            $('.selectedStuff').append('
' + text +' (selected)×
');

         });

For some reason those its no appearing like i want it to in javascript. In css its fine, but obviously i want the X to appear alongside every search request that i make so later on the user can cancel that request.
Comment: in your javascript you're appending a `` which is not a block-level element, and in your html you are using a `` which is a block level element. Try switching your javascript to use a `` or adding `display:block;` in your css. Also you will want to use a class instead of an id for "markx" because there can only be one instance of an id on a page, but it appears that you will be using multiple instances of "markx"
Answer: In my opinion, you are overthinking this by using JS to get your dynamic X. You can achieve this in a much lighter way with CSS specificity and pseudo-selectors.
Use this:
.selectedStuff > div{
    width:300px;
}
.selectedStuff > div:after{
    content:" x ";
    font-family: Arial;
    color: red;
    position:relative;
    float:right;
    right:-20px;
}

In the same fashion I added the width to the .selectedStuff class through the CSS, you can do that for all the other properties as well instead of hardcoding them inside the jQuery. This makes your code more maintainable.
The X is a simple letter X but if you want something better looking, use the fontAwesome library and add it as an web font icon.
Here is a DEMO
P.S. I noticed in your JS you meant to produce a series of LIs but the code rendered DIVs instead when I ran it in CODEPEN. If yours produces LIs, just replace the > div my CSS above for > li
Comment: That is fantastic, however later on , i am going to make the X an onclick function so it can delete the search result, in case the user has got it wrong, is this possible using this method?
Comment: Sure! Now you go back to JS and make your `$('.selectedStuff > div:after').click().....remove something`. And by something, I mean retracing back to it's parent and find within it the li that needs to be deleted

JavaScript not showing red cross


Doubt about $n$-queens problem when $\gcd(n,6) = 1$

Question: In the $n$-queens problem, we attempt to place $n$ queens on an $n \times n$ chessboard so that no two of the queens attack each other; that is, no two queens share a row, column, or diagonal.
A modular solution to the $n$-queens problem satisfies a stricter condition. Here, the diagonals wrap around one side of the board to continue around the other side. We still do not want queens to share rows, columns, or diagonals, but now it is harder. Equivalently, a modular solution is a solution which continues to work after a (modular) translation of the board is applied (say, every queen shifts $i$ to the right and $j$ down, identifying the $1^{\text{st}}$ row as the one that comes next the last and likewise for column).
It was shown by Pólya that the $n$-queens problem can only have modular solutions if $\gcd(n,6) = 1$; equivalently, if $n \equiv \pm 1 \pmod 6$. (See section 5 of A survey of known results and research areas for $n$-queens by Bell and Stevens for more details.)
My question is: if $\gcd(n,6) = 1$, then are all solutions modular? Or can there be normal solutions which are not preserved by translation?
Comment: Please explain what you mean by a modular solution.
Comment: I mean solutions which remain solution after a (modular) translation of the board is applied (say, every queen shifts i to the right and j down, identifying the 1st row as the one that comes next the last and likewise for column)

A modular solution has the property that even after a shift like that it remains a solution
Comment: How can a gcd be negative?
Answer: It seems that all $5$ queens solutions are modular, but here is a $7$ queens solution which is not:
$$
\begin{array}{|c|c|c|c|c|c|c|}
\hline
&Q\rule[-0.6ex]{0ex}{3ex}\\
\hline
&&&Q\rule[-0.6ex]{0ex}{3ex}\\
\hline
Q\rule[-0.6ex]{0ex}{3ex}\\
\hline
&&&&&&Q\rule[-0.6ex]{0ex}{3ex}\\
\hline
&&&&Q\rule[-0.6ex]{0ex}{3ex}\\
\hline
&&Q\rule[-0.6ex]{0ex}{3ex}\\
\hline
&&&&&Q\rule[-0.6ex]{0ex}{3ex}\\
\hline
\end{array}
$$
Rotating this board to the left or right will cause a conflict between the queens on the third and fourth rows.


Is this copy constructor creating an identical and independent deep copy of the input object?

Question: I have the following copy constructor made for a Polynomial class.  The constructor is supposed to create an independent deep copy of the input Polynomial object.  Is the copy constructor actually doing this or is it creating a shallow copy?
Polynomial::Polynomial(const Polynomial &p) {
    cout << "Enter method\n";
    if(p.head != NULL) {
        cout << "Enter if\n";
        Node* n = p.head;

        int nDegree = n->degree;
        while(n != NULL) {
             this->add(n->coeff, n->degree);
             nDegree--;
             n = n->next;
        }
        n = NULL;
    }
}

Here is the add method:
void Polynomial::add(const float& coeff, const int& degree) {
    Node *temp = new Node(coeff, degree, NULL, NULL);
    temp->coeff = coeff;
    temp->degree = degree;
    if(tail == NULL) {
        head = temp;
        tail = temp;
        arrSize++;
    }
    else {
        temp->prev = tail;
        tail->next = temp;
        tail = temp;
        arrSize++;
    }
 }

Comment: You didn't provide enough information to answer the question. Show the class definition and the other constructors, at least
Comment: _@user2932450_ Next time you post code snippets here, [**please ensure**](http://stackoverflow.com/posts/26026984/revisions) you don't have any TAB characters (`\t`) in the literal text.
Comment: Why are you setting the coefficient and degree twice in the add() method?
Answer: Polynomial::add() creates a new node and inserts it in a linked list.
Your copy constructor iterates through the existing linked list to add notes to the list being consutructed.
So it's a deep copy and not a shallow copy.
Remarks:
Consider initializing explicitey head an tail to NULL in your copy constructor, before starting to add nodes.
Depending on the Node constructor, apparently using coeff and degree you may consider not to redundantly reassign these values to temp members.
The purpose of nDegree--; in your loop is not completely clear to me.  I think you could drop it.


Does convergence in $L^1$ imply uniform boundedness on compact sets?

Question: Let $\rho_n,\,\rho\in C(\mathbb R^d)\cap L^1(\mathbb R^d)$ positive for every $n\in\mathbb N\,$. Moreover I know
$$\int_{\mathbb R^d}\rho_n(x)\,d x \,=\,1 \;,\quad\, \int_{\mathbb R^d}|\rho_n(x)-\rho(x)|\,d x\xrightarrow[n\to\infty]{}\,0\,.$$
So in particular the sequence $(\rho_n)_{n\in\mathbb N}$ is bounded in $L^1(\mathbb R^d)$. Can I say that $(\rho_n)_{n\in\mathbb N}$ is also uniformly bounded on compact sets?
Precisely for every $K$ compact subset of $\mathbb R^d$ there exists $M=M_K\in[0,\infty)$ such that for every $n\in\mathbb N$, $x\in K$ we have $\rho_n(x)\leq K$ ?
Edit. In a previous version of this question I asserted that $C(\mathbb R^d)\cap L^1(\mathbb R^d)$ is included in $L^\infty(\mathbb R^d)$. This is not true as pointed out in the comments. The question should still make sense, since I am interest in uniformly bounded sequence on compact sets.
Edit 2. A very rough idea of why I think the answer might be positive. $\rho_n$ is a sequence of probability densities. If it is not uniformly bounded on compact sets, the example of an appoximation of identity comes in my mind. But in this case the limit for $n\to\infty$ would be the Dirac delta distribution, which does not belong to $L^1(\mathbb R^d)\,$. Of course this is far from being a proof.
Comment: No it doesn't. For example $$f(x)=\sum_{n\in\mathbb N}T_n(x)\boldsymbol 1_{(n,n+\frac{1}{n^2})}(x)$$ where $T_n$ is the triangle of vertices $\{(n,0),(\frac{n}{2}+\frac{1}{2n^3},n),(n+\frac{1}{n^3},0)\}$. Then, $f\in \mathcal C(\mathbb R)\cap L^1(\mathbb R)$ but $\limsup_{x\to \infty }f(x)=+\infty $.
Comment: It's not true that $\mathcal C(\mathbb R^d)\cap L^1(\mathbb R)\subset L^\infty (\mathbb R)$.
Comment: @Surb Integrable and locally bounded does not imply bounded?
Comment: @Surb thank you. I'll edit in the question.
Comment: @Surb Is it still possible that my question has a positive answer, since I restric myself to compact subsets?
Answer: Let $f_n$ be the piecewise linear function defined on $[0,1]$ satisfying $$f(0) = 0,\  f(\frac 1{2n}) = -n,\  f(\frac 1n) = 0,\ f(1 - \frac 1n) = 0,\ f(1-\frac 1{2n}) = n,\ f(1) = 0.$$You can extend $f_n$ to the entire line by setting $f(x) = 0$ outside the interval $[0,1]$.  It is easy to verify that $\int f_n \, dx = 0$ for all $n$, that $\int |f_n| \, dx \to 0$, and that $\{f_n\}$ is not uniformly bounded on $[0,1]$.
Now let $\rho$ be any function with $\int \rho \, dx = 1$ and let $\rho_n = f_n + \rho$.  Then $\int \rho_n \, dx = 1$ for all $n$, $\int |\rho_n - \rho| \, dx \to 0$,
but $\{\rho_n\}$ is not uniformly bounded.

EDIT: The example above missed the requirement that $\rho_n \ge 0$.  Another way to proceed is to let $\rho_n$ ($n \ge 2$) be the continuous piecewise linear function on $[0,1]$ satisfying $$\rho_n(0) = 0,\ \rho_n(\frac 1{2n}) = n,\ \rho_n(\frac 1n) = 0,\ \rho_n(\frac 12) = 0,\ \rho_n( \frac 34) = \frac{8n-4}{2n},\ \rho_n(1) = 0.$$
The strange-looking choice of $\rho_n(3/4)$ guarantees that $\int \rho_n \, dx = 1$ for all $n$.
The functions $\rho_n$ converge pointwise on $[0,1]$ to the continuous piecewise linear function $\rho$ satisfying
$$\rho(0) = 0,\ \rho(\frac 12) = 0,\ \rho(\frac 34) = 4,\ \rho(1) = 0.$$
Both $\rho_n$ and $\rho$ can be extended to be equal to zero off the interval $[0,1]$. It is routine to check that
$$\int |\rho_n - \rho| \, dx \to 0.$$
Comment: I am assuming $\rho_n>0$, does it makes any difference?
Comment: Your second example is indeed very interesting. Thank you


Representing 2 or more dimple.js charts

Question: Im a noob and currently I'm practicing with dimple.js.
The problem I'm facing is that I can't represent 2 charts side by side on the same page, it just appears one chart. How can I fix this?
I named each div with two different ID and also considered this on the script.

Answer: EDIT: I cleaned up the code to help make it more maintainable for you going down the road.
http://jsfiddle.net/gv615hcL/
--
So the problem is in the variable naming. You're overriding your variables. In the second declaration you want to change the names of the new dimple svg, for example instead of naming it:
var svg = dimple.newSvg("#chartContainer2", 590, 400);

name it:
var svg2 = dimple.newSvg("#chartContainer2", 590, 400);

Also, make sure you continue to reference the variables properly.
I made a quick JsFiddle for you here: http://jsfiddle.net/fq4p7t2x/
Comment: Thanks! I really appreciate your help (specially now that I'm getting started). :)

Representing 2 or more dimple.js charts


mysql: how to select email_id for which has multiple actions

Question: I have a table like following, email_id is unique to each email while each mail may have multiple actions like both open and unsub, how do I query email_ids with multiple actions? like search email_ids with both unsub and open as actions?
email_id   action
1            open
1            click
2            click
3            open
3            unsub

Comment: Go on. Try something
Answer: This is simple with group by and having:
select emailid
from t
having min(action) <> max(action);

If you want to limit this to particular actions, then use a where clause, such as where action in ('unsub', 'open').


in Xcode, Bundle name in info.plist doesn't change bundle name (.app file name)

Question: I'm developing iPhone app.
I changed Bundle name in info.plist.
But .app doen't change from <project name>.app.

*.app file is shown in the Products folder on the bottom of the Project Navigator(left side of the screen).
I believe .app file is called bundle and Bundle name should change .app's name.
Am I wrong or am I missing something?
Comment: See [this answer](http://stackoverflow.com/a/5791165/119114)
Answer: the applications name(also the display name) is set by a variable called product name .U can change this is in the build settings for target
Comment: thanks. `product name` changed `.app` name. What is `Bundle name` in info.plist? Or why `Bundle name` doesn't work?
Comment: bundle display name changes only the display name..ie how it appears under the icon in the iphone...usually a variable ${PRODUCT NAME} is set as the default..ie whatever you enter as the product name it appears here also... if u think the answer is satisfactory pls vote up :)
Comment: thanks. but i know how `bundle display name` works. what i wanna know is how `bundle name` works. do you know that?
Answer: I dunno if i am getting your question right !
but if you just want to change the name of the project you can
just click on the project name in the project navigator twice with one second gap between the two clicks !!
if you want to change the name of the application the one will appear  in the iPhone device
you may write it on the infoPlist.strings as this

"CFBundleDisplayName" = "youAPPName";

i hope that helps
Comment: @MOthman thanks. but i know both of them. I really wanna change `.app` name. But sujith answered that. And I'll ask about role of CFBundleName(not CFBundleDisplayName) in another question.


Firebase data retrieval is not working

Question: I have been trying to retrieve all my entries in Firebase database to populate my HTML page, but I have not been able to figure it out. I have followed many tutorials and Firebase doc, but my code is somehow not changing the HTML page and no error is shown in the console.
Basically, what I have is a list of job entries in the DB and I need to post those job entries in the format of the picture below.

So for example I have this many job entries in my FirebaseDB

I want retrieve all these entries and display four cards with their respective info and as new entries are being added they will be added to the display. Right now my code is not working and I can't figure out why. Any help will be greatly appreciated.

Job Title

This is where Job description goes
Specialists

var jobTitle = document.getElementById('jobTitle');
var jobDescription= document.getElementById('jobDescription');

database = firebase.database();

var ref = database.ref('Jobs');
ref.on('value', gotData, errData);

function gotData(data) {
  console.log(data);

  var jobs = data.val();
  var keys = Object.keys(jobs);

  for (var i = 0; i < keys.length; i++) {
    var k = keys[i];
    jobTitle = jobs[k].JobTitle;
    jobDescription = jobs[k].JobDescription;

    var li = document.createElement('card', jobTitle, jobDescription)

  }
}

 function errData(err) {
  console.log('Error!');
  console.log(err);
}

Comment: Hi,
 I think you are assigning a string to an element, the correct form should be: `jobTitle.innerHTML = jobs [k] .JobTitle;` And ` jobDescription.innerHTML = jobs [k] .JobDescription;`
Comment: @DarwinMedina Thank you! that worked but only one entry is displayed, do you know how I can get it to duplicate that card for all the other entries in the DB?
Comment: it only display the latest entry not all entries in DB
Comment: Yep, I understand, is the for cycle, there you only replace the existing element in your html, if you want create dynamically elements you need do it different, gimme a chance to show you an example
Comment: Check my response and comment if you have any question
Comment: Thank you it worked for the dummydatajobs, but the problem i'm having is how to replace the dummydatajobs with Jobs in my database.
Comment: I just edited the answer, let know if it works
Answer: Ok @Ola this is an example to how you can populate your html via javascript, also you can check out HandleBars is a JS library to manipulate the DOM and have other many features.
Greetings!

var dummyDataJobs = [
    {
        title: 'CEO',
        description: 'CEO Description'
    },
    {
        title: 'CTO',
        description: 'CTO Description'
    },
    {
        title: 'VP',
        description: 'VP Description'
    }
]
var container = document.getElementById('jobsContainer');
for (var index = 0; index < dummyDataJobs.length; index++) {
    var job = dummyDataJobs[index];
    var newCard = `

`+ job.title + `

`+ job.description + `
Specialists

`;

    container.innerHTML += newCard;
}
<!DOCTYPE html>

In your case you can try the following for cycle:
var container = document.getElementById('jobsContainer');
for (var i = 0; i < keys.length; i++) {
var k = keys[i];
var newCard = `

`+ jobs[k].JobTitle + `

`+ jobs[k].JobDescription +
            `
Specialists

`;

container.innerHTML += newCard;}//END OF FOR

Make sure to add this

 in your html like the example

Firebase data retrieval is not working


Prove $a^3+b^3+c^3\geq a^2b+b^2c+c^2a$

Question:
if $a,b,c$ are positive real numbers,Prove:$$a^3+b^3+c^3\geq a^2b+b^2c+c^2a$$

Things I have done so far: I know the fact that $$a^3+b^3+c^3\geq\frac{1}{2}[ab(a+b)+bc(b+c)+ca(c+a)]$$
However i tried to reach the problem inequality,but I was not succesful.
Source of problem: school exam.
Comment: Alternately, try Rearrangement inequality with $(a^2, b^2, c^2)$ and $(a, b, c)$.
Comment: which school are you in?
Comment: @Aditya,it was not school main exam,it was a exam for students who study for mathematical olympiad.
Answer: By aM-GM:
$$\frac{2a^3+b^3}3\ge(a^6b^3)^{\frac13}=a^2b$$
$$\frac{2b^3+c^3}3\ge(b^6c^3)^{\frac13}=b^2c$$
$$\frac{2c^3+a^3}3\ge(c^6a^3)^{\frac13}=c^2a$$
Add them.

Prove $a^3+b^3+c^3\geq a^2b+b^2c+c^2a$


Store one map with another index map Java

Question: I want to store a whole Map in another Map with index.
My code is as below:
HashMap<Integer, Map<String, String>> custMap = new HashMap<Integer, Map<String, String>>();
Map<String, String> mapCust = new HashMap<String, String>();

for (int i = 0; i < 10; i++) {
    mapCust.put("fname", fname);
    mapCust.put("lname", lname);
    mapCust.put("phone1", phone1);
    mapCust.put("phone2", phone2);

    custMap.put(i, mapCust);
}

Here I have total two Maps custMap and mapCust.
So I want custMap as indexed Map with 10 sub maps of mapCust.
And here fname, lname, phone1 and phone2 are different for each Map mapCust.
But right now, I have all 10 sub Maps with same values like last value of mapCust in all 10 sub Maps.
Comment: because you are working on the same instance of `mapCust` all the time. you might want to reassign `mapCust` at the start of the loop
Answer: HashMap will hold references, so you will have to create new objects for assigning to each keys.
HashMap<Integer, Map<String, String>> custMap = new HashMap<Integer, Map<String, String>>();

for (int i = 0; i < 10; i++) {
    Map<String, String> mapCust = new HashMap<String, String>(); // move this line inside the loop
    mapCust.put("fname", fname);
    mapCust.put("lname", lname);
    mapCust.put("phone1", phone1);
    mapCust.put("phone2", phone2);

    custMap.put(i, mapCust);
}

Answer: Create a new instance of HashMap everytime you iterate
HashMap<Integer, Map<String, String>> custMap = new HashMap<Integer,Map<String, String>>();

for (int i = 0; i < 10; i++) {
Map<String, String> mapCust = new HashMap<String, String>();
mapCust.put("fname", fname);
mapCust.put("lname", lname);
mapCust.put("phone1", phone1);
mapCust.put("phone2", phone2);
custMap.put(i, mapCust);
}

Earlier you were using the same instance of mapCust again and again.


A question about the symmetric positive definite matrix A and $D^{-1/2}AD^{-1/2}$

Question: Assume that $A\in\mathbb{R}^{n\times n}$ is a symmetric positive definite matrix and $D=diag(d_1,\ldots,d_n)$ is a diagonal matrix constructing by using the diagonal entries of $A$, indeed $d_i=a_{ii}$.
What can we say about the relationship between the eigenvalues and eigenvectors of $A$ and the eigenvalues and eigenvectors of $D^{-1/2}AD^{-1/2}$?
Answer: There is not much to say.
$D^{-1/2} A D^{-1/2}$ is positive definite. It has diagonal entries $1$, so the sum of its eigenvalues is its trace, which is $n$.  The trace of $A$ could be any positive number.
Comment: I think you are right. Thank you


Anchor in the entire element's rectangle

Question: I have a list created by the following markup

Bucuresti

Sighisoara

Tuzla

Comorova-Neptun

Maramures

Sinaia

My problem is that the anchor has effect only on the bounding-rectangle created by the a tag, like below:
I want to have, instead the anchor over the entire li tag. In the past, I have been putting the li inside the anchor tag (
Bucuresti
 ), but someone told me that it is wrong. What else can I do to get the effect I want without forcing the HTML syntax?
Answer: Links () are inline elements by default, so they take up the width of their contents. By setting them to block level instead ul.menu a {display:block;}, they'll take up the full width of their containing element by default and you can give them the ability to expand their height.
Answer: You have some CSS to force your
 elements to be the size and shape you want.  It's very likely that you can accomplish the same thing by applying that style to the  elements instead of the
 elements.
jsfiddle.net/92KKa
Comment: somebody posted a comment with `ul.menu li a { display: block; }` and that works. I asked for a bit of explanation.
Comment: @Victor - `display: block` may work beautifully, it all depends on your CSS for the ``.  I updated the jsfiddle from my answer with a version that also compares just adding `display: block` to the links: [jsfiddle.net/92KKa/1](http://jsfiddle.net/92KKa/1/).  You can see that it sort of works, but it doesn't fill the ``, in my case.  It wouldn't be an exact solution for every instance.
Answer: add this style to anchor tag.
a{
  display:block;
}

anchor tag is an inline element and so it should be made block to occupy entire space.


Point dev URL to the default folder of a multisite

Question: In a multisite set up, the default domain www.domain.com point to the 'sites/default' folder.
I want a temporary subdomain point to the default site for development.
In the sites.php files I have:
$sites['dev.domain.com'] = 'default'; // this line can be removed due to the default behavior (see comment below)
$sites['sub1.domain.com'] = 'sub1.domain.com';
$sites['sub2.domain.com'] = 'sub2.domain.com';
$sites['sub3.domain.com'] = 'sub3.domain.com';
Pointing to the 'default' folder is not working for some reason?
What is wrong?
Comment: The default behaviour if the domain isn't listed in sites.php is to go to the default site. If dev.domain.com isn't taking you to default then which site does it take you to? Sounds like there's more to this and you've got other things happening
Comment: @Leigh Yes, there is a misconfiguration in the DNS settings. That is why it was not working indeed.
Answer: Above settings are correct. But there was an error in the DNS settings.


Open a file in Eclipse

Question: i wrote something in C to which needs to open a file.txt and manage some data. I have just started to use Eclipse (after Code::blocks and Netbeans) but i cannot find the right path to put my file in order to allow Eclipse to read it... any suggest?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define COD 10
#define DIP 1000
#define SIZE 5

int main (int argc, char *argv[])
{
    int ora, minuti, i = 0, j = 0, min_lav;
    int num_dip = 0, trovato, dip_lav = 0;
    int vett_or[SIZE][SIZE];
    char cod_dip[COD+1], vett_dip[DIP][COD+1];

    FILE *fp;

    /* Apertura del file */
    fp = fopen (argv[1], "r");

    /* Verifica della corretta apertura del file */
    if (fp == NULL)
    {
        printf ("Errore nell'apertura del file %s\n", argv[1]);
        exit(EXIT_FAILURE);
    }

    /* Primo caso */
    if (argc == 2)
    {
        /* Lettura dele righe e copia degli elementi in un vettore */
        while (fscanf (fp, "%d %d %s\n", &ora, &minuti, cod_dip) == 3)
        {
            strcpy(vett_dip[num_dip], cod_dip);
            num_dip++;
        }

        /* Stampa dei dipendenti */
        for (i = 0; i < num_dip; i++)
            printf ("Dipendente %d: %s\n", i+1, vett_dip[i]);

        /* Ricerca elementi diversi */
        for (i = 0; i < num_dip; i++)
        {
            trovato = 0;

            for (j = 0; j < i && trovato == 0; j++)
            {
                if (strcmp(vett_dip[i], vett_dip[j]) == 0)
                    trovato = 1;
            }

            if (trovato == 0)
                dip_lav++;
        }

        printf ("\n===================================\n");
        printf ("Ci sono stati %d dipendenti a lavoro", dip_lav);
        printf ("\n===================================\n");

    }

    /* Secondo caso*/
    if (argc == 3)
    {
        while (fscanf (fp, "%d %d %s\n", &ora, &minuti, cod_dip) == 3)
        {
            if (strcmp(argv[2], cod_dip) == 0) {
                vett_or[i][0] = ora;
                vett_or[i][1] = minuti;
                i++;
            }

        }

        /* Stampa del dipendente */
        if (i == 1)
            printf ("Per il dipendete selezionato è stato registrato un solo passaggio\n");

        printf ("Dipendente %s:\n", argv[2]);
        printf ("Primo passaggio: %d  %d\n",vett_or[0][0], vett_or[0][1]);
        printf ("Ultimo passaggio: %d  %d\n", vett_or[i-1][0], vett_or[i-1][1]);

        min_lav = ((vett_or[i-1][0]*60)+vett_or[i-1][1]) - ((vett_or[0][0]*60)+(vett_or[0][1]));

        printf ("Il dipendente selezionato ha lavorato per %d minuti\n\n",min_lav );

    }

    return 0;
}

Comment: Is the file name printed correctly in your error message (within the `fp == NULL` clause)?
Comment: "What is the 'best choice' (in your opinion) for a C/C++ IDE under Unix?" -- countless questions like this have been asked here, and closed for being subjective and leading to endless evangelizing. However, *my* suggestion is to **not** use an IDE in the beginning, but using a command-line compiler and simple text editor, because you want to learn **C**, not Eclipse / NetBeans / MSVC / ....
Comment: @simon the name is printed correctly yes...
Comment: @DevSolar i'm a newbie in programming... is it porrible to debugging on command line?
Comment: @user1409641: Absolutely. [GDB](http://www.gnu.org/software/gdb/) is a fine and powerful debugger, and if you start it with `gdb -tui`, even provides you with a nice view at your source code while you set breakpoints and step through your code. While it might not *look* like much, I very much encourage familiarizing yourself with it, because it's second to none when it comes to C/C++ debugging. Command line might look like 70ies, but a good vim / gcc / make / gdb setup beats Eclipse CDT hands down in the long run. For Windows users, I recommend [Cygwin](http://www.cygwin.com).
Answer: In Eclipse you can't actually open single files that are not associated with projects (which can be quite annoying).
Create a project and add the file to it. Then you will be able to open the file ;)
EDIT: Okay, turns out I didn't read your question properly. Ignore this please :)
Comment: Thanks, how to add an existing file to my project?
Answer: You need to put the text file you want to open in the Eclipse project's folder which is (probably) in your workspace folder (or call the function that opens the text file with the absolute path). If you create a new project you can see the path of your workspace folder in the new project wizard window.
Edit: Might be the solution to your problem Read from file in eclipse

Did you try refreshing (right click -> refresh) the project folder after copying the file in there? That will SYNC your file system with Eclipse's internal file system.
Comment: i created a new project called "9.1" and it's correctly positioned in the "workspace" path... i put the "file.txt"in every directory under the "9.1" folder but simply Eclipse does not recognize any file.
Comment: Is the executable generated in the same directory as you also have your text file?
Comment: I can't reproduce your error. I have made a small project and placed a "test.txt" file in the project folder. Calling `fopen("test.txt", "r")` doesn't return `NULL` (built and run within Eclipse) and hence the file can be read w/o problems. What kind of error are you getting?
Comment: Well, i'm passing the file name through command line as "argv[1]" but nothing happens... have not tried opening a file with his name!
Comment: Please show your code. If you pass `argv[1]` you need to enter the file name under `Run > Run Configurations...` in the `Arguments` tab.
Answer: How about putting in a call to getcwd to find the process' current directory?
  char dir[1024];
  getcwd(dir,1024);

Alternatively, could you specify the absolute path to the file?
Comment: Were i need to specify the absolute path?
Comment: How are you opening the file?  `fopen`?  Then instead of `fopen("foo.txt","r")` it would be `fopen("/home/me/stuff/foo.txt","r")`
Comment: yes i'm doing it correctly and i can open the file in the right way running it with (almost) every IDE except eclipse
Comment: So have you tried opening with an absolute path e.g. "/home/..."?

Open a file in Eclipse


WPF Radio Buttons

Question: I am creating Radio button on Visual Studio and I am having a trouble with Binding
This is my button:
<RadioButton VericalAlignment="Center" GroupName="group1" Content="name"></RadioButton>

I want that if the button was selected then the value of {"someString " + Content Value} will be bind
to SomeClass.variable
is something like this possible?
Thank you!
Comment: Handle the `Checked` event?
Answer: Something like this should work:
XAML:
<Window x:Class="StackOverflowRadioButton.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:StackOverflowRadioButton"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">
<Grid Margin="81,36,-81,-36">
    <RadioButton Content="RadioButton" HorizontalAlignment="Left" Margin="111,135,0,0" VerticalAlignment="Top"
                 Name="myRadioButton" Checked="myRadioButton_Checked"/>
</Grid>

CS file:
using System.Windows;

namespace StackOverflowRadioButton
{
    ///
    /// Interaction logic for MainWindow.xaml
    ///
    public partial class MainWindow : Window
    {
        public string someVariable;
        public MainWindow()
        {
            InitializeComponent();
        }

        private void myRadioButton_Checked(object sender, RoutedEventArgs e)
        {
            someVariable = "someString " + myRadioButton.IsChecked;
        }
    }
}

WPF Radio Buttons


Soft-impute on the test set with fancyimpute

Question: The python package fancyimpute provides several data imputation methods. I have tried to use the soft-impute approach; however, soft-impute doesn't offer a transform method to be used on the test dataset. More precisely, Sklearn SimpleImputer (for example below) provides fit, transform and fit_transform methods. On the other hand, SoftImpute provides the only fit_transform, which allows me to fit the data on training but not transform it into the testing set. I understand that fitting the imputation on the training and testing sets will cause data-leak from the testing set into the training. To this end, we need to fit on the training and transform on testing. Are there any ways of imputing the test set of what I fitted from the training set in soft-impute approach?. I appreciate any thoughts.
    # this example from https://scikit-learn.org/stable/modules/generated/sklearn.impute.SimpleImputer.html
    import numpy as np
    from sklearn.impute import SimpleImputer
    imp_mean = SimpleImputer(missing_values=np.nan, strategy='mean')
    imp_mean.fit([[7, 2, 3], [4, np.nan, 6], [10, 5, 9]])

    X_train = [[np.nan, 2, 3], [4, np.nan, 6], [10, np.nan, 9]]
    print(imp_mean.transform(X_train))
    # SimpleImputer provides transform method, so we can apply fitted imputation into the
    testing data e.g.
    # X_test =[...]
    # print(imp_mean.transform(X_test))

   from fancyimpute import SoftImpute
   clf = SoftImpute(verbose=True)
   clf.fit_transform(X_train)
   ## There is no clf.tranform to be used with test set e.g. clf.transform(X_test)

Answer: Fancy impute doesn't support inductive mode. The important thing here is to fill in the training data without using test data. I think you can impute test data using imputed training data. Sample code:
len_train_data=train_df.shape[0]

imputer=SoftImpute()

#impute train data

X_train_fill_SVD = imputer.fit_transform(train_df)

X_train_fill_SVD=pd.DataFrame(X_train_fill_SVD)

#concat imputed train and test

Concat_data=pd.concat((X_train_fill_SVD,test_df),axis=0)

Concat_data=imputer.fit_transform(Concat_data)

Concat_data=pd.DataFrame(Concat_data)

#fetch imputed test data

X_test_fill_SVD=Concat_data.iloc[len_train_data:,]


How does the softmax function come about?

Question: I'm unsure how the softmax function comes about. I understand that the sigmoid function is a result of phrasing the log-odds as a linear equation and then rearranging the formula to model for the probability of an event occurring, but I'm not sure how to do this for softmax. Can someone point me in the right direction?
Comment: Are you dissatisfied with the explanation in https://en.wikipedia.org/wiki/Softmax_function  ?
Comment: @Andreas the answer wasn't really contained in there as it just states "this is a composition of K linear functions", however, the explanation I was looking for was presented here: https://en.wikipedia.org/w/index.php?title=Logistic_regression&oldid=755697139#As_a_.22log-linear.22_model
Answer: Answer on how logistic regression is extended to the multinomial case is presented here:
https://en.wikipedia.org/w/index.php?title=Logistic_regression&oldid=755697139#As_a_.22log-linear.22_model


GCM :Multiple Application ID in Server side

Question: On server side, i found for one device there multiple registration IDs, which obviously is creating for me lots of issues. like messages received many times.
How could I get red of old registration IDs, or make sure that registration doesn't happen if there a valid registration ID.
I follow the example tutorial on Android doc when I wrote my app as below:
<code>checkNotNull(SERVER_URL, "SERVER_URL");
        checkNotNull(SENDER_ID, "SENDER_ID");
        // Make sure the device has the proper dependencies.
        GCMRegistrar.checkDevice(this);
        // Make sure the manifest was properly set - comment out this line
        // while developing the app, then uncomment it when it's ready.
        // NOT required any more GCMRegistrar.checkManifest(this);

        /**
         * this code to register reciver moved to message actvity
         */
        //registerReceiver(mHandleMessageReceiver, new IntentFilter(
        //      DISPLAY_MESSAGE_ACTION));

        /* final String */regId = GCMRegistrar.getRegistrationId(this);

        /**
         * save regId in pref to be used by Location update service
         */
        SavePreferences("regId", regId);

        if (regId.equals("")) {
            // Automatically registers application on startup.
            GCMRegistrar.register(this, SENDER_ID);
        } else {
            // Device is already registered on GCM, check server.
            if (GCMRegistrar.isRegisteredOnServer(this)) {
                ;;
                // Skips registration.
                // -- mDisplay.append(getString(R.string.already_registered) +
                // "\n");
            //  System.out.println(getString(R.string.already_registered)
                //      + "\n");

            } else {
                // Try to register again, but not in the UI thread.
                // It's also necessary to cancel the thread onDestroy(),
                // hence the use of AsyncTask instead of a raw thread.
                final Context context = this;
                mRegisterTask = new AsyncTask<Void, Void, Void>() {

                    @Override
                    protected Void doInBackground(Void... params) {
                        boolean registered = ServerUtilities.register(context,
                                regId);
                        // At this point all attempts to register with the app
                        // server failed, so we need to unregister the device
                        // from GCM - the app will try to register again when
                        // it is restarted. Note that GCM will send an
                        // unregistered callback upon completion, but
                        // GCMIntentService.onUnregistered() will ignore it.
                        if (!registered) {
                            GCMRegistrar.unregister(context);
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(Void result) {
                        mRegisterTask = null;
                    }

                };
                mRegisterTask.execute(null, null, null);
            }
        }
</code>
EDIT: Notice, I could receive messages on the device.
Answer: for a time ,there is only one registration id for single device, multiple ids wont be possible.
when ever you firstly run your application you will get registration id and that you have to register it to GCM registrar.Otherwise message wont be delivered to your device.
on server side, you need to keep this registration id safely so that you can use it when you want to send message.
your problem of keeping track of registration id for particular device: When you got registration id for your device then save it in your server database if you are using otherwise keep it array.and whenever new registration id is generated ,delete the previous one and add new entry into your database.
Comment: sry ..
when a new id is generated you will try to register it GCM registrar.

when this new registration id successfully register your onRegister() method of service will be called .checked following code.
here you can add code to replace previous one with new one.

@Override

 protected void onRegistered(Context context, String registrationId) {

  ServiceUtilities.register(context, registrationId);

 }
Comment: sry but i cant properly indent above code in comment part, cant add this code as another as,its against stackoverflow rule.
from next time please ask new question as separate question
Comment: Thanks ... the trick here how do I need there is a new ID is generated for same device so that I could delete old one?
Comment: I created a new question here http://stackoverflow.com/questions/15031167/multiple-application-id-in-server-side-in-gcm


How do I create a year-only drop-down field?

Question: How do I create a year-only drop-down field?
I want to create a Drupal 8 field that shows a year drop-down with 100 years to the current year.
Answer: The Year Only module provides this feature by defining a new field type.
.
It comes with a range configuration.

It produces the following result in the entity (node, ...) edit form. Configured with unlimited number of values in this example.
Answer: I would personally recommend following https://drupal.stackexchange.com/a/242011/5438. It's a little more work with some coding but it doesn't mean you need to add another module that needs to be supported in relation to many drupal areas. You can use a List (integer) field and add things there.
You can can also use a field_integer textfield and use a form alterer.
Comment: @DanielHarper it's a helper module that uses a core API hook, this means you will hardly have to update it and it uses core's field types instead of one provided by a module. The level of maintainability is considerable less IMO. I did say it was a personal recommendation, this is the reasoning behind it.
Comment: The link suggests creating a custom module so I don't see the benefit here?
Answer: You can use Date module.

This package contains both a flexible date/time field type Date field
  and a Date API that other modules can use.

When you add field you can choose what you want to show (day, month, year) and + and - from current year.
Comment: This was only the case for the D7 module. Date in core does not have these options.


AutoCompleteTextView click event on Android

Question: I have successfully implemented my AutoCompleteTextView which is based off an SQLite query and is placed in an array adapter. That's all working beautifully, however I can't get my onclickevent working.
I just want to create an intent to pass the selected value to a new activity. I know how to create an onclicklistener. I am just unsure about how to apply it to the dropdown box of the AutoCompleteTextView.
Answer: Nevermind. I've solved it. I was just executing poorly. The code below autocompletes my textview based off a simple SELECT SQLite statement and executes when the user selects the university from the dropdown list.
The onclick event creates a new intent and starts a new activity passing the selection to this activity within the intent.
<code>final AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.ac_university);
String[] universities = myDbHelper.getAllUnis(db);

// Print out the values to the log
for(int i = 0; i < universities.length; i++)
{
    Log.i(this.toString(), universities[i]);
}

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, universities);
textView.setAdapter(adapter);

//textView.setOnItemSelectedListener(this);
textView.setOnItemClickListener(new OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                            long arg3) {

        Intent intent = new Intent(Main.this, Campus.class);
        Bundle bundle = new Bundle();

        bundle.putString("university_name", arg0.getItemAtPosition(arg2).toString());
        bundle.putLong("_id", arg3);
        intent.putExtras(bundle);
        startActivity(intent);
    }
</code>
Answer: putExtra function can be used for this purpose.
Here is an example...
Form the sending activity:
<code>    lv.setOnItemClickListener(new OnItemClickListener()
    {
        public void onItemClick(AdapterView<?> parent, View v, int pos, long id) {
            ApplicationInfo x = appinstalled.get(pos);
            PackageInfo y = appinstall.get(pos);
            //Intent i = new Intent(InstalledPackages.this, Information.class);
            i = new Intent(InstalledPackages.this, Information.class);
            i.putExtra("i",x);
            i.putExtra("j", y);
            startActivity(i);
        }
    });
}
</code>
On the receiving side:
<code>    super.onCreate(savedInstanceState);
    Intent myIntent = getIntent();
    ApplicationInfo i = (ApplicationInfo)myIntent.getParcelableExtra("i");
    PackageInfo j = (PackageInfo)myIntent.getParcelableExtra("j");
</code>
Comment: I've created a clickevent that works for my listview activities in my app & i've adapted it for the AutoCompleteTextView, however when I click on on item I want from the dropdown list the event is not firing so I'm obviously not referencing to the dropdown list properly so i am really just asking for a generic bit of code illustrating how to fire an even from the clicking of the drop down list!! cheers


D7 theme field items of a "List (text)" input as

Question: In Drupal 7, I have a field for a custom node type that is a text list "List (text)" with a widget input type of "Check boxes/radio buttons". When displayed on the front-end the following HTML is generated:

XHTML

CSS 3

PHP

How can I theme this output as an HTML
 instead? Something like this:

XHTML

CSS 3

PHP

I should note that I'm overriding output using a node--custom_type.tpl.php file.
Answer: The "right" way of rendering a list, that is, one that interacts properly with all the other systems in Core is theme_item_list.
Code example:
// In this case, $result is a list of nodes returned from a database query.
$list = array();
$list['type'] = 'ul';
$list['title'] = 'List of nodes';
$list['attributes'] = array('class' => array('list-of-nodes'));
$list['items'] = array();
foreach($result as $record) {
  $list['items'][] = l($record->title, 'node/' . $record->nid);
}
$output = theme('item_list', $list);

This should be applicable in your node.tpl as well.
Comment: +1 this function is in file theme.inc so to override this (e.g. to be able to insert css classes into the `` html tag) then, in my theme, would I: copy theme.inc into my theme's includes folder and then override this function name e.g. mytheme_item_list and edit code as required?
Comment: I made a small correction, and added an example of adding a css class, see the attributes line. You don't need to copy the theme file, if you all you want is a css class, though you could re-implement `THEME_item_list` in your template.php if you want to do wildly different things.
Answer: I can advise you to install Devel Themer (don't worry, you can install safely the dev version) and when you'll active you can navigate between elements and you'll have every information you need about theming.
So, active it and then select you element and check the candidate templates or/and candidate functions.
Answer: If you look into bartik template.php, you will find how to override taxonomy field output exactly to your expectation. This is applicable to any other field, the way you want either with UL, OL, DL, etc:
/**
 * Implements theme_field__field_type().
 */
function bartik_field__taxonomy_term_reference($variables) {
  $output = '';

  // Render the label, if it's not hidden.
  if (!$variables['label_hidden']) {
    $output .= '
' . $variables['label'] . ':
';
  }

  // Render the items.
  $output .= ($variables['element']['#label_display'] == 'inline') ? '
' : '
';
  foreach ($variables['items'] as $delta => $item) {
    $output .= '
' . drupal_render($item) . '
';
  }
  $output .= '
';

  // Render the top-level DIV.
  $output = '
' . $output . '
';

  return $output;
}

Answer: You can alternatively use the Text Formatter module which allows you to set the display of fields as either an unordered or ordered list - just like your original question's layout.


What is branching and iteration in an algorithm

Question: This is my first question here. I was looking over the curriculum of year 5 mathematics in my country and came across this "Content description". (from http://victoriancurriculum.vcaa.vic.edu.au/mathematics/curriculum/f-10?y=5&s=NA&s=MG&s=SP&layout=2)
Follow a mathematical algorithm involving branching and repetition (iteration) (VCMNA194)
Can someone explain what branching and repetition mean here? The repetition part I am fine with, but the branching part I cannot picture concretely.
If you could give an example of branching within an algorithm, it would be very helpful. I looked up mathematics dictionaries, but with no luck.
Thank you in advance.
Comment: It looks like they are referring to [this type of branches](https://en.wikipedia.org/wiki/Branch_(computer_science)). And they give an example deeper in your link: "manipulating sets of numbers using a given rule, for example, if a number is even halve it; if a number is odd, subtract 1 then halve it"
Comment: In a nutshell, "branching" is associated in computer science to "if then else" instructions...
Comment: I've noticed I got marked down :-( If my question is a duplicate, I would be very appreciative if I could see where else this question was asked. Or if this is the wrong forum for such a question, it would be helpful if I knew where to go for this sort of information. My google and dictionary search didn't get me very far. This is a topic I'm supposed to be across, so it won't do for me not to find an answer (somewhere). Sorry for the intrusion or inadvertent breach of etiquette :-( (If there is something I need to know, I'm all ears).
Answer: Quoting above:
It looks like they are referring to this type of branches. And they give an example deeper in your link: "manipulating sets of numbers using a given rule, for example, if a number is even halve it; if a number is odd, subtract 1 then halve it" – orole yesterday
In a nutshell, "branching" is associated in computer science to "if then else" instructions... – Jean Marie yesterday


How to send slash commands with selfbot in Discord using Python?

Question: I'm trying to send slash commands with a selfbot ran on repl.it but they are sent as normal message and not detected as commands.
Here's the code:
# coding=utf-8
import discord
import os
from keep_alive import keep_alive
from time import sleep
bot = commands.Bot(command_prefix="+", intents = discord.Intents.default())
def __init__(self, bot):
  self.bot = bot

@bot.event
async def on_ready():
  print("Logged in as {0.user}.".format(bot))
  while True:
    sleep(1)
    await bot.get_channel(farmchannel).send("/tableflip ")

farmchannel = CHANNEL_ID

keep_alive()
bot.run(os.getenv("token"), bot=False)

How to make it work?
I searched in the documentation of discord.py but I saw nothing that is made to send slash commands.
Answer: /tableflip is not a slash command btw. It's built into the client and all it does is put the table flip text at the end of your message. You can replicate this functionality by sending a msg appended to   (╯°□°)╯︵ ┻━┻
For actual slash commands (like "/8ball how is the weather" or "/saved queue list" or whatever) you can use discum's bot.triggerSlashCommand(...) function in the development branch.
There are 2 examples here: https://github.com/Merubokkusu/Discord-S.C.U.M/blob/development/examples/slashcommands.py
The reason for the 2 examples is that there are 2 ways slash commands are triggered (since searching for slash cmds in DMs is done by rest requests but searching for slash cmds in guilds is done by websocket communications).
It doesn't really matter which example you use for which situation.
If you want to mimic the client, use the 1st example in guilds and the 2nd example in DMs.
Finally, if you don't want to use a synchronous api wrapper like discum, you can use discord.py-self. I heard that they will implement slash commands sometime soon.
Answer: I know this post is old but for everyone wondering:
Discord.py doesnt support slash commands for selfbots, because selfbots are no longer supported by the library. However theres a library called Discord.py-self (mentioned by discord tehe), which is basically d.py for selfbots only (it can also be used for normal bots).
To implement slash commands with dpy-self, heres a working solution:
import discord
from discord.ext.commands import Bot

client = Bot(command_prefix="!", self_bot=True, chunk_guilds_at_startup=False)

@client.command()
async def bump(ctx):
  channel = client.get_channel(ctx.channel.id)
  async for command in channel.slash_commands():
    if command.name == "bump":
       await command(channel)

client.run("token")

First we get the current channel to send the slash command, then we use a for loop to go through all slash commands in that channel until we get to the wanted slash command and then send it (you can also go through the slash command ids).
Comment: Thanks buddy it helped me! Just a quick question will it pick the bot that it will find first? Like in discord it's alphabetically ordered?
Comment: @Dumb I'm not sure but i think it is ordered like discord does, but the [Docs](https://discordpy-self.readthedocs.io/en/latest/api.html?highlight=slash_commands#discord.abc.Messageable.slash_commands) don't mention it.
Comment: Oh, I see. I made a self bot and it runs all the commands with that name.
Comment: you can get the id of the specific command and then run it like i mentioned in my post
Answer: Try using character code
await bot.get_channel(farmchannel).send(chr(47) + "tableflip ")
Comment: It's still send as normal message. Thanks for answering though.
Comment: Still normal message.
Comment: @SuperShaoBros Discord must have broke it when they added Slash Commands which uses a separate API. discord.py might update in future to add this function.
Comment: Ok thanks. I'll tell you if I succeed when it gets added.


A rectangular pig pen is built against an existing brick fence. $24$ m of fencing was used to enclose $70$ m$^2$. Find the dimensions of the pen

Question: A rectangular pig pen is built against an existing brick fence. $24$ m of fencing was used to enclose $70$ m$^2$. Find the dimensions of the pen.
If $2L+2W=24$ and $LW=70$
$2L+2W=24$ to $2L=24-2W$ to $L=12-W$
Substitute the answer into: $W(12-W)=70$ to $12W-W^2=70$ to $W^2-12W+70=0$
Quadratic formula with $a=1, b=-12$ and $c=70$ we get $\frac{12 \pm \sqrt{-136}}{2}$ and I cannot seem to go further than this. What can I do now?
If you have another way of solving this, I'd appreciate it if you'd share it with me too.
Ok I found a way to solve this.
$L+2W=24$ and $LW=70$
$L=24$-$2W$
Substitute into = $W(24$-$2W$)=$70$
$-2W^2$+$24W$-$70$=$0$
$W^2$-$12w$+$35$=$0$
W is 7 or 5.
So, $L$=$24-$2$\cdot $7
$L$=$10$
Or
$L$=$24-$2$\cdot $5
$L$=$14$
Answer: $7$ m by $10$ m or $5$ m and $14$ m.
Comment: If it's against a brick well you don't need to use any fencing for the side.  Your perimeter includes both fencing are brick so $2W + 2L =\text{fencing} + \text{brick wall}= 24+\text{however much of the brick wall you choose to use}$.  HINT: make a better equation than the one I did.
Comment: @Ibti No, $2W+2L=24$ does not correctly model your problem.  You need two "arms" of the fence to extend out from the brick wall, but you only need one stretch of fence to connect the two arms.  The brick wall connects the base of the two arms and doesn't require any fencing.
Comment: Think of it this way.   The brick wall will act as one of the sides.  So you only need the fencing for $3$ of the $4$ sides.  You don't have $24 = Perimeter = 2W+2L$.  You have $24 = Part\ of\ the\ Perimeter = 3\ out\ of\ the\ 4\ sides=???????$.
Comment: @Ibti: $L+2W=24$ because, as everyone is saying, you need fencing for only three sides, the fourth side is the brick fence.
Comment: Its against a brick fence on one side
Comment: @ArcticChar Yes, it is.
Comment: Your answer would work just as well as if the farmer were building it in the middle of a field (which is impossible as the ideal shape is a square-- well actually a circle-- and $6^2=36 < 70$-- [and if he made a circle $\pi r^2=\pi \times (\frac {Circumference}{2\pi})^2=\frac{144}\pi < 70$]).  You need to work the brick wall into this.
Comment: @fleablood This is supposed to be in the shape of a rectangle actually. Not a circle.  I'm sorry but I am so lost right now. 2W+2L=24+?
Comment: Sorry about the circle and square stuff.  I can see in hindsight it'd be confusing.  But the point is you need to take the brick wall into acount.  It is one of the sides.  So you either have $2W + 2L = Perimeter = 24 + \text{the brick wall side}$ or $24 = Fencing = \text{the sum of 3 of the 4 sides}$
Comment: Hint.   We will use the brick wall for either the length or the width of one side of the pen.  It doesn't matter which variable we use.  Let say one Width, $W$, of the pen will be the brick wall.... so.....
Comment: Welcome to MathSE.  This [Mathjax tutorial](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) explains how to typeset mathematics on this site.
Comment: Draw a picture of the pen.   Mark the side against the brick wall as $x$.  Mark the side opposite the brick wall as $x$ (it's a rectangle so that side opp the wall is equal).  Mark the other two sides $y$ (its a rectangle so the other two sides are equal).  Now.  What is the proper formula for you $24$ feet of fencing (that covers the side opposite the wall and the two other sides).
Comment: @fleablood 2L+2W=24+ $\frac{3}{4}$ ?
Comment: @Vasili Thank you! I was about to add this.
Comment: Nobody has remarked that the fact that the wall is with bricks has not been exploited. Had it been in straw or sticks, would the answer have been the same. And I sign;  :):):) ? Hi, Walt !
Comment: @fleablood I truly appreciate your efforts with the hints! Thank you so much to everyone!
Answer: We are told that a rectangular pig pen is built against a wall.  That means three sides of the rectangle are bounded by a fence, while the fourth side of the pen is bounded by a wall.
In the diagram, the thick side represents the wall, while the thin sides represent the fence.  We are told that $24~\text{m}$ of fencing are used.  Hence,
$$24~\text{m} = l + 2w \tag{1}$$
We are told that the area of the rectangle is $70~\text{m}^2$.  Hence,
$$70~\text{m}^2 = lw \tag{2}$$
Solve equation $1$ for $l$.  Substitute the resulting expression in the equation for the area to obtain a quadratic equation in $w$.  Solve it for $w$.  Since $w$ represents the width of the pen, discard any solutions for $w$ that are not positive.  Substitute your value(s) for $w$ into the equation you obtained for $l$ to find the corresponding value for $l$.
Comment: Your revised solution is correct.
Comment: I really needed a vivid mental picture of the question after being confused. Thank you truly much!


Understanding Lens space in Hatcher's Algebraic Topology

Question: Update: I put my understanding in the answer.
If you find any mistakes, please let me know. Thanks for your time.

This is from Hatcher's Algebraic Topology, Example 2.43: Lens Spaces, page 144--146.
Given integer $m > 1$ and integers $l_{1}, \ldots, l_{n}$ relatively prime to $m$.
Define action of $\mathbb Z_{m} = \langle \rho \rangle$ on $S^{2n-1} \subset \mathbb C^{n}$ by $\rho(z_{1}, \ldots, z_{n}) = (e^{2\pi i l_{1}/m} z_{1}, \ldots, e^{2\pi i l_{n}/m} z_{n})$.
Lens space $L = L_{m}(l_{1}, \ldots, l_{n}) := S^{2n-1} / \mathbb Z_{m}$.
Devide unit circle $C$ in $n$-th $\mathbb C$ factor of $\mathbb C^{n}$ by taking points $e^{2\pi ij/m} \in C$ as vertices, $j = 1, \ldots, m$.
Joining the $j$-th vertex of $C$ to unit sphere $S^{2n-3} \subset \mathbb C^{n-1}$ by arcs of great circles in $S^{2n-1}$.
All these arcs form a $(2n-2)$-dimensional ball $B_{j}^{2n-2}$, which is homeomorphic to $D^{2n-2}$ and bounded by $S^{2n-3}$.
Similarly, joining the $j$-th edge of $C$ to $S^{2n-3}$ gives a ball $B_{j}^{2n-1}$ bounded by $B_{j}^{2n-2}$ and $B_{j+1}^{2n-2}$.
Rotation $\rho$ takes $S^{2n-3}$ to itself while rotating $C$ by angle $2\pi l_{n} / m$,
hence $\rho$ permutes the $B_{j}^{2n-1}$'s and $B_{j}^{2n-2}$'s.
For $r$ s.t. $r l_{n} = 1 \bmod m$, $\rho^{r}$ takes each $B_{j}^{2n-1}$ and $B_{j}^{2n-2}$ to the next one.
$(r, m) = 1$, $\rho^{r}$ is a generator of $\mathbb Z_{m}$.
We may obtain $L$ as quotient of one $B_{j}^{2n-1}$ by identifying its two faces $B_{j}^{2n-2}$ and $B_{j+1}^{2n-2}$ together via $\rho^r$.
The two faces $B_{j}^{2n-2}$ and $B_{j+1}^{2n-2}$ are identified via a reflection across $B_{j}^{2n-1}$ fixing $S^{2n-3}$, followed by a rotation.
My question:
$1$. What's the relation of these $B_{j}^{2n-1}$'s? Do we have $\bigsqcup_j B_{j}^{2n-1} = S^{2n-1}$?
$2$. Since $B_{j}^{2n-2}$ and $B_{j+1}^{2n-2}$ identified together via $\rho^r$, where does that reflection come from?
Answer:
In the first picture, I visualize $S^{2n-3}$ as $S^0$ (I really doubt the legitmacy of this, since $S^0$ is not connected and other $S^n$'s are connected), visualize $S^{2n-1}$ as $S^2$, $B_j^{2n-2}$ and $B_{j+1}^{2n-2}$ as arcs in $S^{2}$ connecting "north pole" and "south pole" along great ciecle, and region between them is $B_j^{2n-1}$ in the second figure.
In the third picture, I visualize $S^{2n-3}$ as $S^1$, $B_j^{2n-2}$ and $B_{j+1}^{2n-2}$ as upper and lower disk $D^{2}_+$ and $D^{2}_-$.
Arcs in red, green, yellow and purple are identified respectively.
As far as I understand right now, the unit circle $C$ in the $n$-th $\mathbb C$ factor is vertical to $S^{2n-3}$, so arcs along graet circles in $S^{2n-1}$ from points $e^{2\pi ij/m}$ $(j=1,\cdots, m)$ to points in $S^{2n-3}$ yield $(2n-2)$-dimensional balls $B_{j}^{2n-1}$, which form an equal division of $S^{2n-1}$.
$\rho^r$ is a generator of $\mathbb Z_m$ and takes each $B^{2n−1}_j$ and $B^{2n−2}_j$ to the next one, so we can obtain $L$ as quotient of only one $B^{2n−1}_j$ by identifying its two faces $B^{2n−2}_j$ and $B^{2n−1}_{j+1}$ via $ρ^r$.
Since $\rho$ acts on different coordinates respectively, we can factorize $\rho^{r}$ as $\rho_{2} \circ \rho_{1}$.
$\rho_{1}$ is $\rho^{r}$ restrcting on last $\mathbb C_{n}$ factor, producing a reflection from $B_{j}^{2n-2}$ to $B_{j+1}^{2n-1}$ fixing $S^{2n-3}$.
It's indeed a reflection since the unit circle $C$ in the $n$-th $\mathbb C$ factor is vertical to $S^{2n-3}$, and $B_{j}^{2n-2}$ is formed by arcs along great circles in $S^{2n-1}$.
$\rho_{2}$ is $\rho^{r}$ restrcting on $S^{2n-3}$, producing a rotation on $S^{2n-3}$.