What is the technical term for the note names C, D, E, F, G, A, and H?

Question: I'm trying to find out whether my knowledge of the theory is correct, so this question might look a bit silly.
There's the term pitch. Pitch allows objectively tell whether two sounds are equal, and which one is higher (if not). This can be expressed using two approaches:

using frequency of the sound (e.g., 440Hz is objectively lower than 441Hz, and objectively equal to 440Hz); this allows arbitrary precision, and easy to operate with for a computer.
using human terms (for example, F4 is higher than C♯4, and lower than A♭4); this is precise up to the difference between two adjacent alterations.

The problem I'm facing at this moment is related to the second approach. It is obvious for me, that there are three entities needed to fully define a pitch:

octave (exact portion of pitch space, from C to the next H),
tone (C, D, E, F, G, A, or H), and
alteration (♯, ♭, ♮, etc.).

My concerns is that I wasn't able to find usages of the word "tone" in that sense. So my question is whether this is the correct term for this entity. If it is not, which one is?

In this question the OP calls this entity using the term principal note, but I think it is even more confusing, since notes have pitch, not the opposite. Also, there are no other usages of this term in this sense.
The closest thing I was able to find is pitch class, but it is still different: for example, D♭ is not a separate tone (it is one of the possible alterations of D), but it forms its own pitch class, along with all the other D♭'s (see the link for a better definition).
Comment: I don't see how this could actually be a useful notion. I think the term you may really be looking for is _scale degree_, but that would be Ⅰ Ⅱ Ⅲ Ⅳ Ⅴ Ⅵ Ⅶ rather than C D E F G A B. (Side note: many languages use "H" for the note between A and C, but in English it's B.)
Comment: When I see H in musical note names, I immediately think German Notation and the BACH motif, where B = Bb and H = B.
Comment: To clarify: are you trying to classify *absolute* pitches, with no relation to any particular key, mode or scale? If so, then why do you not accept "pitch class"? Your system divides "pitch class" into "tone" and "alteration" but no such division is sensible. In your system, going up by, say, a major 3rd from a "tone" gives a "tone" A, E or B (H if you prefer) if you start from the "tone" F, C or G, but a pitch which is not a "tone" if you start from another "tone". Don't privilege certain pitches. Instead, use a line of fifths ...,A♭,E♭,B♭,F,C,G,D,A,E,B,F♯,C♯,G♯,D♯,...
Comment: Aren't you just talking about letters? It's the letter or letter name of the pitch.
Comment: @JohnWu: I'm trying to define this attribute of pitch
Comment: Yes, and it's called the *letter.* We're talking about notation here. When you notate a pitch using these conventions, there is a letter name, an octave number, and an accidental. I am not sure why this isn't obvious. Or is there a specific reason you don't believe that name to be suitable for your purposes?
Answer: I agree that there is a lack of a good term. Note is a poor choice, not only because, as you say, "notes have pitch, not the opposite," but notes also have duration. If asked, "what are the notes?" You could just as easily answer, "whole notes, half notes, quarter notes..." as "A, B, C..."
I don't think there is a formal term, though "note letters", "white keys", or "the naturals" would probably be well understood (in English). You can get the meaning from context in the question you linked, where the OP calls it "principal tone". But tone can also mean other things (whole step, timbre, e.g.).
The class of C, D, E, F, G, A, H/B is a useful notion in software that models music, and I would argue generally as well. A class (in the computer science sense) called ScientificPitch (to distinguish it from other meanings of "pitch" such as frequency, which you mention) might have properties like MidiNote, NoteLetter, PitchClass, Accidental (or Alteration), StatedOctave, and AbsoluteOctave. The notes shown below:

...share the same pitch class, MIDI note, and absolute octave, but they do not share note letters, stated octaves, or scientific pitches. Given MIDI note 60 or the-white-key-called-middle-C, how does software—or indeed a person—know whether to render the pitch as B♯3 (H♯3?), C4, or D♭♭4? You can only do so if you're given context or told something like, "in this case, use note letter C."
For what it's worth, "Note Letter" is the term I've used in my own software.
Answer: Historically, the idea to identify pitch with a letter or solfege name is part of an idea called: gamut. But I think that meaning is really a reference to the whole set in connection with diatonic pitches.
The modern term for a pitch and it's related higher and lower octaves is: pitch class.

D♭ is not a separate tone (it is one of the possible alterations of D)

Certainly Db and D are separate tones. The question is just what labels to use in the nomenclature you have made.
From the wiki article:

Important to musical set theory, a pitch class is, "all pitches related to each other by octave, enharmonic equivalence, or both."
Note that in standard Western equal temperament, distinct spellings can refer to the same sounding object: B♯3, C4, and Ddouble flat4 all refer to the same pitch, hence share the same chroma, and therefore belong to the same pitch class; a phenomenon called enharmonic equivalence.

I think the point then is D and Db are different pitches and it doesn't matter how you spell them to classify them in a pitch class. According to the points above Db and C# belong to the same pitch class. Your "tone" concept says C# is a different "tone" from D, but Db is not a different "tone" from D. That runs contrary to the meaning of pitch class.
My suggestion is to just use established terms or plain English labels:

octave has a clear, established meaning in scientific pitch notation and is just a number.
the gamut A B C D E F G are just letters, call that attribute letter. I have also seen the terms "name" and "letter name" used in music theory writing.
♯ ♭ ♮, etc. are called accidentals, just call that attribute accidental.

I kind of suspect this is about a computer program. Is so, you could have a "tone" object with attributes: octave, letter, accidental. The reading of those labels would be perfectly clear with no misuse of terms.
Comment: If this is indeed about a computer program, and if we may assume a mean-tone temperament, then specifying pitch needs 2 (not 3) attributes: octave and pitch class. Pitch class denotes position x on a line of fifths .,A♭,E♭,B♭,F,C,G,D,A,E,B,F♯,C♯,G♯,D♯,.. Anything else means that transposing a piece of music will not be straightforward. From x you can obtain the letter name (from x mod 7) and the alteration (from x/7 or something similar) but the letter name and alteration are not fundamental; pitch class is.
Comment: @Rosie, yes you could have just octave and pitch class. But I don't see why a tone object couldn't have a 'pitch_class' method to use when transposing along a line of fifths. Ex. $tone->pitch_class() would return `Eb`, etc.
Comment: I've only made one such program. It made chords or scales of various types on a given tonic. I kept letter and accidental as separate attributes and used methods that counted on either a 7 step diatonic series (the letters) or 12 step chromatic series. But the purpose wasn't transposing. It took a tonic and then intervals like `M2,M3,P4`, etc. as input.
Comment: I'd say that working out the name of the pitch which is a particular interval above a specified pitch (the tonic) is transposing -- it's transposing the tonic. OK, delete the words "a piece of music" from my earlier comment -- here, it's just transposing one pitch.
Comment: It seems to matter if the transposing is diatonic or chromatic. If it's diatonic, it seems easier to work with 7 steps and 12 for chromatic. In my code I handled things with numeric values and the spellings were for final printing. Anyway, the question wasn't about how to program, it was simply what to call `A B C D E F G`.
Answer: The vernacular term is Note. Regardless of technical nuances, all musicians know what "note" means in the context you are referring to. IMO nothing more is necessary.
Another term, not particularly technical, that you'll find in the introduction to every theory book, is Musical Alphabet, when referring to the group at large.
However Musical Alphabet includes only C-D-E-F-G-A-H, while Note also includes accidentals - Eb is a different note than E.
Comment: At a gig, I wouldn't fuss over the nuance between C, the letter used to name notes, and C (natural), the note. But, if communication is key, it can't hurt to ask about how to refer to these separate concepts unambiguously. Sometimes it does matter.
Comment: @Stinkfoot, when the OP brings _pitch class_ into the question, I expect to use technical terms, and use them correctly. This isn't a gig, it's a _music theory forum!_
Comment: Some - like me - consider _note_ to be some written or notated thing. Basically, a pitch with a rhythm value. Tone would be just the pitch or scale degree info.
Comment: I speak with commonly understood terms like: leading _tone_, tendancy _tone_, or _tone_ deaf, etc. Tone is used to mean pitch all the time as discussed here: https://music.stackexchange.com/questions/3262/. Using your vocabulary isn't arcane.
Comment: @trw - Agreed. But reading way too much into this- What I said was very simple: When you talk, you call it a **note**. Say you're working something out - pianist plays a lick, you want to nail it on guitar but one **note** you're not sure of. Ordinarily, you'll play out as much as you've got and when you get to the dubious **note**, you say _and what's that **note**? I can't quite hear it..._ Pretty simple IMO.
Comment: Sure, but that's not the context of the OP's question. The OP asked for a technical term to distinguish the concepts without being ambiguous. "Note" doesn't do the job.
Comment: Just to clarify, the communication means are irrelevant here, since we're talking in a context of a computer program (as many have guessed correctly) and object-oriented design.With that said though, a concept of **tone** (in _my_ sense of this word) might still be useless, compared to a more powerful **pitch class** (the "2 entities instead of 3" thing). Nevertheless, knowing the correct term, if it does exist, is pretty useful by itself.
Comment: Also worth mentioning that the concept of **pitch class** doesn't hold the information about visual representation at the staff (only an audible property), as @trw pointed out in their answer.
Comment: @MichaelCurtis - as a musician, how do you speak? We call it a _note_. I've never heard anybody call it anything else: _Play that **note** again._ **Communication** is the key, not the some arcane academic definition.
Comment: @MichaelCurtis - that's how you speak at a gig or session?
Comment: @trw - _"Note" doesn't do the job_  - IMO since everyone generally knows what **Note** means, it does do the job - that's what it's called - _**A Note**_.
Comment: @MichaelCurtis - as stated:  IMO since everyone generally knows what Note means, it does do the job - that's what it's called - A Note.
Answer: Well, if you are really talking about the set (in strict mathematical sense) which the entities C, D, E, F, G, A and H belong, the answer will be the scale - because it's a set of notes (in your case it will be C major, as well as A minor, H Locrian etc.).
But you probably have meant the other thing — speaking in the language of computer science, the class of objects like C or D. Yes, you're likely right that this has no standard notion, since the separation of notes and keys into "white" and "black" ones has mostly historical reasons (since in the early days of notation, namely in the Middle Ages, the diatonic scale was the only used one, and the only difference was in the now-7th degree "B", which can be either "soft"/"round" (♭) or "hard"/"squared" (♮) — so, that's the reason for writing B and H respectively). Now, in the days of equal temperament, chromaticity and scales based on different notes, notes like E and E♭ "have equal rights", so E♭ is now not just E with a flat attached to it, but a note on its own; we can invent an own letter to it, for example writing S (from the syllabic Eastern European notation Es), so there would be no more illusion that this is not the note on its own.
So, likely the best notion for this (i.e. a note letter without the accidental) will be just "letter" (if you use C-D-E-F-G-A-H) or "syllable" (if you use do-re-mi-fa-sol-la-si).
Comment: @DmitryParzhitsky Yes, it's quite useless to split the note name (pitch class) into a letter and an accidental (outside the context of a scale and/or a key).
Comment: In another case of the letter S being used for E Flat, there's the DSCH motif (D-E flat-C-B), which is reasonably common in Dmitri Shostakovich's works and rising in popularity elsewhere.
Comment: @Dekkadeci yes, it's actually very common to use E-flat as S in such "musical signatures"
Comment: @trolley813 Yes, _class_ is what I really mean. Good catch!
Comment: @trolley813: Does your answer mean, that in order for me to refer to a tone (in the common sense of this word), I would have to do it in the context of a tonality ("the third step of C major" would be "E"; and "the fifth step of A♭ major" would be "E♭")? This would make pitch a compound entity of **note** and **octave**, — 2 entities, instead of 3. And without tonalities, I'd have to use terms like "letter", "character", or "symbol", which are not musical terms, but rather from linguistics. Am I going in the right direction with these thoughts?
Comment: _the answer will be the scale_ - not correct. A set has no order, a scale most certainly does.(But that is part of the reason I edited the language of the question and removed "set".) In addition, there are countless scales but the OP isn't looking for that usage.
Answer: The term for the meaning of the  7 alphabetical letters used for the notes and their pitch respectively for  the steps of the key scales  is "absolute note names" corresponding to the fixed do in opposite to the "relative note names" corresponding to the movable do, (the alterations marked by sharps and flats for the 5 halftones used for the 12 keys and the 12 tone scale.)
The absolute note names  stand for a scale tone (which pitch is indicated: the octava by the letters of the alphabet A,B,C... and   a,b,c...  or by adding an Arabic number like an C1, C2, C3 ... or the sign c', c'', c'''.
http://www.flutopedia.com/octave_notation.htm
https://en.wikipedia.org/wiki/Musical_note


Find the maximal domain and range of $f(x) = \ln(x^2 - 7)$

Question:
Find the maximal domain and range of:
$$f(x) = \ln(x^2 - 7)$$

I reasoned that the domain can be found by finding the values of $x$ such that $x^2 - 7 > 0$ so that the logarithm is defined. So:
$$x^2 > 7\\
x > \pm \sqrt{7}$$
Shouldn't I have arrived at $x > \sqrt{7}$ and $x < -\sqrt{7}$ somehow? From inspection I can see this, but I couldn't seem to understand why I didn't arrive at that algebraically.
Also, by inspection, I would guess that the range is $\{y \in \mathbb{R}\mid y > 0\}$. Is it standard to just derive this from a graph? or should I discuss the limiting behaviour as $x \rightarrow \pm~ \infty$ and as $x \rightarrow \pm\sqrt{7}$ from $+$ and $-$ respectively?
Answer: For the domain, your reasoning is correct, but
$$\begin{align*}x^2 > 7 \implies |x| > \sqrt{7} & \implies -x > \sqrt{7} \; \text{or }\; x > \sqrt{7}\\
& \implies x < -\sqrt{7} \; \text{or } \; x > \sqrt{7},\end{align*}$$ as you were expecting.  You just skipped a step when you wrote $x < \pm \sqrt{7}$, forgetting to reverse the inequality when you moved the negative across.
For the range, this is all the values that $\ln(x^2 -7)$ can take, so you could say that it goes to $-\infty$ as $x \to \sqrt{7}$ from the right and as $x \to -\sqrt{7}$ from the left.  It also goes to $\infty$ as $x \to \pm \infty$.  So the range is all of $\mathbb{R}$.
Answer: You can break $x^2-7 > 0 \Leftrightarrow (x-\sqrt 7)(x+\sqrt 7) >0$ in two cases :
1) $(x-\sqrt 7)>0 ~\text{and}~(x+\sqrt 7) >0$
2) $(x-\sqrt 7)<0 ~\text{and}~(x+\sqrt 7) <0$
So , domain should be :
$x \in (-\infty,-\sqrt 7) \cup (\sqrt 7 ,+\infty)$
Answer: $x^2-7>0$ means that    $x \in (-\infty,-\sqrt 7) \cup (\sqrt 7 ,+\infty)$
Comment: Please use $\LaTeX$ for the posts you make.
Comment: So, what does $x^2 - 7 > 0$ mean?
Comment: it means that  in logarithm  argument can't be   negative  or 0
Answer: Your domain appears to be in the set of Real Numbers - the domain is x is an element of the Real Numbers less than the negative square root of seven or greater than the postive square root of seven.
If you wish your domain to be in set of Complex Numbers, try it out and see what Complex values of x must be excluded. What is the range?
Try it for x as an element of the Integers. What is the range?
What does "maximal" mean in these cases? Maximal domain is the domain which is the super set of all posible domains - in other words, the maximal domain is the domain which has all possible domains as its subsets. For example, you may choose the domain with only the positive values. This is a subset of the maximal domain.


How can I send parameter with getters in nuxt?

Question: I want send id with $route.params.id in getters but it does not work!
In my component I have blogs object; I want save this.$route.params.id in blogId and then pass it with my getters method like this:
created() {
  const blogId = this.$route.params.id;
  console.log(blogId); ////1
  this.blog=this.$store.getters.getBlogById(blogId);
  console.log(this.blog);
},

but
console.log(this.blog) is undefined
when I send a number like this:
$store.getters.getBlogById(2)
it works and console.log(this.blog) print my object
What should I do?
my getters:
const getters = {
  allBlogs: state => state.blogs,
  getBlogById: (state) => (id) => {
    return state.blogs.find(blog => blog.id == id)
  }
}

Comment: Could you provide the code of your getter?
Comment: const getters = {
    allBlogs: state => state.blogs,
    getBlogById: (state) => (id) => {
        return state.blogs.find(blog => blog.id === id)
    }
}
Comment: Are you certain you have an item in `state.blogs` where `id === 1`? `.find` will return `undefined` if it doesn't find an item in the array that matches the condition.
Comment: yes yes , i am sure
Comment: What if you do `console.log(this.$store.getters.allBlogs())` under `console.log(blogId)`?
Comment: i get this error
this.$store.getters.allBlogs is not a function
Comment: Is your module namespaced?
Comment: Sorry try `this.$store.getters.allBlogs` (without parens).
Answer: const blogId = this.$route.params.id - is a string, and in getter your are using ===, I think that's the reason.
Comment: why `===` not works in getters but `==` works?
Comment: Because blogId from route is a string and blog.id in getter is a number. That's why '===' operator returns false but '==' operator returns true. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality


sendmail: how to add X-RBL-Warning

Question: I am running sendmail on CentOS.
I am interested if anyone knows how to add a X-RBL-Warning for incoming messages (without rejecting the mail).  I just want to add the X-RBL-Warning header so that our downstream filters can work with it.
Thanks,
John
Answer: You can do that by using MIMEDefang (both with SpamAssassin and not).

sendmail: how to add X-RBL-Warning


A question about the Cauchy Integral Formula

Question: http://www.uio.no/studier/emner/matnat/math/MAT2410/h14/supplementarynotes/cauchy-starshaped.pdf
I am trying to prove the Cauchy Integral formula for star shaped regions which will use one of the ideas in the notes posted.
On page 2, the last paragraph says that
If, for each fixed  $ \epsilon > 0$, we let the width $\delta$ of the corridor go to zero, the contributions
to the integral of the two sides of the corridor cancel due to the continuity of $g$.
This seems conceptually right, but how to write it down rigorously? Where does the continuity of $g$ come in?
Can anyone give me any idea on how to write down the explicit formulas of the integral so that I can actually see how to use the continuity of $g$?
Comment: The corridor can have a $0$ width, I don't see the problem. And if you assume $f(z)$ to be continuously complex differentiable, you might want to look at [those comments](http://math.stackexchange.com/questions/1940621/more-direct-proof-of-cauchys-integral-formula-for-simply-connected-domains) for showing directly $\int_{|z| = R} \frac{f(z)}{z-a} dz = \int_{|z-a| = \epsilon} \frac{f(z)}{z-a} dz$
Answer: Continuity of $g$ at $z$ basically means that for any $\epsilon > 0$, we can find a $\delta$ where all the $g(\zeta)$ are within $\epsilon$ of $g(z)$ if $\zeta$ is within $\delta$ of $z$.
Thus as the width of the corridor goes to zero, the continuity of $g$ means $g(\zeta)$ on the inner boundary and the $g(\zeta)$ on the outer boundary becomes as close as we'd like and hence the difference between the two integrals vanishes.
For a discontinuous function, you have no such guarantee. It is possible to have a jump in the function where $\zeta \to z$ does not imply $g(\zeta) \to g(z)$.
Comment: Yes, those functions tend to be very close by continuity, but they are on different lines $r$ and $r'$, the sum of those two integral would be $\int _r f - \int _{r'} f$, how do I estimate this difference?


Finding values by using partial key name in a Redis Sorted Set

Question: I have a sorted set which has the following key name and values :
zrange bargraph:branch:1:category:2:product:4
1) "76"
2) "55"
3) "10"
4) "84"

Is there a mechanism in redis where I can use a wildcard character(maybe an ?) when using zrange to still get the same values? In other words, does redis support zrange bargraph:branch:1:category:2? If not, how best can I get all the values if I only know the category id(2) and not the product id(4) without using a different sorted set?
Answer: Here is an updated answer for 2015.
If you can upgrade Redis above 2.8, the SCAN command with MATCH will work for this. Before that version, not so much, and do NOT use the KEYS command except in a development environment.
http://redis.io/commands/scan
Example on command line:
$ redis-cli
127.0.0.1:6379> scan 0 match V3.0:*
1) "0"
2) 1) "V3.0:UNITTEST55660BC7E0C5B"
   2) "V3.0:shop.domain.com:route"
   3) "V3.0:UNITTEST55660BC4A2548"
127.0.0.1:6379> scan 0 match V1.0:*
1) "0"
2) (empty list or set)
127.0.0.1:6379> scan 0 match V3.0:*
1) "0"
2) 1) "V3.0:UNITTEST55660BC7E0C5B"
   2) "V3.0:shop.domain.com:route"
   3) "V3.0:UNITTEST55660BC4A2548"

Example in PHP:
// Initialize our iterator to NULL
$iterate = null;

// retry when we get no keys back
$redis->setOption(Redis::OPT_SCAN, Redis::SCAN_RETRY);

while ($arr_keys = $redis->scan($iterate, 'match:*')) {
    foreach ($arr_keys as $str_key) {
        echo "Here is a key: $str_key\n";
    }
    echo "No more keys to scan!\n";
}

Note, php code is not tested and from the core documentation for example here. Production code would need to be modified depending on the keys needed to look up.
For those on Ubuntu here are the instructions to upgrade php5-redis:

Download the 2.2.7 package here: http://pecl.php.net/package/redis
$ php -i | grep Redis
Redis Support => enabled
Redis Version => 2.2.4
Follow instructions in README to phpize, configure, make install
Create a symlink for command line cli package: cd /etc/php5/cli/conf.d && sudo ln -s ../../mods-available/redis.ini 20-redis.ini
$ php -i | grep Redis
Redis Support => enabled
Redis Version => 2.2.7
Answer: As you've mentioned, KEYS is inefficient because the engine performs a linear scan for keys.
Unfortunately, there is no wildcard solution such as you are looking for
Consider using a SET for your product keys per category:
SADD bargraph:branch:1:category:2 1 2 3 4
to fetch all set category members do:
SMEMBERS bargraph:branch:1:category:2
If you don't care about summing your scores, or have different items per a sorted set, you can do a union of your per product sorted sets like this:
ZUNIONSTORE bargraph:branch:1:category:2:product:all 4 bargraph:branch:1:category:2:product1 bargraph:branch:1:category:2:product2 bargraph:branch:1:category:2:product3 bargraph:branch:1:category:2:product4
and now you can zrange bargraph:branch:1:category:2:product:all
You pipeline the above operations for better performance


How to get in class variable from outside class

Question: i have a problem. how to get a variable from outside class in the class?
<?php
    include("Configuration.php");
    $MySql = new MySql();
    class MySql{
        public function Connect(){
            mysql_connect($ip, $login, $password); //error Undefined variable: ip,login,password
        }
        function SelectDatabase(){

        }
    }
?>

Configuration.php:
<?php
$ip = "localhost";
$db = "website";
$login = "";
$password = "";
?>

Comment: This isn't related to your original question but please avoid using `mysql_...` Those functions have been deprecated.
Comment: Also: please use the `mysqli` interface - `mysql_connect` and friends are obsolete and will be removed from PHP soon. http://php.net/manual/en/mysqli.overview.php
Comment: Seems a shame/waste to use `mysql_` functions with a class.
Comment: http://php.net/manual/en/language.variables.scope.php
Comment: Why don't you just `include` inside the `Connect()` method?
Comment: This is basic syntax question. If you are in process of learning PHP, please read the OOP section in PHP manual.
Comment: Please **DO NOT** continue down this path. I have no idea what you're doing here, but using `mysql_query` in new code is ridiculous and writing your own ORM, if that's what this is going to end up as, is a complete waste of time. These things are hard to write correctly, especially if you're not intimately familiar with PHP. Before you do any more damage, consider using a
[development framework](http://codegeekz.com/best-php-frameworks-for-developers/) like [Laravel](http://laravel.com/) that provides all of this for you.
Answer: Either use global, or pass them in as parameters.
public function Connect(){
 global $ip, $login, $password;

public function Connect($ip, $login, $password){

Answer: Add it to the constructor.
   include('Configuration.php');
   $MySql = new MySql($ip, $login, $password);

And your MySQL class:
class MySql
{

    protected $ip, $login, $password;

    public function __construct($ip, $login, $password)
    {
        $this->ip       = $ip;
        $this->login    = $login;
        $this->password = $password;
    }

    public function Connect()
    {
        mysql_connect($this->ip,
            $this->login,
            $this->password);
    }

    function SelectDatabase(){}

}

Just a little tip for your further development. You probably wanna assign your connection to a property in the object, it's just good manners to close it again. It could look something like this:
class MySql
{

    protected $ip, $login, $password, $conn;

    public function __construct($ip, $login, $password)
    {
        $this->ip       = $ip;
        $this->login    = $login;
        $this->password = $password;
    }

    public function Connect()
    {
        $this->conn = mysql_connect($this->ip,
                                    $this->login,
                                    $this->password);
    }

    public function closeConnection()
    {
         mysql_close($this->conn);
    }

}

And yeah, as several others stated, mysql_connect() etc. is deprecated, but I see you're aware.
Comment: I prefer this method to my suggested ones. +1
Comment: @Fred-ii- You got a point. But my guess is that, when asking such a basic question, OP is in a learning-state and just kata-coding right now ;) So at the time something goes into production and not just sandbox, he's probably miles away using PDO anyway!
Comment: He knows a lot, so we better go with `$Lord_knows[]="You try";` - and that concludes our OT-conversation!
Comment: After all that work, why not just suggest a `mysqli_` solution instead? (wink) - Once OP gets a notice about `mysql_` functions being deprecated, would need to totally rebuild.
Comment: I'm just trying to save everybody a bit of time. ;)


Flipped view in RTCView for react-native

Question: I am using react-native-webrtc library for developing an application for video chat. When I local stream my video it displayed me flipped view of video in RTCView element.
Is there any argument I should have to pass with rtcview element? how can I solve this issue?
Answer: You can pass mirror option.
<code><RTCView streamURL={this.state.stream.toURL()} mirror={true} />
</code>
Please check react-native-webrtc github repo


How to sort a hashtable of class values by their property in c#?

Question: I have a Hashtable in C# like.
Hashtable people = new Hashtable();
people.Add(0, new Person("Jimmi", "Hendrix"));
people.Add(1, new Person("Bob", "Dylan"));
people.Add(2, new Person("Jim", "Morrison"));

How would I sort this hash by the people last name  with Linq?
class Person
{
    public Person(string firstName, string lastName): this(firstName, lastName, DateTime.Now)
    {}

    public Person(string firstName, string lastName, DateTime birthDate)
    {
        FirstName = firstName;
        LastName = lastName;
        DateOfBirth = birthDate;
    }

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime DateOfBirth { get; set; }
}

Comment: All has-table based types (Dictionary, HashSet, Hashtable) don't have concept of ordereing. If you clarify what you actually want to achieve someone may suggest more appropriate type or approach to achieve that.
Comment: Note that for code running against supported .Net framework (and not 1.x) using `Dictionary` would be better choice..
Answer: var result = people.Cast<DictionaryEntry>().OrderBy(kvp => ((Person)kvp.Value).LastName);

the result becomes OrderedEnumerable though, because putting back to Hashtable will forget the order.\
EDIT:
If you are looking for a way to enumerate the result and pull out the id's along with the Person information, this is how you do it:
// this is the original answer
var result = people.Cast<DictionaryEntry>().OrderBy(kvp => ((Person)kvp.Value).LastName);

// now convert it to an array
var listToIterate = result.ToArray();
foreach(var item in listToIterate)
{
    var id = item.Key;
    var person = (Person)item.Value;
}

Hope this helps...!
Comment: Sorry, never worked with OrderedEnumerables how would I iterate over this?
Comment: You can convert it to array with `ToArray()` or to list with `ToList()` at the end. To iterate.... `foreach(var item in result)`
Comment: @nebulus: simple - just invoke the `ToList()` method of the `IOrderedEnumerable` and assign the result to a variable. Then you can enumerate it as you would a regular list.
Comment: Argh. Let me edit @kurakura88's answer with the full solution that you are looking for.
Comment: Not bad! It works, last thing how would I sort it when the names have numbers, order should not be 1, 10, 2 but 1, 2... 10. Cheers!
Comment: LOL... ok, since you now understand how casting and linq ordering works, how about you think about how `Convert.ToInt32()` will fit into the grand scheme of things?
Comment: @code4life BTW, you don't really need to convert it to array to iterate though. I was mentioning the To Array in case if nebulus would like to store it into more known type.
Comment: Okay, Maestro. Thanks for your help.
Comment: @kurakura88: however, you should convert it - in order to ensure that deferred linq execution does not occur and to ensure that the ordering that you "snapshotted" remains pristine. The `ToArray` (the `ToList` is ok too) is a good practice to follow if you care about preserving the order.
Answer: You are using a non generic (IMO legacy) data type. So you will need to poke it a bit to get what you want.
people.Values.OfType<Person>().OrderBy(p => p.LastName);
First you want to sort the values, but that isn't generic, so use OfType. Now you can play with the standard Linq operators like OrderBy
Comment: @LeeCampbell: I wouldn't say "don't use HashTable because it's an outdated type". That's basically making a huge assumption that the problem domain that you are assuming is orthogonal to all problem domains in a global manner. The OP might be under specific constraints and TBH, it *is* an interesting problem, to extract a sorted list from a HashTable. It's exactly the sort of problem we may face when maintaining legacy code.
Comment: Okay, thanks... How do I iterate over that and still get the key pair?
Comment: As per Alexei's suggestion, dont use hashtable. It is an out dated type. Use Dictionary
Comment: Okay, I still don't get how to use this. I need to output this as and array and see the ids.


CDK An ApiMapping key may contain only letters, numbers and one of... error

Question: I am trying to create an API Gateway mapping with a slash, but the CDK is giving me a formatting error:
Error: An ApiMapping key may contain only letters, numbers and one of $-_.+!*'(),
The code I am using:
        apigatewayv2.ApiMapping(self, "AccountsGetBasePathMapping",
            api=accounts_get_api,
            domain_name=apigateway.DomainName.from_domain_name_attributes(self, "ApiMyDomainComApiGwCustomDomain",
                domain_name="api.mydomain.com",
                domain_name_alias_hosted_zone_id="xxxx",
                domain_name_alias_target="xxxx.execute-api.eu-west-1.amazonaws.com."
            ),
            api_mapping_key="accounts/get",
            stage=accounts_get_api_stage,
        )

However, if I try the same in the console the slash character is allowed:

Is this a limitation of the AWS CDK?
Answer: api_mapping_key means:
The path where this stage should be mapped to on custom domain
This is optional so it does not api_context_path as you put above accounts/get
For example: there are some APIs you want to separate, you can define:
On custom domain, you define api.mydomain.com/apiv1 so api_mapping_key in this case is apiv1,  acount path should be: api.mydomain.com/apiv1/account
Comment: If I want all my APIs to be available at / under the custom domain does this mean I don't need the api_mapping at all?


any representation is a group action but the opposite is not true.

Question: A group action is defined to be action of a group $G$ on a set X.
But a group representation is also defined to be the action of the group $G$ on a vector space $V$.
So in fact both the definition are same except some less condition on group action.
i.e., any representation is a group action but the opposite is not true.
Is it like that?
Answer: Yes, it is "like that". Every representation on a vector space is an action on the underlying set. There is an extra condition: the permutation of vectors corresponding to each group element must be a linear transformation.
That extra condition makes no sense when the  set $X$ acted on is just a set with no other structure. When it does have structure (perhaps it's a manifold) we usually require the action to respect that structure.


How to save the sate of my Activity

Question: I have an EditText followed by a list view under it.
So it works like this - when u type something in the edit text it shows items from the list which match the text above.
Anyway I need to save the state of list view. means if the user navigates away from this screen and comes back the list view should have the same state and the edit text should be filled with the same text. Hope u got it.
Please tell me how to achieve this.
Answer: Save your data in onPause(), and restore it in onResume() if needed.
Comment: Hi Stefan ! U know I am using these lines of code in my class -        @Override
    protected void onPause()
    {
    super.onPause();

    }

    @Override
    protected void onResume()
    {
    super.onResume();

    }
It does work this way. I mean it gives me the desired result, but can u give me a little insight into it that how it works ?
Comment: When another activity launches, onPause() gets called, so you can store the data you want to retrieve when returning to your activity. When your activity is reactivated, onResume() gets called and you can restore your data if you need to. You have to be more specific with your question if this is not the answer your looking for.
Comment: ok, but what happens when we say super.onPause(); and super.onResume();  Besides when another activity is launched, whether our activity calls onPause() or onStop() ?
Comment: super.onPause() calls the onPause method on your parent class.
Answer: You should save your edit text input string on (over ride those methods)
protected void onPause()

And when user returns, you just bind your string to edit text view on
protected void onResume()

http://developer.android.com/guide/topics/fundamentals/activities.html#Lifecycle

How to save the sate of my Activity


SFTP file download and upload permission

Question: I have folder /sftp/xyz, need to give download and upload permission for 'xyz' folder for user 'abc'.
User 'abc' should access only the folder /sftp/xyz.
I tried so many things but now the user 'abc' is able to access /home/, /sftp/ also able to edit files. Please help.
Comment: We can't guess what the system's current state is.
Comment: Why don't you just set that user's home dir to /stfp/xyz ?
Answer: This is because user abc has a home directory in /home, so they implicitly have access to that directory. If you want that user to only have access to /sftp/xyz, then make that their home directory and remove permissions to every other directory.
Using ACLs (Access Control Lists) is another option, but not recommended because they are definitely not necessary in this situation.


MCMC/EM limitations? MCMC over EM?

Question: I am currently learning hierarchical Bayesian models using JAGS from R, and also pymc using Python ("Bayesian Methods for Hackers").
I can get some intuition from this post: "you will end up with a pile of numbers that looks "as if" you had somehow managed to take independent samples from the complicated distribution you wanted to know about." It is something like I can give the conditional probability, then I can generate a memoryless process based on the conditional probability. When I generate the process long enough, then the joint probability can converge.and then I can take a pile of numbers at the end of the generated sequence. It is just like I take independent samples from the complicated joint distribution. For example, I can make histogram and it can approximate the distribution function.
Then my problem is, do I need to prove whether a MCMC converges for a certain model? I am motivated to know this because I previously learned the EM algorithm for GMM and LDA (graphical models). If I can just use MCMC algorithm without proving whether it converges, then it can save much more time than EM. Since I will have to calculate the expected log likelihood function (will have to calculate posterior probability), and then maximize the expected log likelihood. It is apparently more cumbersome than the MCMC (I just need to formulate the conditional probability).
I am also wondering if the likelihood function and prior distribution are conjugate. Does it mean that the MCMC must converge? I am wondering about the limitations of MCMC and EM.
Comment: EM is faster, it is non-Bayesian (not everyone loves Bayesian statistics) and in some cases it has less identifiability issues (it converges to a single *maximum* value while with MCMC approach you have a whole distribution that could be more complicated then point estimate) etc.
Comment: MCMC converges as $n \rightarrow \infty$ by definition. Rather then proving it you *diagnose* the convergence to check if your model has converged e.g. http://www.math.pku.edu.cn/teachers/xirb/Courses/QR2013/ReadingForFinal/MCMC/2291683.pdf or http://www.people.fas.harvard.edu/~plam/teaching/methods/convergence/convergence_print.pdf
Comment: EM is used for maximum likelihood or maximum a posteriori estimation but was initially described as ML algorithm and is commonly used in ML approach (see http://en.wikipedia.org/wiki/Expectation%E2%80%93maximization_algorithm).
Comment: For me using EM is non-Bayesian because it gives you a point estimate of your parameters of interest and does not quantify the full posterior distribution. With both EM and MCMC one can have a full probabilistic model with priors, latent and observed random variables but the inference is different. MCMC aims to characterise the full posterior distribution while EM gives does not convey the information of the full posterior distribution. For me a Bayesian is someone who uses the posterior distribution for decision making. However, this might be simplistic. I am also learning this stuff.
Comment: Even if you use EM for MAP estimation rather than ML, it is non-Bayesian for me because it does try to characterise the posterior distribution but only gets you the local mode of it.
Comment: @Tim Thanks for the reply! I think I previously do not fully understand MCMC will edit my problem later. But still have a problem, if MCMC must converge, I am wondering about MCMC's drawback compared with E-M.It seems E-M is more cubersome..
Comment: Like why most papers choose to use e-m for LDA, also when we are taking machine learning classes, we are learning e-m first but seldom do we learn mcmc.
Comment: @Tim  Ah I do not know why EM is non-bayesian, I up till now only use em algorithm for graphical model problems and I think they are all bayesian-related. Can you give me a common non-bayesian problem using em algorithm? many thanks!
Comment: @Luca Thanks for the explanation! Just to make it clear, does that mean the biggest difference MCMC and EM, is that we must have prior distribution of parameters, while for EM, we only need the conditional probability?(That means EM is not bayesian,since we do not assume prior probability and only get point estimation for parameters)
Answer: EM is an optimisation technique: given a likelihood with useful latent variables, it returns a local maximum, which may be a global maximum depending on the starting value.
MCMC is a simulation method: given a likelihood with or without latent variables, and a prior, it produces a sample that is approximately distributed from the posterior distribution. The first values of that sample usually depend on the starting value, which means they are often discarded as burn-in (or warm-up) stage.
When this sample is used to evaluate integrals associated with the posterior distribution [the overwhelming majority of the cases], the convergence properties are essentially the same as those of an iid Monte Carlo approximation, by virtue of the ergodic theorem.
If more is needed, i.e., a guarantee that $(x_t,\ldots,x_{t+T})$ is a sample from the posterior $\pi(x|\mathfrak{D})$, some convergence assessments techniques are available, for instance in the R package CODA. Theoretically, tools that ensure convergence are presumably beyond your reach. For instance, perfect sampling or rewewal methods.

MCMC/EM limitations? MCMC over EM?


SOLRCloud in JBOSS

Question: Has anyone shared step-by-step instructions on setting up SOLR Cloud in a 2-node JBOSS cluster. I've checked other newsgroups and only found similar questions but nothing detailed in terms of a wiki page or a blog with step-by-step instructions.
Comment: do you found anything relevant about that? thanks
Comment: did you find anything on this? I have the same question
Answer: There you go : http://wiki.apache.org/solr/SolrCloud%20with%20Jboss
It looks pretty simple and straightforward.

SOLRCloud in JBOSS


Flipping coins- percentages of heads vs tails

Question: If I flip a coin multiple times and count the number of time it fell on heads and the number of times it fell on tails and keep a track of them. In how many flips on average will the delta between percentage of heads and percentage of tails will be less than 0.1%?
Comment: It is not really a rephrasing, it is entirely different, and quite a bit easier.
Comment: I will rephrase the question- I want to check if a coin is fair(lands 50% of the times on each side. I assume that delta of 0.1% between them is fair). How many flips do i need in order to be 99% confident that the coin is fair?
Comment: Thanks Andre. So it is two questions i guess
Comment: For the second, it is well over a million.
Comment: @AndréNicolas can you show your calculation as an answer?
Comment: I cannot do that at this time.  It would not at all be an answer to the question as currently posed, it would be an answer to the very different question you asked in a comment. And if the original question were to change, and I knew it had changed, I could not answer it until morning, it is quite late here.
Comment: @AndréNicolas thanks. I posted it as a different question
Comment: The original question is quite interesting. There would be some initial inaccuracy using the normal approximation, but for the rest the method of indicator random variables would give a reasonably close answer. That question is about expectation rather than probabilities.
Comment: My reading of the original question is that a fair coin is flipped $n$ times giving $n$ observations of the cumulative $H$ and $T$ seen; then the number of times $\left|\frac{H-T}{H+T}\right| \lt \frac1{1000}$ is counted.  My calculations suggest that for $1$ flip, the expectation is $0$; for $10$ flips the expectation is about $1.71$; for $100$ flips about $7.04$; for $1000$ flips about $24.25$; for $10^4$ flips about $540.19$; for $10^5$ flips about $16663.55$; for $10^6$ flips about $483950.29$
Comment: The alternative rephrased question is at http://math.stackexchange.com/questions/1873620/checking-if-a-coin-is-fair
Comment: @AJ222: To be exact, are you asking for the number $n$ of trials such that if the coin has probability $1/2$ of landing heads, then with probability $0.99$ the ratio $\frac{|H-T|}{n}$ is $\lt 0.001$? If you want to calculate some other related probability, please be as clear as possible, so that I can give a precise answer in a comment.
Comment: In the above, $H$ is the number of heads, and $T$ the number of tails.
Comment: On the revised question, my calculations suggest that with a fair coin, $\mathbb{P}\left(\left|\frac{H-T}{H+T}\right| \lt \frac1{1000}\right) \approx 0.9900006$ for $n=6633001$ but about $0.989995$ for $n=6636000$, with any greater $n$ giving over $0.99$. Meanwhile a normal approximation (without continuity correction) of $(1000\Phi^{-1}(0.995))^2$ suggests $n \gtrsim 6634897$
Answer: 1) Interpreting the revised question as asking how many tosses $n$ of a fair coin are required to have the probability that $|H-T| \lt 0.001 n $ greater than or equal to $0.99$, where $H$ is the number of heads and $T$ the number of tails with $H+T=n$, this is equivalent to asking for $n$ such that $\mathbb{P}\left(-0.0005n \lt H-\frac12{n} \lt 0.0005n\right) \ge 0.99$ since if $H=\frac12{n}+0.0005n$ then $T=\frac12{n}-0.0005n$ and $H-T= 0.001n$.
It is typical to use a normal approximation to the binomial distribution for questions like this.  $H$ has a mean of $\frac12{n}$, a variance of $\frac14n$ and a standard deviation of $\frac12\sqrt{n}$.  So using $\Phi^{-1}$ as the inverse cumulative distribution function of a standard normal random variable, we have $\mathbb{P}\left(-\Phi^{-1}(0.995) \lt \dfrac{H-\frac12{n}}{\frac12\sqrt{n}} \lt \Phi^{-1}(0.995)\right) \gtrsim  0.99$ or  $\mathbb{P}\left(-\Phi^{-1}(0.995)\frac12\sqrt{n} \lt H-\frac12{n} \lt \Phi^{-1}(0.995)\frac12\sqrt{n}\right) \gtrsim 0.99$.
So we need to solve  $0.0005n \gtrsim \Phi^{-1}(0.995)\frac12\sqrt{n}$ which gives  $n \gtrsim (1000\Phi^{-1}(0.995))^2$ and since $\Phi^{-1}(0.995)\approx 2.575829$ this gives  $n \gtrsim 6634897$.
But this is only an approximation. We could use computer calculations of the binomial distribution to get exact answers, but there is an issue that due to rounding every thousand, the probability is not a monotonic function of $n$.  I believe that the smallest $\mathbb{P}\left(\left|\frac{H-T}{n}\right| \lt \frac1{1000}\right) \approx 0.9900006$ for $n=6633001$ but about $0.989995$ for $n=6636000$, with any greater $n$ giving over $0.99$.  So the normal approximation gives a reasonable answer.
2) The original question is actually slightly different, asking "In how many flips on average will the delta between percentage of heads and percentage of tails will be less than $0.1\%$?" Interpreting this as asking for the expected cumulative number of times in the $n$ tosses it is true that $\left|\frac{H-T}{H+T}\right| \lt \frac1{1000}$, it is possible to use linearity of expectation and to add up the probabilities of being in this interval.  For small values of $H+T$, it makes sense to use the binomial distribution as rounding matters: for example with $n \le 1000$ the probability is zero for odd $n$.
As I said in a comment while the question was closed, my calculations suggest that for $1$ flip, the expectation is $0$; for $10$ flips the expectation is ${2 \choose 1}\frac1{2^{2}}+ {4 \choose 2}\frac1{2^{4}}+ {6 \choose 3}\frac1{2^{6}}+ {8 \choose 4}\frac1{2^{8}}+ {10 \choose 5}\frac1{2^{10}}\approx   1.71$; for $100$ flips about $7.04$; for $1000$ flips about $24.25$; for $10^4$ flips about $540.19$; for $10^5$ flips about $16663.55$; for $10^6$ flips about $483950.29$.  For small $n$ the expected number is much smaller than $n$, but for very large $n$ most cases will fall in the relative small interval around the mean.
Answer: Great question! So let's look at the binomial distribution. We can represent the standard deviation with the equation $\mu_x = \sqrt{npq}$ and $p$ in our case is the probability of heads. This is $.5$. Same with tails. $n$ is the number of tosses. So $\mu_x = \sqrt{.5 * .5 * n} = .5*\sqrt{n}$
Our mean here is zero and our standard deviation is $.5\sqrt{n}$. Because we can apply the same rules as the normal distribution, if we had, let's say $10,000$ tosses, 68% will fall within 1 standard deviation, so $.5\sqrt{10,000}$ which is $50$. For 99% confidence, we would do 3 standard deviations, so for this would be $150$. So we can be 99% confident that the difference is equal to or less than 150 tosses. You can apply this logic to your problem to get the answer.
Note: I'm not an expert in this field so please do feel free to edit anything that isn't proper terminology.
Comment: Thanks. Andre says it should be over 1million. Do you understand why?
Comment: @AJ222 ah yes, because you have to use what I gave you to solve the problem at hand. You can solve for n by doing some algebra and saying that .001 (.1%) times n equals 3 * .5 * sqrt(n). I got 2.25 million as a final answer. Does it make sense how I solved for n here?
Comment: My answer (see comments on the question) using a normal approximation would be about $(1000\Phi^{-1}(0.995))^2 \approx 6634897$
Answer:
I want to check if a coin is fair(lands 50% of the times on each
  side. I assume that delta of 0.1% between them is fair). How many
  flips do i need in order to be 99% confident that the coin is fair?

For large n you can apply moivre laplace. So you approximate the binomial distribution by the normal distribution.
Let $p=\frac{X}{n}$, where $X\sim Bin(n,0.5)$. The equation becomes
$P(|\frac{X}n-0.5|\leq 0.001)=2\Phi\left(\frac{0.001}{ \frac{0.25}{\sqrt n}} \right)-1=0.99$
$\Phi\left(\frac{0.001}{ \frac{0.25}{\sqrt n}} \right)=0.995$
$\frac{0.001}{ \frac{0.25}{\sqrt n}} =\Phi^{-1}\left(0.995\right)$
$\frac{0.001}{ \frac{0.25}{\sqrt n}} =2.576$
$\sqrt n=2.576\cdot \frac{0.25}{0.001}$
$n=414,736$
Comment: If the  difference is to be $\lt 0.001$, the proportion of heads has to be between $0.4995$ and $0.5005$.
Comment: @callculus: In addition to the difference in interpretation of "the delta" there is a little problem with the $0.25$ of the answer. The standard deviation of the mean is $\frac{0.5}{\sqrt{n}}$, not $\frac{0.25}{\sqrt{n}}$.
Comment: Thanks. So is it 2m (see rb612's comment) or 400k?
Comment: From the result I got the number of tosses has to be at least $414.736$. Sure 2 million tosses is O.K. as well.
Comment: Thanks. I am looking for the minimal number of course
Comment: You´re welcome.
Comment: @AndréNicolas The stardardized random variable is $z_p=\frac{p-\pi}{\sqrt{\frac{p\cdot q}{n}}}$ Why  don´t you sleep ?
Comment: So you are suggesting that with $n=414736$ the probability of having $H-T$ between  $-414.736$ and $+414.736$ (i.e. $H$ between $207160.632$ and $207575.368$) is at least $0.99$.  I suspect that probability is closer to $0.48$
Comment: @Henry, my answer coincides with yours. If we use my equation and solve with the value provided, https://goo.gl/pGxuQT, we get a z-score of 1.28 (if I'm using my equation correctly) and this gives us around 80% probability.
Comment: @rb612: My answer (see comments on the question) using a normal approximation would be about $(1000\Phi^{-1}(0.995))^2 \approx 6634897$
Answer:
If I flip a coin "$2$" times... On average the delta between percentage of heads and percentage of tails will be less than $0.1 \%$. Thank you.

As It can be $\{HH \}$ or $ \{TT \}$ or $\{HT\}$ or $\{TH \}$
I went through a lot of sleeplessness because of this question randomly popping up somewhere I don't even remember now.
Comment: Not sure why this question just came alive again... but if you flip a fair coin twice, the difference between the percentage of heads and the percentage of tails is 100% with probability 1/2 and 0% with probability 1/2... so on average it is 50%.


Form is not submitted with arg() in URL

Question: I have a list of items. By clicking on an item I open a form at /items_form/123 where 123 is the itemid. When filling the form I use the arg() function to get the 123 and read some data from the database. No problem.
My problem is, when submitting the form, the default submit handler is not called.
When I open the form without the arg e.g. /items_form and submit this form, the submit handler is called.
Where is my missing link?
Here is my hook_menu:
<code>$items['items_form'] = array(
'title' => 'Item Form',
'page callback' => 'drupal_get_form',
'page arguments' => array('get_item_form'),
'access arguments' => array('access items_form content'),
'type' => MENU_NORMAL_ITEM, //Will appear in Navigation menu.
);
</code>
Any ideas?
Comment: You should use `'page callback' => 'drupal_get_form'` in your code.
Comment: Hi! Thank you. I just realized my fault and edited it. The page callback is now 'drupal_get_form' and the 'page arguments' is the name of my function. I cleared the caches, but the submit doesn't work. ;-(
Comment: Please add completed code for the form also.
Comment: Hi! Here is an example of the function used as submit handler
`function get_item_form_submit($form_id, $form_state) {
  echo "Hallo";
}
`
Comment: When you submit the form, it will redirect to current form if you have not added redirection. Try `'function get_item_form_submit($form_id, $form_state) { echo "Hallo"; die; } `
Comment: Hi! Thank you. It now says hello and debugs the posted values and saves the values - but how do I redirect to e.g. the item list?
Comment: You can use `$form_state['redirect]= 'your url'` in your submit function.
Comment: The problem was that I used '#value' to prefill the form fields instead of '#default_value'!
When taking '#value', the value seems to be frozen, or better read only. It can be changed in the form, but the submitted value is the same as the value predefined in the form earlier.

I changed my form and now I take '#default_value' to prefill the fields.
Comment: It would be easiest for someone to give you a better answer if you posted also your code for the form & for the submit handler in the original post (you can just edit it)
Answer: First, if you want to get an argument from the URL, you should declare it in hook_menu, as such:
<code>$items['items_form/%'] = array(
  'title' => 'Item Form',
  'page callback' => 'drupal_get_form',
  'page arguments' => array('get_item_form', 1),
  'access arguments' => array('access items_form content'),
  'type' => MENU_NORMAL_ITEM, //Will appear in Navigation menu.
);
</code>
Drupal's menu system will then pass in the itemid to drupal_get_form(), which will then pass it along to your form declaration function. You will need to add an argument to your function definition to access it, suggest something like this:
<code>function get_item_form($form, $form_state, $itemid = NULL){
  $form = array();
    ...
}
</code>
Please look at the documentation for hook_menu for more information about how to handle URL arguments. I would caution against using arg() in your code.
The reason this is important is what happens when you submit your form with a URL argument. By default, if you do not override with the #action parameter in your form, it submits a POST request to the present URL. By not declaring that your URL has an argument in it, Drupal actually doesn't know how to handle a request to *items_form/123*. The only reason you see anything but a 404 when you go to *items_form/123* is that Drupal attempts to find the nearest path. I suspect that since it doesn't know explicitly what to do when a request is made to *items_form/123* it breaks the form submission handling.
I should also mention that you'll need to declare both *items_form* and *items_form/%* menu paths if you wish them both to work. They're distinct paths in the eyes of Drupal's menu system.

Form is not submitted with arg() in URL


Does Ubercart have an external API?

Question: Does Ubercart have an external API that a 3rd party site could query? Specifically from a fulfillment point of view? We need to be able to query the system for items to ship, then update the order's status and set a tracking number after the item shipped. All this is done on a completely different server/company, so needs to be done via a publicly exposed API (like a REST or SOAP service). Does Ubercart do something like this?
Comment: There are a couple of solutions for Drupal 6 ([Bee Colony](https://drupal.org/project/bee_colony), [UC Services](https://drupal.org/project/uc_services)), but I've never come across anything for Drupal 7. Focus has somewhat shifted to Drupal Commerce for 7. You could always implement your own [services](https://drupal.org/project/services)
Comment: Is there such a thing for Drupal Commerce? I searched and couldn't find anything...
Comment: [But of course](https://drupal.org/project/commerce_services) :)
Answer: Ubercart does have an API (see http://www.ubercart.org/docs/api and http://api.ubercart.me/ ), but I don't see general REST or SOAP support related to fulfillment.
Some options may include miniRESTapi or as noted UCServices and Bee Colony for Drupal 6. There are some vendor-specific SOAP implementations for CyberSource, but I do not know how well-supported they are.

Does Ubercart have an external API?


Directive In ionicModal complies first, before even controller loaded

Question: I have a $ionicModal and inside that I have a directive, lets call it <scrap-link-cards> , this takes in the a two way data bind value of a scope object. This is inside a $ionicModal template:-->
<scrap-link-cards datasource=(updates.update_links)> </scrap-link-cards>

This is my full directive:
.directive('scrapLinkCards', function ($log) {
        var controller = function ($scope) {
            $scope.links = angular.copy($scope.datasource); //undefined
            $scope.LastIndex = $scope.links.length - 1;
        };
       var templateUrl ='/path/to/template' ;

        return{
            restrict :'E',
            controller: controller,
            scope: {
              datasource :'='
            },
            templateUrl : templateUrl
        }
    })

This is my templateUrl's Template:

{{links[LastIndex].title}}

{{links[LastIndex].description}}

Please NOTE that, this is inside a $ionicModal:
$ionicModal.fromTemplateUrl('path/to/template/html', {
        scope: $scope,
        animation: 'slide-in-up'
    }).then(function ($ionicModal) {
        $scope.ReadMore = $ionicModal;
});

Now here is my problem, since its inside a $ionicModal, the HTML gets complied, before angular can have access to (updates.updates_links). I get a undefined object at $scope.links. How can I workaround this?  I have tried using link function of directive, (moved all the logic in link) still.. I think $ionicModal templates are compiled before controller loaded ? Is it?
Comment: I'm maybe wrong, but this synthax seems odd to me ... datasource=(updates.update_links). Shall not it be : datasource="updates.update_links"
Comment: just some clarifications... Where and how do you activate your modal? Does the modal itself contains the directive? Thanks
Comment: @aorfevre yes, but it works this way too.
Comment: yes the modal contains the directive. I am calling it from a click event on from my controller.
Answer: The only work around I managed to create is to stop the compile function to ever reaching the Modal's directive. Using a ng-if and wrapping the directive with a div.
In the Modal's template :

<scrap-link-cards datasource=(updates.update_links)> </scrap-link-cards>

This way the complier leaves the directive and only complies when the user opens the modal.
Comment: Thanks, this gets the job done. It seems like a bit of an anti-pattern, but given the very deficient modal implementation in ionic, I'll take it. You should be able to simplify a bit with ng-if on the same element as your directive.


Sequelize does not create hasMany associations but foreign keys defined in DB

Question: Altough it seems my associations defined in the database when I call create on my manufacturer model associations does not create.
These are my associated models.
ManufacturerText.associate = function (models) {
    models.manufacturer_text.belongsTo(models.language, {
      as: 'language'
    });
    models.manufacturer_text.belongsTo(models.manufacturer, {
      as: 'manufacturer'
    });
  };

  ManufacturerVideo.associate = function (models) {
    models.manufacturer_video.belongsTo(models.language, {
      as: 'language'
    });
    models.manufacturer_video.belongsTo(models.video_type, {
      as: 'video_type'
    });
    models.manufacturer_video.belongsTo(models.manufacturer, {
      as: 'manufacturer'
    });
  }

And this is the main model:
 ```
  Manufacturer.associate = function(models) {

// models
    models.manufacturer.hasMany(models.manufacturer_text, {foreignKey:'manufacturer_id', as: 'manufacturer_translations' });
    models.manufacturer.hasMany(models.manufacturer_video, {foreignKey:'manufacturer_id', as: 'manufacturer_videos' });
    models.manufacturer.hasMany(models.inspiration_image, {foreignKey:'manufacturer_id', as: 'inspirations' });

    models.manufacturer.belongsTo(models.file, {as: 'image'});
    models.manufacturer.belongsTo(models.file, {as: 'header_image'});

  };

none of the two associations above work.
When I inspect DB with MySQL Workbench it seems associations defined properly.
Answer: It seems the problem caused by the input.
When you send id attribute even doesn't matter if its null, sequelize do not understand that it is an INSERT
I was sending a record like below;
{
  delivery_days: 10,
  image_id: 4,
  { id: null, url: 'http://url', ... }
}


incorrect syntax near '='

Question: The following SQL generates the error "incorrect syntax near '=' The issue seems to be with the select statement (alias TITER).  I've swapped out the TITER Select statement with other tables, and the SQL executes without the error. The error will not generate after I add the FULL OUTER JOIN; only after I type TITER.FLDDATE = TITER.FLDDATE in the SELECT statement in the CROSS APPLY section. My goal is to isolate for the reason for the error and correct the syntax if needed.
SELECT
    EMPLOYEE.FLDLNAME,
    EMPLOYEE.FLDFNAME,
    EMPLOYEE.FLDREC_NUM,
    EMPLOYEE.FLDID2,
    TUBER_FLDDATE as "TUBER Date",
    TUBER_FLDCLASS as "TUBER Result",
    TITER.FLDDATE as "Titer Date"
FROM   EMPLOYEE
CROSS APPLY
    (SELECT TUBER_FLDDATE = TUBER.FLDDATE,
            TUBER_FLDCLASS = TUBER.FLDCLASS,
            TITER.FLDDATE = TITER.FLDDATE
      FROM (SELECT rn = row_number() over(order by TUBER.FLDDATE),
              TUBER.FLDDATE, TUBER.FLDCLASS
            FROM TUBER
            WHERE EMPLOYEE.FLDREC_NUM = TUBER.FLDEMPLOYEE
              and TUBER.FLDEMPLOYEE = '123') TUBER
        FULL OUTER JOIN
            (Select rn = row_number() over(order by TITER.FLDDATE),
                    TITER.FLDDATE
             FROM TITER
             WHERE TITER.FLDTYPE = 'BAMT'
                AND EMPLOYEE.FLDREC_NUM = TITER.FLDEMPLOYEE
                and TITER.FLDEMPLOYEE = '123') TITER
           ON TITER.rn = TUBER.rn) tests

Comment: In the subquery, If `TITER.FLDEMPLOYEE = '123'`, what does `EMPLOYEE.FLDREC_NUM = TITER.FLDEMPLOYEE
` do? I think it may be superfluous.
Comment: EMPLOYEE.FLDREC_NUM = TITER.FLDEMPLOYEE  joins the main table (EMPLOYEE) to the subquery (TITER table). The TITER.FLDEMPLOYEE = '123' is just pulling a specific employee to make my query run quicker during development.
Comment: ahhh, yes, I've done that. Suggestion: that would be better as a nullable input parameter in a single Where clause predicate:  `and TITER.FLDEMPLOYEE = Coalesce(@employeeNbr,  EMPLOYEE.FLDREC_NUM)`
Answer: I think you have an incidental period instead of an underscore:
TITER.FLDDATE = TITER.FLDDATE should be TITER_FLDDATE = TITER.FLDDATE
and then it parses successfully.
Comment: Good catch! I made that change it does run. I needed to add another full outer join in my cross apply section and I get the following error: "The multi-part identifier "TITER.FLDDATE" could not be bound". But because this is truly a different issue I will explore this error message and how to remedy.

incorrect syntax near '='


Views table doesn't set fields next to each other

Question: I got a content type with 7 fields. Each field can contain unlimited inputs. Like:

Field Type/DN got fields 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
Field L got fields 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11

When I make this in a view table I get this:
Type/DN       L
1             1
1             2
1             3
1             4
1             5
1             6
1             7
1             8
1             9
1             10
1             11
2             1
2             2
2             3
2             4
2             5
2             6
ETC.

What I want is
Type/DN       L
1             1
2             2
3             3

The fields are imported from a CSV file by feeds importer.
Here some images to show my settings:
Comment: I tried to reproduce this issue and I just want to clarify when you are adding fields in views, are you selecting the delta of the field? As shown in the below
image there are 2 fields showing for field_image in which you should be choosing the first one. Just make sure you are not choosing the delta one. Which may cause field to be displayed in the order which you don't want. [![enter image description here](http://i.stack.imgur.com/r80y7.jpg)](http://i.stack.imgur.com/r80y7.jpg)
Comment: I know but that isn't the issue. The problem is that he adds all the content form the second field to every content of the first field.
Comment: would you be able to share some screenshot that how are you adding fields to the views.
Comment: The thing is what he outputs is how the view works what i want is something different and i don't know how to do it. I want that the first cel of the table is the first field of the input, So you get 1 next to 1 en 2 next to 2 etc.
Answer: I made the excel import input all the fields.
And make a node for every row in the xls file, then i made a extra field with the product name in the xls file so every node could reconize on what tabel they had to add the rows.
bit messy with a lot of tables but the out put works.


html formatted email using form api

Question: I have created my contact us module using form api, email is successfully generated and send to my specified email address, but I need body of the email to b html formatted, for this I have created another file mymodule.install in my module folder and add the below code:
function mymoduleenable() {
 $current = variable_get('mail_system', array('default-system' =>    'DefaultMailSystem'));
 $addition = array('mymodule' => 'mymoduleMailSystem');
 variable_set('mail_system', array_merge($current, $addition));
}

function mymoduledisable() {
 $mail_system = variable_get('mail_system', array('default-system' => 'DefaultMailSystem'));
 unset($mail_system['mymodule']);
 variable_set('mail_system', $mail_system);
}

and in my mymodule.module
 class mymoduleMailSystem extends DefaultMailSystem {
 public function format(array $message) {
 $message['body'] = implode("\n\n", $message['body']);
 $message['body'] = drupal_wrap_mail($message['body']);
 return $message;
 }
}

but due to above all piece of code I am unable to receive email, kindly suggest any solution.
Answer: Same thing i do in my module may be it is set to you requirement
    global $content;
    $content .= '<button class="btn btn-primary" data-toggle="modal" data-target=".bd-example-modal-lg">Apply</button>';
    $content .= '
';
    $content .= '
';
    $content .= '
';
    $content .= drupal_render($form);
    $content .= '
';
    $content .= '
';
    $content .= '
';
    return $content;

Comment: `$body[] = 'Name: '.$valid_name.'Email: '.$valid_email.'Quantity: '.$valid_quantity.'Article: '.$valid_id.'URL: '.request_uri();` @Adi, I am talking about this line, I need it to be html formatted when email is received

html formatted email using form api


Append Parse Objects to Array

Question: Can't find the answer to this anywhere.
After I call a pfquery, how do I add PFObjects to an array? I have this so far
var array = [PFObject]()

and
var query = PFQuery(className: "Stores")

EDIT: I want to append PFObjects from Parse to an array, so I can then shuffle the order of objects randomly. I know Parse doesn't have the ability to fetch objects randomly
Comment: i mean.. edit with your current code.
Answer: You may use .extend method.
Try initialize your array like this:
var array: [PFObject] = []

And when calling the find method try the following:
 var query = PFQuery(className:"Stores")
            query.findObjectsInBackgroundWithBlock {
                (objects, error) -> Void in
                if (error == nil) {
                    //casting object as [PFObject] since objects is [AnyObject]
                    self.array.extend(objects as! [PFObject])
                    println(self.array)
                }else {
                    println(error?.userInfo)
                }
            }

Comment: it terminated with an uncaught exception =/

Append Parse Objects to Array


descobrir o menor primo maior que o numero n em C

Question: O exercício pede o seguinte: escreva um programa que lê um número n, e então imprime o menor número primo maior ou igual a n.
Minha solução é foi receber um número; analisar se é primo; se for primo a var primo recebe um. Caso não, entraria no while para receber o próximo numero e o programa deveria analisar para ver se é primo ou não. Mas o código não funciona. Quais pontos eu estou errando ?
<code>int main(void) {
  int num,i, j, ediv=0, primo=0;

  printf("Digite um numero\n");
  scanf("%d", &num);

   for(i=2; i<num*num; i++){
    if(num%i==0){
      ediv = ediv + 1;
    }
  }
  if(ediv<=2){
    primo = 1;
  }
  if(primo==1){
    printf("Este numero e primo");
  }else{

while(primo!=1){

  printf("digite o proximo numero");
  scanf("%d", &num);
  for(i=2; i<num*num; i++){
    if(num%i==0){
      ediv = ediv + 1;
    }
  }
  if(ediv<=2){
    primo = 1;
  }
  }
  printf("o menor primo seguinte e %d", num);
    }
  return 0;
</code>
Comment: Seu programa faz outra coisa e não o que foi pedido. Simplesmente leia um número. Só um número. E retorne o primeiro primo menor ou igual a ele. Isso sugere um `for` descendo de `N` até `3`. E naturalmene pulando os pares, já que 2 é o único primo par e 3 já é primo.
Comment: Obg! Corrigi o meu programa. Obrigada pela contribuição!
Comment: Franklin Almeida, aqui apareceu uma [tentativa sua de edição em uma das respostas](https://pt.stackoverflow.com/review/suggested-edits/399993), outra resposta havia sido anteriormente  removida, e as modificações que sugeriu não fazem sentido como uma edição. O pergunto, não preferiria apresentar e explicar aquele código como uma solução a sua pergunta?
Answer: Não me parece que o objetivo do exercício seja o utilizador ter de continuar a introduzir manualmente o próximo número. A lógica correta parece-me ser verificar se o número é primo e caso não seja testar o número imediatamente a seguir e assim ciclicamente até encontrar o "menor primo maior do que o número n".
Neste exemplo tens uma função que retorna se um número é primo ou não (1 ou 0) e um ciclo que vai testando os números começando em n e incrementando-o até encontrar um que seja primo.
<code>#include <stdio.h>

int isPrime(int n) {
    int prime = 1;

    if (n == 0 || n == 1) {
        prime = 0;
    } else {
        for (int i = 2; i <= n/2; ++i) {
            if (n % i == 0) {
                prime = 0;
                break;
            }
        }
    }
    return prime;
}

int main(void) {
    int n, primo = 0;
    printf("Digite um numero: ");
    scanf("%d", &n);

    while (primo != 1) {
        primo = isPrime(n);
        n++;
    }

    printf("Menor numero primo maior ou igual a n: %d\n", n-1);
    return 0;
}
</code>
Comment: Ah, obrigada. Eu acho que consegui fazer. Mas não utilizando função, pois meu prof não chegou nesse tópico ainda. Obrigada pela contribuição novamente.


Command-line for DCC is too long while using MSBuild to compile Delphi project

Question: We use MSBuild to build our Delphi projects. Sometimes the DCC32 commandline gets too long (>32K characters) and fails. This is caused by our Search Path. We have already shorten this path using relative paths, combining sources, etc. This fixed it in the past.
Now we encounter this again and I am looking for a final solution for this. Restructuring the codebase is something I want to avoid, because we use a lot of third-party components which I don't want to mix (and keep in seperate directories).
I have read about response files for MSBuild, but I have no idea how I can get this working for DCC32. I have always mentioned that the same Search Path is passed several times to DCC32 with different flags (-U, -I, -R, -U). The -R (which is used for the resource compiler) does not have to use the exact same Search Path, but unfortunately it always inherits the Search Path from the compiler and I don't see options to ignore that.
Who has any idea how to solve this and find a solution to prevent these issues in the future?
Comment: Have you tried variables (for recurring parts in the path)? The can be defined in the IDE, used in project search paths, and also passed to MSBUILD as additional parameters.
Answer: As it turns out, Embarcadero already had a fix inplace for this, but never documented it (I am not sure from which Delphi version this is supported). It is used when you enable the compiler option Use MSBuild externally to compile in your project. This enables the option/condition DCC_UseMSBuildExternally in the MSBuild script CodeGear.Delphi.Targets (locate in the Delphi-Bin directory). If this option is enabled, the MSBuild script will auto-generate a response file <your project>.cmds which is passed to dcc32. The comments in the Embarcadero MSBuild script are clear :-)

So, to make a longer story short. Use the following MSBuild commandline to prevent these issues:
msbuild <your project>.drpoj /p:DCC_UseMSBuildExternally=true
Answer: You can place all the parameters in a commands file, each on a separate line, and give that file to the compiler prefixed with an @.
"c:\program files (x86)\embarcadero\studio\22.0\bin\dcc32.exe" @myProject.cmds myProject.dpr

Comment: To clarify: You don't need to put all parameters into the command file. Just a part of it (f.i. the path names) are fine, too.
Answer: Could you please try to enable "Use MSBuild externally to compile" option in the IDE's project options page?
The project will contain DCC_UseMSBuildExternally property. So your project will use a script file for compiling the source code instead of long-long command line options.
Comment: That is the solution I used, but more dedicated because I want to use the Delphi internal compiler in the IDE and MSBuild in VS Code (for the same destination and build type).


Proof that a unique BST can be reconstructed from a preorder (or a postorder) traversal unambiguously

Question: For a Binary SEARCH Tree, a preorder or a postorder traversal is sufficient to reconstruct its original binary search tree unambigiously.
But I cannot find a proof or a explanation for why it is so.
For inorder traversal, it is trivial to come up with a counter-example to show that there may be many different BSTs correspond to a given inorder traversal.
Is there any proof or reference that a preorder or a postorder traversal is sufficient to reconstruct its original BST unambiguously?
This is for a BST, not for a general binary tree.
Comment: moreON's argument is correct if we disallow duplicate elements. If we *don't* disallow duplicate elements, then the claim is false: `1 1 1` is a preorder traversal of 5 different BSTs.
Comment: Consider that the preorder traversal begins with the root, then the left subtree, then the right subtree. So the first element is definitely the root. Is there any possibility that there is more than one way that you could choose where amongst the rest of the traversal the left subtree ends and the right subtree begins. If there is no such ambiguity - there is a unique point that you can determine, then there is only one way to choose the root, left subtree nodes and right subtree nodes. Each subtree is a BST, so if you can uniquely split the entire tree like this, you can do it with subtrees.
Comment: @moreON: My comment was not intended as a criticism of yours; I'm sorry if it came off as one. The OP is looking to prove a certain claim, and insofar as the claim is correct, your proof (= the proof that your comment is guiding the OP to) is the correct one. I'm simply pointing out an ambiguity in the claim, and clarifying that only under one interpretation is it actually correct.
Comment: @ruakh - If you read carefully, you'll find that I proposed a method to reason about this, into which you can place your own rules and assumptions about BSTs that would lead to appropriate conclusions rather than constructing a specific argument for any particular conclusion. Note the use of "if ..." to allow one to come to their own conclusions.  I will admit that with the conciseness required by comments it certainly does guide the reader toward one set of assumptions.
Comment: @ruakh Thanks for clarifying the problem. I should've mentioned that this was case for no duplicate elements :)
Comment: @moreON Thanks for the answer! Now I see the idea (the same logic applies to postorder). I would've defintely upvoted it an marked it as a correct answer if it wasn't a comment :)
Comment: Go ahead and convert it to something answer-worthy yourself and claim your correct answer bonus, I have no complaints. I think it's probably a little short of being an answer right now.
Comment: (You may answer your own question. Even if somebody else sketched the idea in a comment.) Please correct the title.
Answer: By the definition of pre-order traversal, it is guaranteed that root will be the first element.
Now, given the root, there is a unique set of elements that will come in the left half of the root - i.e. all elements having value less that root->val.
Likewise for the right subtree.
Now, we have to apply the above logic recursively for the left subtree and the right subtree.
Since, post-order traversal is just the reverse of pre-order traversal on the reverse tree, the same logic applies to post-order traversal too.


Why in CNN network 3 filters are learning same feature?

Question: I am using a simple CNN with one convolutional layer and one fully connected layer. I am using 3 filter channel and one input channel. I run my code 500 times with random initialization of weights in each loop. Each training loop is run for 30 thousand training steps. Then I plot filter weights of 1st filter and use fitting function to fit the data, similarly for second and third filter. I am getting similar result. Which shows that machine is learning same features to distinguish two classes. But I read every filter channel should learn a different feature. My model is showing 80 percent accuracy in 500 training loops. So what can be the reason for learning same features? Is my input data is quite simple?
Answer: Actually nothing guarantees that different convolutional filters would learn different features. The filters have same structure and are trained in the same way, so they are redundant before they learn something. We initialize the parameters randomly and we hope they will learn different features. You should probably try different initialization for the weights. If this doesn't help, try debugging the network as described in What should I do when my neural network doesn't learn?.
Comment: I want to say that I'm randomly initializing weights.
Comment: Should I plot heat map to get a feeling of whether they are similar or not?
Comment: Actually i'm running a k -loop 500 times. in this k loop i use random initialization. Inside k-loop an i-loop is nested  and every i-loop runs for 30 thousand training steps, I don''t use any random initialization in this i-loop.
Comment: @jerry unfortunately I don't understand your comment. I meant randomly initializing the weights, if you didn't do that, then there is no chance in getting something else then exactly the same outcomes for all the filters.
Comment: @Jerry You can also plot a heat map of the "over all filters" std and mean to get a feel of the similarity. Only the std helps for that but I like to plot the mean too.
Answer: Deep neural networks use Several hidden layers to hierarchically learn high level representation of a given picture, for example : first layer of your neural network might detect edges present in your given picture, second layer may detect curves present in your given picture and 3rd layer may detect your full face from your given picture,basically they try to bridge the gap between high level representation and low level features.so even if you keep on doing  random initialization every time there is a possibility that first layer of your neural network might still detect something like edges present in your given picture over and over again,low level features are minor details of your picture, like lines,dots etc and these are typically caught by convolution filters... does it make sense?if you want your network to learn more features then increase neurons and hidden layers.
Comment: I'm only using one convolutional layer with 3 filter channels. So can I say that my network is learning almost same features(low level). My model's accuracy is quite higher even with such a simple network.


TestCafe - How to use both User Role and HTTP Authentication?

Question: I am using TestCafe to automate my tests.
The problem is that i am using a CMS, and need to test two types of environments:
1. Author
2. Publish
- Eg. I want to create some content as Author, and verify the same on the Publish instance, using the same test.
The problem occurs when i want to switch between the environments because the Publish environment uses HTTP Auth. and the Author does not.

I wanted to use User Roles to switch between the environments. This works okay for the Author environment, but when i need to switch to Publish, i need HTTP Authentication to login. TestCafe provides this only on a test / fixture level and thus i must use a different test for the Publish instance which is not logically true and also will create more overhead for the test.
Answer: The scenario is quite complex, so at this moment it's difficult to say precisely why you have an issue. There can be some specifics on your site or TestCafe can have some limitations. It's better to create a separate issue in the TestCafe Github repository and provide the team with a working example or url to your project. In this case we can research your project and help you with a solution.
Please use the following template to create an issue: https://github.com/DevExpress/testcafe/issues/new?template=bug-report.md


How to convert string to NSArray in iOS

Question: I have a JSON object and it has a key value pair like this
"AttachedDocument": "[{\"DocumentId\":354,\"DocumentName\":\"Screenshot_2016-04-15-00-35-11.png\",\"DocumentType\":\"image/png\"}]"

This value is coming as a string. How can I convert that into an NSArray
FULL OBJECT
{
    "LeaveEntryCode": 0,
    "RequestId": 0,
    "EmployeeCode": 17186,
    "LeaveYear": 2016,
    "LeaveTypeCode": 1,
    "LeaveReasonCode": 0,
    "BaseType": "ess",
    "StartDate": "2016-10-24T00:00:00",
    "EndDate": "2016-10-24T00:00:00",
    "NoOfDays": 1,
    "StartDateSession": "full",
    "EndDateSession": "full",
    "PreApproved": false,
    "ForDate": "1901-01-01T00:00:00",
    "Remarks": "test from Android",
    "CoveringPersonCode": 0,
    "AttachedDocument": "[{\"DocumentId\":354,\"DocumentName\":\"Screenshot_2016-04-15-00-35-11.png\",\"DocumentType\":\"image/png\"}]",
    "RequestStatus": "P",
    "Deleted": false,
    "Status": false,
    "CreatedBy": 0,
    "CreatedDate": "0001-01-01T00:00:00",
    "UpdatedBy": 0,
    "UpdatedDate": "0001-01-01T00:00:00",
    "DeletedBy": 0,
    "DeletedDate": "0001-01-01T00:00:00",
    "ModuleId": 2,
    "ObjectId": 20,
    "StartDateString": "10/24/2016",
    "EndDateString": "10/24/2016",
    "LeaveDayList": [
        "10/24/2016-FH,10/24/2016-SH"
    ],
    "SystemLeaveTypeCode": "ANN",
    "LeaveTypeName": "ANNUAL",
    "Employee": null,
    "LieuDayList": null,
    "BaseLeaveType": "ANN",
    "CoveringPersonName": null,
    "LeaveReasonName": "test",
    "DocumentSource": "LEAVE"
}

This is the full JSON Object im getting. I am getting this via a web service.
Comment: Where/how are you receiving this? Is it from a URLRequest? How are you getting the string in this format?
Comment: It's JSON String representation inside JSON. Possible duplicate of [Parsing JSON Within JSON in Objective-C](http://stackoverflow.com/questions/33149110/parsing-json-within-json-in-objective-c)
Answer: Actually you are getting josn string as response, so you can convert it to josn object something like,
 NSString *yourString = @"[{\"DocumentId\":354,\"DocumentName\":\"Screenshot_2016-04-15-00-35-11.png\",\"DocumentType\":\"image/png\"}]";

NSError *error;
NSData *data = [yourString dataUsingEncoding:NSUTF8StringEncoding];
NSArray *jsonObject = [NSJSONSerialization JSONObjectWithData:data
                                  options:NSJSONReadingMutableContainers
                                    error:&error];

   NSLog(@"json object : %@",jsonObject);

here yourString means object for AttachedDocument key!

How to convert string to NSArray in iOS


Window within window html framework

Question: sorry for the vague title. I was wondering if there's any framawork I could use to make something like Gmail's compose an email window. For example for posting comments, I'm currently using a Modal with Twitter Bootstrap, but that covers all the website, I want something smaller but just as functional. If not a framework, is there a name for this kind of window?
Comment: You can set the size of a Twitter Boostrap modal: http://stackoverflow.com/questions/10169432/how-can-i-change-the-default-width-of-a-twitter-bootstrap-modal-box
Comment: @nb1987 Thanks, but I'm looking for a solution that does not suspend control of the rest of the website
Answer: You could try something like this.
<!DOCTYPE html>

    <title>Note Test Page</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

        <button type="button" class="btn btn-primary" onclick="openNote();">Show Note</button>

        <textarea id='note' name='notes' rows='12' style="width: 495px;" contenteditable="true"></textarea>
        <button type="button" class="btn btn-primary" onclick="closeNote();">Close Note</button>

Window within window html framework