Erro ao verificar campos na base de dados

Question:     //código da classe
    public function ver_utilizadores (){
    $bd = new ligacao_bd();
    $ver_utilizador = "SELECT * FROM utilizadores";
    $resultado = $bd -> realizarQuery($ver_utilizador);
    return ($resultado);
    }
//codigo do script
if(!$erros){
        $username= $_POST['username'];
        $email= $_POST['email'];
        try{
        $verificar = new utilizadores();
        $resultado = $verificar -> ver_utilizadores($username, $email);
        if($resultado -> num_rows >= 1){
        echo "asdasd";
        }else{
        $insere = new utilizadores();
        $resultado = $insere -> inserir_utilizador($username, $password,$email);
        header('location: login.php');
        }
    }//fim try
        catch (Exception $e){
            echo "Erro de inserção";
        }

Estou a tentar verificar se existem campos iguais ( username e email ) na base de dados, para que se existe não deixe registar.
alguém sabe onde está o erro?
é que ele insere na mesma mesmo que os campo sejam iguais
Comment: Eu acabei entendendo errado, quando vc imprimi(echo) `$resultado->num_rows` aparece o que?
Answer: Bom, na terceira linha do seu código na variável  $ver_utilizador = "SELECT * FROM utilizadores", não tem informação do usuário e email logo a chamada do seu método ver_utilizadores($username, $email) traz sempre todos os registros da tabela, não fazendo validação alguma se o usuário existe ou não, coloque a cláusula "WHERE" no seu SQL utilizando os campos username e email, exemplo:
SELECT * FROM utilizadores WHERE username = ? and email = ?


Need Help passing field data from one content type to another

Question: I am working on an Equipment Checkout system using Drupal 7, MERCI, views, panels, rules, and many other modules. I am working for a community college in Oregon. I am upgrading features on an already running system that was built by myself with the help of a few other people last year. The system is offline for the summer.
Before I jump into the nuts and bolts of the question let me give you a little information on our workflow.
When the Student want to checkout equipment (cameras, microphones, whatever) we first open up the students customer account. This is a content type called customer, that has various fields containing data about the student, name, email, L# etc. We do this to verify the identity of the student as well as to make sure that they can actually check out the equipment they are requesting.
After we have verified the students credentials. We then create a new reservation, that is also a content type. Then we input the student information into the reservation.
So what I want to do: Have a button or link on the customer page that will capture the customer data, create a reservation, and then put the data in the appropriate place.
I have done some searching looking for answers and this seems to be a common problem, but the specifics always seem to throw me off. I've tried a few modules to attempt this, autofill and prepopulate but with no success.
This is the first of many features that I am trying to implement over the next 3 months, any help would be greatly appreciated.
Thank You
Answer: I don't have enough reputation to comment. I would approach this with an entity reference field, a block, and rules.
Your reservation content type should have an entity reference field for the 'customer' record.
A block would have the button to click. It goes on your customer record page. You might need a module like Rules Link  to trigger rules.
Set up rules so that when you click this button it:

creates a new entity (a node of type reservation)
populates the user reference field with the customer node you are looking at
saves the new node
opens the edit screen on the new node so more work can be done

It will take some playing around play around with rules to get it right.
Comment: I think your work flow is solid. I did some looking into rules_link and it looks like a good solution, now I just need to figure out Rules. lol Time to do some research on rules now. Thanks :)
Comment: Any chance you know rules well enough to help me get them in place. I can create the new reservation, but after that I get lost.  Thanks :)


Why is SonarQube's skippedModules property deprecated?

Question: I am doing a Sonar analysis with Maven on a Maven multimodule project. I have to use sonar.skippedModules property frequently and ever since I have upgrade to SonarQube 4.3, I've noticed that this property is deprecated although I can still use it. Is there a reason for this property to be deprecated and will be be removed in future versions of SonarQube? I surely hope not.
Answer: Yes, This has been been removed from SonarQube 4.3. You need to change the syntax. I am not sure what is the new syntax. But refer this :- https://jira.codehaus.org/browse/SONARVS-31
And please like the post if you found this stuff useful.
Comment: That is interesting because excluding modules from the GUI page is effective. They mentioned wildcards feature, I really hope that gets added in.


Would this Sharepoint Services 3.0 Application Template work on Sharepoint Foundation 2010...?

Question: I'm looking to do an install of Sharepoint Foundation 2010 and implement a Help Desk / Issue Tracking system.
This Help Desk Template is for Sharepoint 2007.  Could I use it under Foundation 2010...?
Comment: Probably, but without having tried it there's no way I could be sure.
Answer: Well, that's a bit of a tricky situation. If you have a current SharePoint 2007 environment with that template installed, you should be able to upgraded it to SharePoint 2010 without too much issue. But if you have a new SharePoint 2010 environment, you will not be able to create new sites using that template in the 2010 environment. This post has more info on that situation: http://blogs.technet.com/b/tothesharepoint/archive/2010/08/18/sharepoint-2010-products-upgrade-and-the-fabulous-40-application-templates.aspx
There is good news though :) A member of the SharePoint community has recompiled several of the site templates in that "Fantastic 40" group for SharePoint 2010 and posted them here: http://techsolutions.net/Blog/tabid/65/EntryId/17/Fab-40-Templates-for-MOSS-2010.aspx
I would suggest taking a look at that page and trying the Help Desk template you find there. It is important to keep in mind though that those templates are not supported, so you're going to have to deal with any errors or issues you encounter on your own.
John


Non-binomial posteriors for a binomial prior?

Question: Let's assume we have a discrete binary random variable K (K=0 or K=1) for which the prior distribution is binomial. My understanding of Bayesian statistics tells me that regardless of the likelihood, the posterior distribution for K can only be binomial as well. However, I have encountered a text which talks about "beta posterior for a binomial prior" -- am I correct that this is wrong?
Comment: Can you give more of the text?  It probably means a Beta (hyper)prior for the binomial prior.  And that Beta prior can be updated, so it has a prior value, a likelihood and a posterior.
Comment: What is your observational data? You have prior distribution of $k\sim B(n,p)$. What is your observational data? And what is your conditional distribution? If your observational data is $k$, then it becomes the maximum likelihood estimation, with nothing to do with the posterior. $p(k|X)\propto p(k)L(k|X)$. What is your observational data $X$? If your observational data is your successful rate $p$, first of all, how do you get your observation of $p$? If it is, then what is $L(k|X)$? If $L(k|X)=\Pi f(X)$, then we have $p(k|X)=p(k)$, a binomial distribution.
Comment: @NeilG No, the text doesn't discuss hyperpriors.
Comment: @quant_dev: They may not have used that term, but a Beta distribution is the conjugate prior for the Bernoulli distribution, which is the most likely explanation.  Why don't you give more of the text?
Comment: I cannot post the original text, buy it says about using multinomial logistic regression for modelling measured data.
Comment: @quant_dev: Then it sounds like rather than updating the parameters by, for example, gradient descent, the learning algorithm is updating a prior on the parameters, which is beta-distributed (or Dirichlet in general).
Answer: 1) Let $K\sim\text{Bernoulli}(p)$. When you observe a random sample, you get $n$ realizations of $K$ and try to guess $p$.
So your random sample is a realization of the multiple random variable $(K_1,\dots,K_n)$.
$Y=\sum_{i=1}^n K_i$ is equal to the number of $K_i=1$, is the number of "successes" in your sample and $y/n$ ($y$ is the realization of $Y$) is your best guess about $p$. For example, if you get 100110101110, where $y=7$ and $n=12$, $p$ is likely close to $7/12$. So the binomial distribution of $Y$, $Y\sim\text{B}(n,p)$, is your likelihood, not your prior!
You need a likelihood, not a prior, for $K$ -- better: for $y$. Then you need a prior for $p$ ($n$ is known).
2) The posterior always depends on both prior and likelihood, because is just their product. So you can never say that is something "regardless of the likelihood". Moreover, you are looking for a posterior for $p$ (the unknown parameter in $K\sim\text{Bernoulli}(p)$) conditional to the realizations of $K$, not a posterior for $K$.
3) If you assume that the prior for $p$ is $\text{Beta}(\alpha,\beta)$, then your posterior will be $\text{Beta}(y+\alpha,n-y+\beta)$, as you can see here. This is called "coniugacy" -- when prior and posterior belong to the same family -- and is computationally convenient; so this is why a beta prior is often used when the likelihood is binomial.


Dominant seventh chord in the major scale contains diminished triad of the seventh?

Question:
The seventh chord built on the fifth step of the scale (the dominant seventh) is the only dominant seventh chord available in the major scale: it contains all three notes of the diminished triad of the seventh and is frequently used as a stronger substitute for it.

What does this mean, especially "diminished triad of the seventh"?
Answer: "Dominant seventh" is a shorthand for what others call a "major-minor seventh," meaning a major triad with a minor seventh on top.
If we take all notes of a major scale and create seventh chords on top of them using only the notes of that major scale, only one of these seventh chords will be a major-minor ("dominant") seventh: that built on scale-degree 5 of the major scale. Scale-degree 5 is called the "dominant," hence the term "dominant seventh."
When this text says "diminished triad of the seventh," the writer is being a little loose with their terminology. It should say "diminished triad of the seventh scale degree," because the triad built on top of that seventh scale degree is a diminished triad. And that same diminished triad is the third, fifth, and seventh of the dominant seventh chord built on scale-degree 5.
In C major, scale-degree 5 is G and scale-degree 7 is B. The seventh chord on G is G B D F (a major triad G B D with a minor seventh G F), and it includes the diminished triad built on scale-degree 7: B D F.
Answer:
We call the resolution stronger because the V7 chord is much more directional (the vii°7 chord, which would be the diminished seventh chord, is symmetrical and ambiguous). There are other reasons, and as further reading, this post does a good job explaining this resolution's strengths.
Comment: With the Bb accidential (correct term?), this does not match the C major scale, does it?
Comment: @zebonaut oh wow, good catch. Yep, it should be C major, not F major!
Answer: I won't explain much of chord theory since it seems clear that you are looking into theory on your own. however, I will explain what is written in the snippet that you posted in your question.
 "The seventh chord built on the fifth step of the scale (the dominant seventh)"

it is referring to the diatonic seventh chord derived from the 5th note of your major scale.
Diatonic seventh chord means the chord has the triad plus the seventh note which is in the scale.
For example - in the case of C major scale, the fifth of C is G. Now let's try forming the seventh chord (remember the seventh chord is basically the triad plus the 7th note from the initial note.).
G triad in C major is a major chord - G-B-D.
the diatonic ( in scale ) seventh from G is F.
So your seventh chord built on the fifth step of C major is G-B-D-F.
This chord is known as a dominant seventh chord and is denoted as (roman numeral)7.
"is the only dominant seventh available on the major scale"

There are 4 types of 7th chords. ( you can look it up on youtube as I don't want to get into too much theory here )
and what the above line meant was that you can only make a dominant 7th chord from the 5th note of the major scale within the scale. Taking any other note and making the seventh chord from that note won't be a Dominant seventh.
 "it contains all three notes of the diminished triad of the seventh and is frequently used as a stronger substitute for it"

the diminished triad of the seventh means the chord root of which is the seventh note of the scale. So in the case of C major scale, it will be a B diminished chord.
The notes of B dim are - B,D,F
.
.
.
Seems familiar?
It has almost all the notes from G7 or "the seventh chord made from fifth step".
Since it has almost all the notes from Bdim, it is often times used as a substitute of the diminished chord.
I hope I was able to give you a satisfactory answer. If you have any more queries regarding music theory, feel free to ask :)
Answer: Every note in a major scale can have a triad built on it, as shown in user45266's answer. But here, we're talking about seventh chords, which not only have 1,3 and 5, but a diatonic 7 too. As in (key C) - C E G B. D F A C.  E G B D.  F A C E. G B D F. A C E G. B D F A. The bold letters are the chord names, and each is called 7th. C and F become maj7, D, E and A become min7, leaving the chords from the question. The only dominant chord is that based on G, which also happens to contain the triad made from the 7th note of the scale - B.
That chord - B D F is diminished, and as such, points in no particular direction, neither major nor minor, so is weak in comparison. However, when it's combined with the dominant note of key C (G), it takes on a far more defining role, pushing towards the root C. Incidentally, adding that extra note to Bo gives B D F A, known as Bm7♭5.


Removing hexadecimal UTF-8 characters in java

Question: I know this question has been asked before, but none of the solutions seemed to work for this particular problem.
My Java application receives a username from another server. The username sometimes contains the hexadecimal representation of UTF-8 characters.
For example: "Féçon" comes in as F\C3\A9\C3\A7on.
None of the examples I found on this site (most of them use "getBytes") worked. No idea why.
So my question is: if you have defined a String with these characters, how can you remove them so it looks right again? You can try it yourself by using the following:
String test = "F\C3\A9\C3\A7on"
thanks!
Mike
Answer: It's not the most performant solution, but at least the code is short....  You're basically URL decoding, where \ indicates an encoded character instead of %.  So the following code works:

String s = "F\\C3\\A9\\C3\\A7on";
s = s.replace('\\', '%');
System.out.println(URLDecoder.decode(s, "UTF-8"));
Answer: In this case getBytes won't work because it sounds like your Java string doesn't contain any Unicode characters; it just contains fifteen regular ASCII characters that represent the escape sequence of the unicode characters.  It's likely that whatever your upstream component is, it's responsible for the escaping.
So easiest way to address this is to see if the "other end" can be persuaded to speak Unicode.  If so, you'll get the characters directly in Java and Bob's your uncle.
Otherwise, you'll need to find some way of decoding these Strings.  The simplest way I can think of is to iterate through, manually converting to chars and concatenating, something like this:
StringBuilder result = new StringBuilder();
char[] input = inputStr.toCharArray();
for (int i = 0; i < input.length; i++)
{
   switch (input[i])
   {
      case '\\':
         // Get the next two characters and turn it into a literal char
         String escapeCodeStr = input[i+1] + input[i+2];
         char escapedChar = (char)Integer.parseInt(escapeCodeStr, 16);
         result.append(escapedChar);
         i += 2; // Move pointer to account for two extra characters read
         break;

      default:
         result.append(input[i]);
   }
}

return result.toString();

This hasn't been tested, but it illustrates the principle of turning the escape codes into literal characters.


What does cv2.cornerHarris return?

Question: I have been reading about cornerHarris in OpenCV. I read through the documentation but I am not sure what does this function return.
While reading through the examples, there is a statement written as:
dst = cv2.cornerHarris(gray,2,3,0.04)

img[dst>0.01*dst.max()]=[0,0,255]

I just cannot understand the second statement above, may be because I do not understand, what is cornerHarris actually returning.
I do sense, that there is some kind of threshold being applied, but I cannot explain.
Answer: I just checked the example page you linked:

Threshold for an optimal value, it may vary depending on the image. img[dst>0.01*dst.max()]=[0,0,255]

This is the documentation page I was actually looking for:
https://docs.opencv.org/2.4/modules/imgproc/doc/feature_detection.html?highlight=cornerharris#cornerharris

Corners in the image can be found as the local maxima of this response
  map.

The cv2.cornerHarris detector returns the corners that were found. As usual this method does not return a list of corners that were found. Instead, it returns an 2d-array - same size as the input - with probabilities. Each position inside this array holds the confidence in this pixel being a corner  (to be precise it is not the single pixel, that is predicted to be a corner. It is the neighbourhood that is centered at this coordinates)
So most likely cv2.cornerHarris returns a value for confidence in it's own prediction. And with
dst>0.01*dst.max()
the code filters corners that are only "low-confidence-corners". Any corner that is detected will just be marked as a corner if the confidence is higher than 1% of the highest confidence.
Answer: dst = cv2.cornerHarris(gray,2,3,0.04)

dst is resultant 2D probability array with the same shape as of input image.
img[dst>0.01*dst.max()]=[0,0,255]

The above code is marely a post-processing technique, where "low-confidence-corners" are filtered out.
or to interpret differently:
Filter in those probabilities whose confidence is more than 1% of the max. probability in the resultant 2D probability array
From the examples documentation. If the image is less complex as given below, Even the below code will work fine:
img[dst == dst.max()]=[0,0,255]

For more clarity, plot the resultant 2D probability array using matplotlib:
def display(img, mapp='gray'):
    plt.imshow(img, cmap=mapp)
    plt.show()

What does cv2.cornerHarris return?


Use picking instead of hammer-ons and pull-offs

Question: In my learning, I'm nearing that point when the notes just seem too fast to be picked individually. Most tabs I come across contain hammer-ons and pull-offs for fast notes. However, I'm finding that by picking each individual note, I can produce better sound and even play more accurately, even if the notes are really fast (by my current definition of fast anyway). I'm wondering if it's "OK" to pick all notes instead? Will this cause problems later on?
Answer: I would say it's not ok.
Obviously, how you play a certain piece and your personal style can differ from one person to another and one song to another. But you asked the question in the context of learning to play the guitar and not in the context of fingering for a certain song.
As you get better, you will not pick as fast as you can hammer on and pull off. Failure to learn the technique will limit your speed a great deal.
As songs get more complicated, you will find that there are times when you want to do a hammer on or pull off when picking it will be exceedingly difficult. In particular, rhythm parts that include a strumming action for the chords and hammer ons or pull offs for accent or melody.
Hammer ons and pull offs are heavily used techniques in guitar. You should take the time to learn them, even if you can "get around it" at your current skill level. That won't hold true as you get better.
Answer: It will cause the "problem" that you will have your own sound and playing style.
At some point, most players want to learn hammer-ons and pull-offs. At some other point, most players want to learn to pick every note in a fast run cleanly and fluidly. Usually players learn the legato hammer-on and pull-off style first, since it seems to be easier. There's no need to learn it first. You won't hurt yourself by learning to pick every single note at this time.
Notice I'm assuming you will eventually come back and learn hammer-ons and pull-offs. I'm very confident that sooner or later, you will. If you never do, then you will have firmly fixed your own style and there will be some sounds and styles you won't be able to reproduce. If that's how you turn out, that's ok. There are plenty of excellent guitarists who are unable to execute all kinds of techniques, even basic ones. If you watch Bruce Springsteen carefully, he is a terrible guitarist, from a technique point of view. But he is the only one who plays the way he plays.
Answer: Of course you can pick each note separately. But, they'll have a terminal velocity. Think about it - a hammered on note can be literally as quick as banging the next note down, much quicker than recovering your pick or finger. And pull-offs are similar in speed. Try doing consecutive hammers and pulls on, say, 4th and 5th frets. Lightning speed in comparison to picking each note!
But only when they're done properly. Hammer-ons need to be smart and firm, and will eventually sound much like picked notes. Pull-offs will sound exactly like a finger pick, because that's what they are - only with the fretting fingers.
It won't cause problems later, as the more you play, the quicker the picking will get, but learning to produce good sounding hammers and pulls will set you up for great legato playing anyway. Listen to experts and it's almost impossible to tell the difference between those and simple picked notes.
Comment: The fastest playing I've ever heard has all been picked. Logic is nothing in the face of the literature, IMHO. Only referencing Dick Dale and Eddie Van Halen should be enough, to say nothing of Tom Morello, Eric Johnson, Ministry, and Dragonforce.
Comment: @Todd Wilcox - EVH for one uses two hand tapping, which involves hammers and pulls. Granted, for tremolo all notes picked is faster, although I guess 3 or 4 finger tremolo is even faster.
Comment: EVH also uses tremolo picking and other very fast picking techniques. My point is, there seems to be an assertion in this answer that picking every note can never be as fast as legato playing, and I don't feel like that assertion has a lot of support in the literature of guitar playing. Beyond that, speed is not by itself an important factor in being a great guitarist.
Comment: @ToddWilcox - certainly agree with the last point, however, the OP doesn't seem to be asking with that target in mind. I feel that he's asking about general playing, and feel that for most people legato playing produces the speed needed for certain passages more satisfactorily than only using picked notes.
Comment: @ToddWilcox, I would add that, as a former teacher, you should learn the basic techniques of the instrument. If you then develop a style that doesn't use them, that's fine. But I'd never recommend you create a style by skipping basic parts of the instrument.
Comment: @yossarian I'm not a former teacher, I'm a current teacher, and I have learned all the basic techniques. My mission in teaching is not to make every guitarist conform to some standard of guitar playing. It's to help students learn a way to express themselves and understand a communication style that is both highly structured and infinitely flexible, so they can experience the supposed dichotomy of "logic versus emotion" for themselves. So I teach what my students want to learn, more or less, since specific techniques are not by themselves relevant to that mission.
Comment: At the risk of getting into a secondary argument over the definition of "gracefully", I assumed that accepting gracefully excluded arguing over the downvote reason. I'm inclined to go back to not explaining downvotes.
Comment: @ToddWilcox - this is a discussion - I'm not arguing. It's just good to have a reason behind any downvote - after all, we should be responsible for our actions, and in fairness, ought to be able to give reasonable reasons why we decided to perform them, rather than hiding behind anonymity. That way, we all know where we stand, and may learn more. I gracefully accept the downvote, but that doesn't preclude further discussion - or does it?
Comment: @yossarian I'm not skipping anything, in fact I try to learn as many techniques as I can. However, I just think picked notes sound better, and I *think* ho/po is meant as a shortcut to faster playing (*in cases of extreme speed only*). I do use them as needed for slower notes, as the sound they create is nice (for lack of a more professional term).
Comment: @ToddWilcox I first tried picking all notes after watching an Arch Enemy live video, and I think the Amotts were both picking all their notes (or so I seem to remember). In all honesty, their style is the exact thing I'm most interested in playing. That's what gave me the idea, and what do you know, I'm actually better at picking than I am at fast ho/po.


ios 7 dequeueReusableCellWithIdentifier:forIndexPath method - does it need registerClass method

Question: I am using ios 7.
Quick question. I have a working program that uses dequeueReusableCellWithIdentifier:forIndexPath to display cells with two different prototypes. I never used the UITableView registerClass method.
Does this mean that I am not reusing the cells? My thinking is that this is not the case (as I have fixed bugs before in this app which were related to cells retaining prior states).
If I actually use registerClass now (in viewDidLoad for the tableVieW), my data is not being shown - any ideas why?
Thank you!
UPDATE
I add the registerClass code in viewDidLoad as follows:
<code>[self.tableView registerClass:[ProtoCell1 class] forCellReuseIdentifier:@"proto1"];
[self.tableView registerClass:[ProtoCell2  class] forCellReuseIdentifier:@"proto2"];
</code>
Comment: "If I actually use registerClass now (in viewDidLoad for the tableVieW), my data is not being shown - any ideas why?" - how can we know? you have not placed any CODE. Registering classs is just a new feature, you can use both methods now. but maybe old method is depricated now
Comment: I added the code to add register class, if that helps.
Comment: @serverman are you using storyboard?
Answer: If the cell is created using prototypes within a storyboard it is not necessary to register the class.
Using
<code> registerClass:forCellWithReuseIdentifier
</code>
will prevent your view from rendering if it was already declared in Interface Builder. If you registered your cell identifier in storyboard and you are using
<code>  dequeueReusableCellWithReuseIdentifier:
</code>
then you should be reusing cells
Comment: Thanks Kyle, that answers my question!


How to get exactly result from async methods via await without Task.Result?

Question: I wanted to experiment with async and await but I had a fiasco.
I have the method which need to run two methods asynchronously(it works partly)
public void Run()
{
            Task[] tasks = new Task[2];
            tasks[0] = Task.Factory.StartNew(DisplayInt);
            tasks[1] = Task.Factory.StartNew(DisplayString);

            //block thread until tasks end
            Task.WaitAll(tasks);
}

And two methods which are used
public async void DisplayInt()
    {
        Task<int> task = new Task<int>(
            () => 10);
        task.Start();
        Console.WriteLine(await task);
    }

    public async void DisplayString()
    {
        Task<string> task = new Task<string>(
           () => "ok" );
        task.Start();
        Console.WriteLine(await task);
   }

And usually I got next results:1) 10 ok
or
2)ok
10
but sometimes
I got 3)nothing
How to get exactly result from async methods via await without using task.Result or it cannot happen?
Comment: Is writing to the console from many threads even safe? I can't remember right now.
Comment: Yes, links: https://msdn.microsoft.com/en-us/library/system.console.aspx and http://stackoverflow.com/questions/1079980/calling-console-writeline-from-multiple-threads.
Comment: You can also do `task.GetAwaiter().GetResult()`, which is different from `task.Result` in that it doesn't wrap exceptions with `AggregateException`.
Answer: I recommend you read some introductory articles like my own async intro, and follow that up with my MSDN article on async best practices. If you just bang out code, you're going to end up with a lot of pain.
In particular, you should not use Task.Factory.StartNew, the Task constructor, nor Task.Start; and you should avoid async void (all links are to my blog where I explain in detail why).
To answer your actual question:

How to get exactly result from async methods via await without using task.Result or it cannot happen?

To get the result from a task, you can either asynchronously wait for the task to complete (via await), or you can synchronously (blocking) wait for the task to complete (via Result). There's no "other way", if that's what you're asking.
Answer: Welcome to SO...
Well, in your case for both tasks it takes more time to initialize them, then to run the method inside. That's why sometimes second task finishes before the first one (if it was initialized in shorter time). If you change your DisplayString method to :
    public static async void DisplayString()
    {
        Task<string> task = new Task<string>(
            () => { Thread.Sleep(10); return "ok"; });
        task.Start();
        Console.WriteLine(await task);
    }

As now DisplayString method now takes around 10 ms to execute It'll will always result in :
10
ok

P.S.
As pointed by Stephen Cleary you can read some basic articles about async / await. I'd also recommend to test it on WinForms projects rather then doing it with Console.
Comment: Sleep-based sync is not quite a good practice  - I think you should add that it's only for demo purposes. Someone inexperienced might take your example as a pattern to use.


Function for slider with minimum, maximum and "midpoint" value

Question: I'm trying to create a slider that lets the user pick a value as low as some given minimum, or as high as some given maximum. The slider must also, when positioned half way, have a value that is some given "mid point".
So I'm looking for an increasing function $f(x) : [0,1] \to \mathbb{R}$ such that
$f(0)=k_{\mathrm{min}}$
$f(\frac{1}{2})=k_{\mathrm{mid}}$
$f(1)=k_{\mathrm{max}}$
for any $k_{\mathrm{max}} ≥ k_{\mathrm{mid}} ≥ k_{\mathrm{min}}$.
What could I choose? My first thought was a quadratic, since I have three unknowns, but this was non-inreasing for some values.
Thanks.
Comment: I think a quadratic should work as long as the middle point is actually in between the min and the max... How did you get non-increasing functions?
Comment: Is piecewise linear too simple?
Comment: @Vhailor: consider the function $f(x) = -(x-1)(x-3/4)+3/4$. $f(0) = 0$, $f(1) = 3/4$, $f(1/2) = 3/4 - 1/8$. $f$ attains a global maximum at $x = 7/8$.
Answer: There are many ways of fitting a function to your requirements. Here is one particular way, which assumes some sort of power law type distribution between the min and the max values.
We first define the case where the min is 0 and the max is 1. Then we can set
$$ f(x; k_{\mathrm{min}}, k_{\mathrm{max}}, k_{\mathrm{mid}}) = k_{\mathrm{min}} + (k_{\mathrm{max}} - k_{\mathrm{min}})\cdot f(x; 0,1, k) $$
where
$$ k = (k_{\mathrm{mid}} - k_{\mathrm{min}}) / (k_{\mathrm{max}} - k_{\mathrm{min}}) $$
Now we consider the function $g(x) = x^p$. This function satisfies $g(0) = 0$, $g(1) = 1$, and it is guaranteed to be increasing between 0 and 1. It suffices to find the $p$ such that $g(1/2) = k$. We solve:
$$ (1/2)^p = k \iff p = - \log_2 k $$
So in the end we can take the function
$$  f(x; k_{\mathrm{min}}, k_{\mathrm{max}}, k_{\mathrm{mid}}) = k_{\mathrm{min}} + (k_{\mathrm{max}} - k_{\mathrm{min}}) x^{\log_2 (k_{\mathrm{max}} - k_{\mathrm{min}}) - \log_2 (k_{\mathrm{mid}} - k_{\mathrm{min}})} $$


Como organizar as colunas numa tabela

Question: Há alguma forma de fazer colspan para metade de uma coluna?!

     ola
     ola
     ola
     ola

     ola
     ola
     ola

 </table

Gostava que as colunas da segunda linha ficassem a cobrir a linha toda e que todas as células tenham o mesmo comprimento!!

Como nesse exemplo, as 2 colunas superiores estao a cobrir a tabela toda e a separação está no meio...
Answer: Você pode fazer isso com colspan e definindo um width de acordo com a quantidade de colunas dividindo por 100%. Por exemplo: 3 colunas = 33.3%, 4 colunas = 25% e por aí vai...
Exemplo de 2 linhas de 4 x 3 colunas:

       ola
       ola
       ola
       ola

       ola
       ola
       ola

3x2:

       ola
       ola
       ola

       ola
       ola

5x4:

       ola
       ola
       ola
       ola
       ola

       ola
       ola
       ola
       ola

A lógica é meio complicada, mas se baseia nos valores dos colspan somados e no número de colunas. Veja que na linha onde possui mais colunas, eu não especifico colspan na primeira e última, apenas nas do meio. A soma dos colspan + número de colunas sem colspan de cada linha devem ser iguais. No primeiro exemplo, veja que somando o valor de colspan="3" na primeira linha + 2 colunas sem colspan, dá 5. Na segunda linha também dá 5 somando os valores do colspan. Esses números sobem à medida que vai se adicionando mais colunas.
Veja um outro exemplo com 5x3:

       ola
       ola
       ola
       ola
       ola

       ola
       ola
       ola

Veja que a lógica segue a mesma: somando os valores da primeira linha, 1+4+3+4+1 = 13. Na segunda linha também: 3+7+3 = 13.
Comment: era exactamente isso que eu pretendia, muito obrigado pela resposta, entendi perfeitamente
Answer: Só usar colspan = numero total de colunas

     ola
     ola
     ola
     ola

     ola

 </table
Comment: eu quero 4 elementos na primeira linha e 3 na segunda
Comment: editei a minha pergunta, talvez seja mais facil entender o que pretendo com a imagem
Comment: @Droopy na figura vejo 2 células na primeira, uma linha branca estreita no meio e uma linha com 3 células
Comment: exato, a linha branca não interessa, eu quero obter esse resultado quando uso 2 celulas numa linha e 3 noutra
Comment: por exemplo se eu meter 2 celulas numa linha e 3 noutra linha a linha que tem as 2 celulas vai ficar com um espaço vazio
Comment: @Droopy, não consegue, faz uma tabela com duas linhas, e em cada linha mete uma tabela. A primeira divide em 4 ou 2 células e a segunda divide em 3 células

Como organizar as colunas numa tabela


Get $form_state backup and migrate filter extended class

Question: I have form altered the backup and migrate quick backup screen (admin/config/system/backup_migrate) and added a text field. I'd like to use the value of the field to create a new node just before the backup is done. I found a way to "hook" backup and migrate just before it performs a backup, which is great. However, I need to get $form_state['values']['my_value'] and pass that to my function that creates a new node. I can't figure out how to get that passed to the pre_backup() inside the extended class backup_migrate_filter.
Answer: From your question, I get you altered the form built from the following function.
/**
 * The quick backup form.
 */
function backup_migrate_ui_manual_quick_backup_form($form, &$form_state, $inline = TRUE) {
  backup_migrate_include('profiles', 'destinations', 'sources');
  drupal_add_js(drupal_get_path('module', 'backup_migrate') .'/backup_migrate.js');

  $form = array();

  // Theme the form if we want it inline.
  if ($inline) {
    $form['#theme'] = 'backup_migrate_ui_manual_quick_backup_form_inline';
  }

  $form['quickbackup'] = array(
    '#type' => 'fieldset',
    "#title" => t("Quick Backup"),
    "#collapsible" => FALSE,
    "#collapsed" => FALSE,
    "#tree" => FALSE,
  );

  $form['quickbackup']['source_id'] = _backup_migrate_get_source_pulldown(variable_get('backup_migrate_source_id', NULL));

  $form['quickbackup']['destination'] = _backup_migrate_get_destination_pulldown('manual backup', variable_get('backup_migrate_destination_id', 'download'), variable_get('backup_migrate_copy_destination_id', ''));

  $profile_options = _backup_migrate_get_profile_form_item_options();
  $form['quickbackup']['profile_id'] = array(
    "#type" => "select",
    "#title" => t("Settings Profile"),
    '#default_value' => variable_get('backup_migrate_profile_id', NULL),
    "#options" => $profile_options,
  );

  $form['quickbackup']['description_enabled'] = array(
    '#type' => 'checkbox',
    "#title" => t("Add a note to the backup"),
  );
  $form['quickbackup']['description'] = array(
    '#type' => 'backup_migrate_dependent',
    '#dependencies' => array(
      'description_enabled' => TRUE,
    ),
  );

  $form['quickbackup']['description']['description'] = array(
    '#type' => 'textarea',
    "#title" => t("Note"),
    '#description' => t('This note will be saved with the backup file and shown on the listing page.'),
  );

  $form['advanced'] = array(
    '#type' => 'markup',
    '#markup' => '
' . t('For more backup options, try the advanced backup page.', array('!advancedurl' => url(BACKUP_MIGRATE_MENU_PATH . '/export/advanced'))) . '
',
  );

  $form['quickbackup']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Backup now'),
    '#weight' => 1,
  );

  $form['#validate'] = array('backup_migrate_ui_manual_quick_backup_form_validate');
  $form['#submit'] = array('backup_migrate_ui_manual_quick_backup_form_submit');

  return _backup_migrate_ui_action_form($form, $form_state, 'backup');
}

The only way to pass a value submitted in a form to a hook is to save it into a persistent variable, exactly in the same way a submission handler does.
/**
 * Submit the quick backup form.
 */
function backup_migrate_ui_manual_quick_backup_form_submit($form, &$form_state) {
  backup_migrate_include('profiles', 'destinations');
  if (user_access('perform backup') && !empty($form_state['values']['settings'])) {
    // Save the settings for next time.
    variable_set("backup_migrate_source_id", $form_state['values']['source_id']);
    variable_set("backup_migrate_destination_id", $form_state['values']['destination_id']);
    variable_set("backup_migrate_copy_destination_id", $form_state['values']['copy_destination_id']);
    variable_set("backup_migrate_profile_id", $form_state['values']['profile_id']);

    // Do the backup.
    backup_migrate_ui_manual_backup_perform($form_state['values']['settings']);
  }
  $form_state['redirect'] = BACKUP_MIGRATE_MENU_PATH;
}

Your hook_form_alter() implementation needs to do two things:

Add the form element, as you already did
Add a submission handler to $form['#submit'] ($form['#submit'][] = 'mymodule_submission_callback';)
Comment: Most excellent! I should have mentioned that I did end getting the clues I needed from a friend and I added my function to the submit handler. Thank you for replying! An upvote for you, sir.


Capturar informação e utilizar quando necessitar Java

Question: Estou a pensar em implementar um função que capta o usuário logado, ainda não imagino como posso implementar tal função, gostaria de saber o que é usual e propicio para que eu registre o nome e o código do usuário enquanto o software executa. Minha aplicação é feita em Java.
Comment: Quando o usuário se logar você pode jogar ele na sessão `HttpSession sessao = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);`, se a sua aplicação for web.
da uma lida aqui [httpsession](http://docs.oracle.com/javaee/5/api/javax/servlet/http/HttpSession.html)
Answer: Caso sua aplicação seja web, essas informações são geralmente guardadas na sessão da aplicação. Veja aqui uma boa explicação sobre sessões:
http://klauslaube.com.br/2012/04/05/entendendo-os-cookies-e-sessoes.html
Caso sua aplicação seja desktop, você pode guardá-la em um Map que é acessado publicamente, como um singleton e sincronizado. Veja a seguir a definição de singleton:
http://pt.wikipedia.org/wiki/Singleton
Session
Veja a seguir um exemplo usando HTTP Session para servlets:
....
import javax.servlet.http.HttpSession;
....

@WebServlet("/MyServlet")
public class MyServlet extends HttpServlet {
....

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        // recupera a sessõa
        HttpSession session = request.getSession();

        // colocar um valor na sessão
        session.setAttribute("user", "Pankaj");

        ....

        // recupera valor da sessão
        String userName = (String) session.getAttribute("user");

        ....

    }

....

}

Desktop
Veja uma classe que poderia ser usada para uma sessão Desktop:
package com.myapp.session;

import java.util.Hashtable;
import java.util.Map;

public class Session {

    // note that HashTable is synchronized
    private Map<String, Object> _map = new Hashtable<String, Object>();

    private static Session _session = new Session();

    public static Session getSession() {
        return _session;
    }

    public void setAttribute(String key, Object value) {
        _map.put(key, value);
    }

    public Object getAttribute(String key) {
        return _map.get(key);
    }
}

Daí, para utilizar a sessão faça o seguinte:
Session session = Session.getSession();
....
// coloca um valor na sessão
session.setAttribute("user", "Pankaj");

....

// recupera valor da sessão
String userName = (String) session.getAttribute("user");

Comment: Veja agora que você tem um exemplo de como utilizar sessões para servlets e como criar e utilizar sessões para aplicações Desktop.
Comment: ok, Eduardo tem algum exemplo que posso imaginar para começar a bolar como vou fazer? Obrigado
Comment: Sua aplicação é web ou desktop? Se for web, que tecnologia você está utilizando?
Comment: minha aplicação é Desktop
Comment: Caso a resposta esteja correta, por favor de um "tick" na seta verde logo abiaxo da pontuação da questão. Obrigado :)
Comment: Eduardo acabei de testar aqui e funcionou muito obrigado pelo help abraços.


Advantages of Riesz theorem over Caratheodory Extension theorem

Question: I apologize in advance if this question seems vague. I'm self studying Real and Complex Analysis by W. Rudin and I've been reading the proof of Riesz theorem in the second chapter which is then used in the construction of the Lebesgue measure.
In an analysis class I took a few years ago in undergrad we used another approach and used the Caratheodory extension theorem.
I may be biased but I find the second approach much more intuitive in the immediate applications, specifically in the construction of the Lebesgue measure. My question is then the following:

Are there measures that are more easily defined (or that can only be defined) using Riesz theorem?

That is, is there any significant difference in the two approaches?
Comment: Well, the Riesz Representation Theorem doesn't just give you a way of defining measures, although it is useful for that.  It tells you that certain linear functions are induced by integration against a measure, and thereby gives you a more concrete representation of certain dual spaces.
Comment: Please give exact settlements of these theorems. There are different variations, so we need to know exactly which ones you are comparing.
Comment: As I am not the OP I'll give the statements in the comment:
Caratheodory Extension Theorem : https://en.wikipedia.org/wiki/Carath%C3%A9odory%27s_extension_theorem
Reisz representation theorem probably referred by the OP: Theorem 2.14 of page 40 of the book, or page 55 of the PDF : https://59clc.files.wordpress.com/2011/01/real-and-complex-analysis.pdf
Comment: @PeterMorfe so the Caratheodory theorem provides a way to construct the measure then. This is actually another think I was wondering about, Riesz Representation theorem is usually used to prove existance of certain measures, but does not provide any way to construct them.
Answer: General comments: Riesz is easier to remember Arguably Lebesgue measure is an example (of a measure where the Riesz construction is easier).  The annoying thing about the Caratheodory extension theorem is you always have to check whether or not a certain class of sets is a semi-algebra, semi-ring, etc.  I personally never could remember the definitions of these objects.  Compared to remembering the statement of Caratheodory and checking its assumptions, I would say it is much easier to check that Riemannian integration defines a bounded linear functional on $C_{c}(\mathbb{R}^{d})$ and then invoke Riesz to get Lebesgue integration for free.
I want to emphasize what is nice about this proscription: if I have an idea for a measure $\mu$ that I already more or less understand, if I can recast it as a (bounded) linear functional on an appropriate space, then I can more-or-less mindlessly apply the Riesz Theorem, no further questions asked.  We will see this in action in another example below.
General comments: Riesz Theorem has applications As for intuition, yes, the Caratheodory approach for Lebesgue measure is more concrete since you are building a measure from a set function --- you start with measures of elementary sets, then extend to "all" sets.  However, I do not think  Rudin proves the Riesz Theorem just to define Lebesgue measure --- he wants to prove the Riesz theorem for its own sake.  It has its own applications, which make it worth including in the book --- see the last part of this answer for a deeper (by now classical) application.
General comments: Intuition  If you think of a measure as describing how large a set is, then Caratheodory is intuitive --- start with elementary sets, then somehow "generate" the sizes of other sets by invoking the theorem.  However, this geometric interpretation isn't the only way to think about measures.  One of the other major applications of measure theory is in probability.  Here a probability measure often describes the law of a random variable.  The most natural way of thinking about that is if $X$ is my random variable (say, real-valued) and $f$ is some (say, continuous) function, then the law of $\mu_{X}$ is a probability measure such that
\begin{equation*}
\mathbb{E}(f(X)) = \int_{\mathbb{R}} f(y) \, \mu_{X}(dy).
\end{equation*}
You can think of $f(X)$ as being an "observable" --- it gives me a snapshot of $X$.  The Riesz Theorem tells us that (if $X$ is real-valued) $\mu_{X}$ is uniquely determined by these "expectation values" (i.e. the integrals $\int f d \mu_{X}$ for compactly supported, continuous $f$).  This is often useful to know in probability --- you can use it to check that two random variables have the same law, for example.  As we will see below, in some cases, it is nice to know that I can construct my $X$ through the knowledge of these integrals.
General comments: Similarities in the proof I think it is important to note that many of the arguments appearing in the standard proof of the Caratheodory extension theorem also appear in Rudin's proof of the Riesz representation theorem.  The two results are closely related.  It is often true (even morally true) that what you can prove with one, you can also prove with another.
Another example: Volume measures  Given a smooth compact orientable manifold $M$, we know there is a non-vanishing top dimensional form $\omega$ such that
\begin{equation*}
\int_{M} \omega > 0.
\end{equation*}
We can then define integration "$d\text{Vol}"$ on $M$ by
\begin{equation*}
\int_{M} f \, d\text{Vol} = \int_{M} f \omega \quad \text{if} \, \, f \in C^{\infty}(M).
\end{equation*}
A natural question is: what is "$d \text{Vol}$"?
The Riesz Theorem provides an easy answer.  The linear functional $f \mapsto \int_{M} f \, d \text{Vol}$ has the following estimate
\begin{equation*}
\left| \int_{M} f d \text{Vol} \right| \leq \|f\|_{C(M)} \int_{M} \omega.
\end{equation*}
Hence we can extend it to a linear functional on $C(M)$ by density.  This induces a measure by the Riesz Theorem.  Therefore, there is a Borel measure $\text{Vol}$ on $M$ that gives "$d\text{Vol}$".  Since $f \equiv 1$ defines a $C^{\infty}$ function, it is not hard to show that $\text{Vol}(M) = \int_{M} \omega$.
Here I do not know how to define $\text{Vol}$ using the Caratheodory theorem.  I suspect it is possible to define it using Hausdorff measure.  This should give a lot more information than what the Riesz Theorem does, but it is nice to have quick constructions for a first pass.
Another example: invariant measures in ergodic theory  Invariant measures are basic objects in ergodic theory.  If $X$ is a compact metric space and $T : X \to X$ a Borel measurable map, we would like to know whether or not there is a Borel probability measure $\mu$ on $X$ such that $T_{*}\mu = \mu$, i.e.
\begin{equation*}
\mu(A) = T_{*}\mu(A) := \mu(T^{-1}(A)).
\end{equation*}
One way to think of this is if $Z$ is a $X$-valued random variable with law $\mu$, then $T(Z)$ also has law $\mu$ --- so the sequence $\{T^{n}(Z)\}_{n \in \mathbb{N} \cup \{0\}}$ is statistically "stationary" (identically distributed).  You can interpret this as saying that $\mu$ is an "equilibrium measure" for $T$.
Do these things exist?  In the setting above, the answer is yes and there is a very simple proof --- using the Riesz Theorem in conjunction with the Banach-Alaoglu Theorem.  Fix a $x \in X$ and consider the measures
\begin{equation*}
\mu_{N} = N^{-1}\sum_{i = 0}^{N-1} \delta_{T^{i}(x)}.
\end{equation*}
We can think of this is a bounded sequence in $C(X)^{*}$ by the Riesz-Theorem, and the Banach-Alaoglu Theorem gives us compactness.  In fact, since $C(X)$ is separable, we have sequential compactness so we can extract a weak-$*$ accumulation point $\mu$.  It is possible to show that $T_{*} \mu = \mu$, that is, $\mu$ is an invariant measure for $T$.
This is probably the best example of a result where the implicit nature of the Riesz Theorem wins out over the constructive approach of the Caratheodory Theorem.  I have my doubts about doing this with Caratheodory.  Anyway, the above existence argument goes by the name Krylov-Bogoliubov Theorem.
Basically the same idea is used to obtain some fundamental results in the mathematical foundations of statistical mechanics.  See the remarks on the Ising model below.
A related example is Haar measure on a locally compact group: at least one way to prove such a measure exists involves the construction of a linear functional first, then an invokation of Riesz.  (See Folland's book on harmonic analysis for such a proof.)
Another example: finite state Markov chains  Let $S$ be a finite set and let $P : S \times S \to [0,1]$ be a function so that, for each $s \in S$, we have
\begin{equation*}
\sum_{s' \in S} P(s,s') = 1.
\end{equation*}
Given a measure $p$ on $S$, we say that a $S$-valued stochastic process $\{X_{n}\}_{n \in \mathbb{N} \cup \{0\}}$ on a probability space $(\Omega,\mathcal{F},\mathbb{P})$ is a Markov chain with transition matrix $P$ and initial measure $p$ if, for each $s \in S$,
\begin{equation*}
\mathbb{P}\{X_{0} = s\} = p(s)
\end{equation*}
and, for each $s_{0},\dots,s_{n},s_{n+1} \in S$,
\begin{equation*}
\mathbb{P}\{X_{n+1} = s_{n+1} \, \mid \, X_{0} = s_{0}, \dots, X_{n} = s_{n}\} = P(s_{n},s_{n+1}).
\end{equation*}
Here is a very easy and "intrinsic" construction of such a process, using the Riesz theorem.  Let $\Omega = S^{\mathbb{N} \cup \{0\}}$.  If we put the discrete topology on $S$ and then the product topology on $\Omega$, this makes $\Omega$ a compact Hausdorff space by the Tychonoff theorem.  Let $\mathcal{C} \subseteq C(\Omega)$ denote the space of "cylindrical" functions that only depend on finitely many coordinates, that is, $f \in \mathcal{C}$ if and only if $f(X) = F(X_{0},X_{1},X_{2},\dots,X_{N})$ for some $F : S^{\{0,1,\dots,N\}} \to \mathbb{R}$ and $N \in \mathbb{N}$.  Now define a linear functional $\phi : \mathcal{C} \to \mathbb{R}$ by
\begin{equation*}
\phi(f) = \sum_{s_{0} \in S} \sum_{s_{1} \in S} \dots \sum_{s_{N} \in S} F(s_{0},s_{1},\dots,s_{N}) p(s_{0}) P(s_{0},s_{1}) \dots P(s_{N-1},s_{N}) \quad \text{if} \, \, f(X) = F(X_{0},\dots,X_{N}).
\end{equation*}
It is not hard to check that this is well-defined (doesn't depend on the choice of $F$ or $N$, only on $f$) and
\begin{equation*}
|\varphi(f)| \leq \|f\|_{C(\Omega)}.
\end{equation*}
Therefore, by density of $\mathcal{C}$, there is a unique extension $\Phi : C(\Omega) \to \mathbb{R}$ of $\varphi$ such that $|\Phi(f)| \leq \|f\|_{C(\Omega)}$.  By the Riesz Theorem, there is a measure $\mathbb{P}$ on the Borel $\sigma$-algebra $\mathcal{F}$ of $\Omega$ such that
\begin{equation*}
\Phi(f) = \int_{\Omega} f(\tilde{X}) \, \mathbb{P}(d\tilde{X}).
\end{equation*}
If we define $X_{n} : \Omega \to S$ by $X_{n}((\tilde{X}_{0},\tilde{X}_{1},\dots)) = \tilde{X}_{n}$, then the sequence of random variables $\{X_{n}\}_{n \in \mathbb{N} \cup \{0\}}$ on $(\Omega,\mathcal{F},\mathbb{P})$ is a Markov chain with transition probability $P$ and initial distribution $p$ as we sought.
A probabilist could very well complain that the above construction is silly.  In response, I would submit the following special case: if $S = \{0,1\}$, $P : S \times S \to [0,1]$ is the constant function $P \equiv \frac{1}{2}$, and $p : S \to [0,1]$ is also constant $p \equiv \frac{1}{2}$, then the construction above gives us an i.i.d. sequence of Bernoulli random variables.  That is, the process $\{X_{n}\}_{n \in \mathbb{N}}$ is determined by the property that, for each $s_{0},\dots,s_{N} \in \{0,1\}$,
\begin{equation*}
\mathbb{P}\{X_{0} = s_{0},\dots,X_{N} = s_{N}\} = 2^{-(N+1)} = \prod_{i = 0}^{N} \mathbb{P}\{X_{i} = s_{i}\}.
\end{equation*}
Such Bernoulli sequences are important building blocks for other stochastic processes (or other measures --- another construction of Lebesgue measure uses a Bernoulli sequence), and the proof that such a sequence exists can be a bit of a bug-a-boo.
A last note: here it is not very hard to construct the Markov chain above using Caratheodory's extension theorem.  I leave it to you to figure out how to do this, and then you can decide which is easier to achieve.
Applications: Ising model As we saw above, when you combine the Riesz Theorem with the Banach-Alaoglu Theorem, you get powerful existence results.  Here is a very nice application: in the Ising model of statistical mechanics, one is interested in studying what physicists think of as "statistical/physical equilibrium."  It turns out that such equilibria mathematically correspond to probability measures, which, for the Ising model, are measures on $\{-1,1\}^{\mathbb{Z}^{d}}$.  To prove that such measures exist, a by now standard approach is to start with certain simpler measures $(\mu_{N})_{N \in \mathbb{N}}$ --- you can think of $\mu_{N}$ as the probability measure describing physical equilibrium in an "experiment" conducted in $\mathbb{Z}^{d} \cap [-N,N]^{d}$ rather than the whole "universe" $\mathbb{Z}^{d}$ --- and then use compactness (guaranteed by the Banach-Alaoglu Theorem and Riesz Theorem) to obtain a sub-sequential limit $\mu = \lim_{j \to \infty} \mu_{N_{j}}$, which turns out to be exactly the kind of physical equilibrium (in the whole of $\mathbb{Z}^{d}$, not just a box) we seek.  In the study of the Ising model, one then goes on to ask what properties $\mu$ has, how many possible equilibria $\mu$ there are, and more.  (It is easy to construct the measures $(\mu_{N})_{N \in \mathbb{N}}$, and the limiting measure $\mu$ is not unique in general --- there can be many physical equilibria.)
Comment: I would have never hoped to get such a rich and insightful answer when I asked this question 3 years ago, thank you so much!
Comment: @Ettore either you asked the question or I would've =D.


Prove that $A-I_n$ is idempotent

Question:
Let $A ∈ R^{n×n}$ be a nonzero singular matrix with the property that $A^2 = A$.
Show that $A − I_n$ is also idempotent.

I tried the following:
$(A - I_n)^2 = (A-I_n)(A-I_n) = A(A-I_n)-I_n(A-I_n) = A^2 - A - A + I_n = A^2 - 2A +I_n = A - 2A + I_n = I_n - A$
Unfortunately, to the best of my knowledge, that doesn't qualify as an answer, as the identity I must get is the following: $A − I_n$.
Since that does not equal to the final form that I got upon simplifying the square, I am sort of lost. Is there something that I did wrong in my steps?
Answer: Your computations are O.K. The statement above is wrong. If $A$ is idempotent, then $I_n-A$ is idempotent !
Comment: Thanks! I have this question on an assignment, so in that case, is the instructor's original question simply stated wrong, and the question should be asking to prove $I_n-A$ instead of $A-I_n$?
Comment: Yes, $I_n-A$ instead of $A-I_n$.
Answer: The correct statement is $I-A$ is idempotent.
If $$0 = A^2 - A = A(A - I)$$
then the minimal polynomial $\mu_A(x)$ divides $x(x-1)$.
If $\mu_A(x) = x$ then $A = 0$ and if $\mu_A(x) = x-1$ then $A = I$, both cases being trivial. Thus assume $\mu_A(x) = x(x-1)$.
Recall that for any matrix $B$ and scalar $\lambda$ we have $\mu_{B - \lambda I}(x) = \mu_B(x + \lambda)$. Also $\mu_{-B}(x) = (-1)^n\mu_{B}(-x)$.
Therefore $$\mu_{A - I}(x) = \mu_A(x+1) = (x+1)x \implies \mu_{I - A}(x) = x(x-1) = x^2 - x$$
We conclude $(I-A)^2 = I-A$.

Prove that $A-I_n$ is idempotent


How to prove $CAA^t=BAA^t$ implies $CA=BA$?

Question: Suppose $A$, $B$, $C$ are $n\times n$ matrices. $A'$ denotes the transpose of $A$. $CAA'=BAA'$. How to prove $CA=BA$?
Comment: May I suggest answering your own question, if you've truly gotten it?
Comment: Show that the kernel on the left of AA' equals the kernel on the left of A.
Comment: @Phira would you mind answering? I would be interested.
Answer: The given equation $(C-B)AA'=0$ means that each row of the matrix $C-B$ is in the left kernel of $AA'$. The desired equation $(C-B)A=0$ means that each row of the matrix $C-B$ is in the left kernel of $A$. So, I want to show that the (left) kernel of the matrix $AA'$ is already the (left) kernel of the matrix $A$.
Suppose the vector $v$ is in the left kernel of $AA'$, i.e. $$vAA'=0$$ which implies $$vAA'v'=0=(vA)\cdot (vA)'=\|vA\|^2$$ (where $v'$ is the transpose of the vector $v$).
So, $vA$ is already the zero vector and therefore, $v$ is in the left kernel of $A$.


How can I display a picture from a field as the user picture rather than the drupal default with user-picture.tpl.php?

Question: Because my site requires user pictures to be approved, the default Drupal user picture is not suitable.
Instead, I want to show a picture from a field in each user's profile as the user's profile picture.
The field is "field_profile_picture".
The image style is "profile_picture".
Based on this tutorial, I put the following code in user-picture.tpl.php in my theme's templates folder:
if (!empty($user->field_profile_picture['und'][0]['filename'])) {
  echo theme('image_style', array('style_name' => 'profile_pic', 'path' => file_build_uri($user->field_profile_picture['und'][0]['filename'])));
}

This doesn't result in any PHP errors but no picture is displayed.  It appears that field_acc_profile_picture is evaluating as empty because even if I put a print "Hello world"; inside the {} it doesn't appear.  However, I am sure that the field has a value because I can see the picture displayed in views.
Answer: I don't think $user->field_profile_picture['und'][0]['filename'] would be set by default, you normally only get the fid column (this does vary depending on context, but you should always get the fid column either way).
This sort of code always works for me:
if (!empty($user->field_profile_picture[LANGUAGE_NONE][0]['fid'])) {
  // Load the file
  $file = file_load($user->field_profile_picture[LANGUAGE_NONE][0]['fid']);

  // Note the style name is "profile_picture" as explained in your question,
  // not "profile_pic" which was in your original code
  echo theme('image_style', array('style_name' => 'profile_picture', 'path' => $file->uri));
}

If you're worried about the extra overhead involved with potentially loading the file twice, don't be, Drupal caches the object the first time round.
It the above doesn't work it's likely that the $user object is not fully loaded and so the fields haven't been attached. If that's the case, load the user like this:
$account = user_load($user->uid);

And then use the $account object to test for the field value.
Comment: One quick addition: I actually needed to load `$account` as `$account = user_load($account->uid);`  Otherwise, when displaying the user pictures in the privatemsg module it will show the logged-in user's picture for all users.
Comment: Thank you so much!  I needed to add `$account = user_load($user->uid);` to get it to work properly.
Comment: Any update on this? I can't get it to work at all. :)


Counterexamples to the following logical statements about sets

Question: $(1)$  $A \subset B$ or $A \subset C$ $\iff$ $A \subset (B \cup C)$ and
$(2)$  $(A \times B) \subset (C \times D) \implies A \subset C$
Is $(1)$ true? Or does the implication only hold in the forward direction? A friend of mine and I are beginning to work through Munkres's Topology and he is convinced it is only the forward direction, but I think it is a logical equivalence.
Note
Munkres defines "or" to mean "either A or B or both"

Edit 2
$(2)$ was asked after the original question, which was $(1)$. For both questions, Brian M. Scott helped with a counterexample.
Comment: What if $B=\{0\},C=\{1\}$, and $A=\{0,1\}$?
Comment: Not necessarily, though this one's a bit tricky. What if $A=\{0\}$, $B=\varnothing$, and $C=D=\{1\}$?
Comment: Then it is indeed only a forward implication. Thanks @BrianM.Scott
Comment: @BrianM.Scott I can't think of a counterexample to show why $(A \times B) \subset (C \times D) \implies A \subset C$ and $B \subset D$. Wouldn't this implication hold even if $A, B$ were empty? Thanks for all your help by the way.
Comment: @JJR I think that if $B$ is assumed non-empty in (2), then the theorem holds.
Answer: A counterexample for (1) is $B=\{0\},C=\{1\}$, and $A=\{0,1\}$.
A counterexample for (2) is $A=\{0\}, B=\varnothing$, and $C=D=\{1\}$.


$\sum_{n=1}^\infty \frac{a_{n+1}-a_n}{a_{n+1}}$ diverges

Question: Let $(a_n)_{n\ge 1}$ is an increasing sequence of of positive numbers such that $a_n \to \infty$ as $n \to \infty $. Then $\sum_{n=1}^\infty \frac{a_{n+1}-a_n}{a_{n+1}}$ diverges.
Answer: Verify that the Cauchy criterion isn't satisfied: Since $(a_n)$ is monotonically increasing,
$$\sum_{n=k}^m \frac{a_{n+1}-a_n}{a_{n+1}} \geqslant \sum_{n=k}^m \frac{a_{n+1}-a_n}{a_{m+1}} = \frac{a_{m+1}-a_k}{a_{m+1}}.$$
Answer: Let $b_n=a_{n+1}-a_n$ and $S_n=b_1+b_2+\cdots+b_n=a_{n+1}-a_1$ so
$$\frac{a_{n+1}-a_n}{a_{n+1}}=\frac{b_n}{S_n+a_1}\sim_\infty\frac{b_n}{S_n}$$
but
$$\frac{b_{n+1}}{S_{n+1}}+\cdots+\frac{b_{n+p}}{S_{n+p}}\ge\frac{b_{n+1}+\cdots+b_{n+p}}{S_{n+p}}=\frac{S_{n+p}-S_n}{S_{n+p}}\xrightarrow{p\to\infty}1$$
so by the Cauchy criterion the series $\sum\frac{b_n}{S_n}$ is divergent so the given series is also divergent by comparison.


How to store and retrieve asp:fileupload from session in VB.NET

Question: My program has an asp:FileUpload control that a user will select a file with. There is a button on the page that the users can click to do some data manipulation. When that button is clicked, the asp:fileUpload control looses the file the user has chosen.
I have found code that apparently works for C# programs, but as I am coding in VB.NET, I tried converting that code.
This is the C# code I used in the converter:
    if (Session["FileUpload1"] == null && FileUpload1.HasFile)
    {
        Session["FileUpload1"] = FileUpload1;
        lblFilename.Visible = true;
        lblFilename.Text = FileUpload1.FileName;
    }
    else if (Session["FileUpload1"] != null && (!FileUpload1.HasFile))
    {
        FileUpload1 = (FileUpload)Session["FileUpload1"];
        lblFilename.Visible = true;
        lblFilename.Text = FileUpload1.FileName;
    }
    else if (FileUpload1.HasFile)
    {
        Session["FileUpload1"] = FileUpload1;
        lblFilename.Visible = true;
        lblFilename.Text = FileUpload1.FileName;
    }

This is what the converter gave me as a VB result:
    If Session("FileUpload1") Is Nothing AndAlso FileUpload1.HasFile Then
        Session("FileUpload1") = FileUpload1
        lblFilename.Visible = True
        lblFilename.Text = FileUpload1.FileName
    ElseIf Session("FileUpload1") IsNot Nothing AndAlso (Not FileUpload1.HasFile) Then
        FileUpload1 = CType(Session("FileUpload1"), FileUpload)
        lblFilename.Visible = True
        lblFilename.Text = FileUpload1.FileName
    ElseIf FileUpload1.HasFile Then
        Session("FileUpload1") = FileUpload1
        lblFilename.Visible = True
        lblFilename.Text = FileUpload1.FileName
    End If

This is what I changed it to in order to use it for my program:
    If Session("fileuPreCalImage") Is Nothing AndAlso fileuPreCalImage.HasFile Then
        Session.Add("fileuPreCalImage", fileuPreCalImage)
    ElseIf Session("fileuPreCalImage") IsNot Nothing AndAlso (Not fileuPreCalImage.HasFile) Then
        fileuPreCalImage = CType(Session("fileuPreCalImage"), FileUpload)
    ElseIf fileuPreCalImage.HasFile Then
        Session("fileuPreCalImage") = fileuPreCalImage
    End If

The code doesn't compile because of an error, in the 4th line of my code, that says: "Value of type 'FileUpload' cannot be converted to 'FileUpload'.
Is there a way I can do this in VB.NET to maintain the FileUpload file after a button click?
Edit:  I took the C# code from this answer https://stackoverflow.com/a/18656681/5265207
Answer: Replace----
fileuPreCalImage = CType(Session("fileuPreCalImage"), FileUpload)

By------
fileuPreCalImage =  DirectCast(Session("fileuPreCalImage"), System.Web.UI.WebControls.FileUpload)

Comment: What that replace will do? A new issue? Explain your answer.


Measure Algebra Question

Question: Background:
Let $G$ be a locally compact group, and define $M(G)$ to be the vector space of all regular complex measures defined on $G$, normed by total variation.
For $\mu,\nu\in M(G)$, define the product $\mu * \nu$ as follows:
Define $\varphi\in C_{0}(X)^{*}$ by $$\varphi(f) = \int_{G}\int_{G}f(xy)d\mu(x)d\nu(y)\text{, for all }f\in C_{0}(X)$$
By the Riesz-Representation Theorem, there is a unique element (call it $\mu*\nu$) of $M(G)$ such that $\varphi(f) = \int_{G}fd(\mu *\nu)$.
This turns $M(G)$ into an algebra.

Proposition:
I'm reading a book which says that it is an immediate consequence of Fubini's Theorem that
$$\int_{G}\int_{G}f(xy)d\mu(x)d\nu(y) = \int_{G}\int_{G}f(xy)d\nu(y)d\mu(x)$$

My Question:
In order to apply Fubini's Theorem, we need
$$\int_{G\times G}|f(xy)|d(\mu\times\nu) < \infty$$
which doesn't seem to follow from $f\in C_{0}(X)$.

Counterexample:
Take $G = \mathbb{Z}$, $f\in C_{0}(G)$ defined by $f(n) = \frac{1}{|n|}$. Then $\int_{G}f(x)d\mu(x) = \sum_{n=-\infty}^{\infty}\frac{1}{|n|} = \infty$.
From here it follows that for fixed $y\in G$, we have $\int_{G}f(xy)d\mu(x) = \infty$ so obviously the hypothesis of Fubini's Theorem is not satisfied.
But in this case, $f$ is non-negative, so the desired integral equation instead follows from Tonelli's Theorem, so all is not lost.

So does the Proposition follow from a different argument? or is an additional hypothesis on $G$ required?
Comment: Thanks Zev, I didn't know it was that easy to type in bold! :)
Comment: No problem - [see here](http://meta.stackoverflow.com/editing-help) for other Markdown formatting tips
Answer: I don't know if this is the answer, but it just occured to me that for $\mu\in M(G)$ to have finite norm, it must have finite total variation, which I think would be sufficient to guarantee the hypothesis of Fubini's Theorem.  Maybe someone with more knowledge than I can confirm this?
Comment: Yes, that is the point.  The convolution of two measures of finite variation is again a measure of finite variation.  Convolution *may* also be defined for certain other measures as well, but that is not involved in the claim in the question.
Comment: Thank you for confirming.  Communicating a question to others seems to be quite illuminating.

Measure Algebra Question


Is there any way to see the content of the theme registry?

Question: I was wondering if there is a way to see (print out) the content of the theme registry.
I've looked in the database; it seems to be stored in the cache table, if I understand things right, but the theme registry itself is stored as a blog.
When I looked at the blog, I couldn't seem to make any sense of what was there. It all seemed to look like hex values.
Answer: If you want to see the content of the theme registry, you can use _theme_load_registry(). The first argument could be the global $theme for the currently used theme, or one of the objects returned by list_themes().
As the function name is prefixed by an underscore, I would suggest to use it only for debugging purposes. (Theoretically, future Drupal versions could drop those private functions, and that would not probably be taken as API change.)
If you have installed Devel, you can use the following code:
global $theme;

$registry = _theme_load_registry($theme);
dsm($registry);

You can also simply visit the devel/theme/registry page which shows you the theme registry content.
Answer: See theme_get_registry()
This simple function returns an array of theme registry
Answer: hook_theme_registry_alter can help in this regard.
function mymodule_theme_registry_alter(&$theme_registry){

$theme_registy would result entire theme registry information.
The hook is invoked as the theme cache is re-built


What should be considered when getting a band PA?

Question: I'm in a band and we just started out, but I need to know what speakers we should get. Like I said we're just starting out so we might not need them for a while, but I still want to be prepared. We have a drummer, an electric guitarist, a bass player, and a pianist. We would sort of all share the vocals.
I'm looking for speakers that are easy to use. Basically I would like to be able to get to a concert plug in our stuff, and play. I don't want to really worry about the speakers. I've been looking online for speakers but I have no idea what half of the stuff they say even means.
I'm honestly not really sure where we would be playing, but probably relatively small venues. I don't know which instruments I would need to put through the speakers, I think just the vocals (2 or 3) and the piano. Any suggestions on what to buy?
Comment: Closing people: This is related to performing music, extreme prejudice. It's not "what brand", it's "what type of equipment". The obsolete part when it comes to equipment does not fit music equipment very well either.
Comment: Hi. I've changed the title of your question to better capture the question. Sorry if I lost your intention, please change if so. Some more information is needed, like the size of the rooms you'll be playing, how much of a racket you want to make, which instruments should be put out through the PA and so on.
Comment: I'm generally opposed to shopping/list/recommendation questions, and I have spoken out against them many times here, but even I must admit that we could probably afford to be lenient when it comes to helping out newbies with general equipment advice like this, especially for "timeless" equipment. I think it's a good question.
Comment: As the question is currently worded, it might get closed (I am not voting for close though) because it is considered off-topic: "Questions seeking recommendations for equipment are off-topic because they tend to become obsolete quickly. Instead, describe your situation and the specific problem you're trying to solve." It also is a little too localized. Maybe you (or we) can re-word it towards "What kind of speakers are less complex to implement in X scenario" or "things to consider in a band PA" or something around that?
Comment: Suggestion for scope change, to avoid closure of questions like these: http://meta.music.stackexchange.com/a/808/8682
Comment: Dunno -- some groups I've heard would benefit from a PA system which attenuated their voices :-)
Comment: Really this depends on your budget. Get the best you can afford with cash on hand.
Answer: Defer this decision until you know where you're going to play.
I'm going to assume you have an acoustic drumkit, which you won't be mic'ing up. So the drums set a baseline volume which the other instruments and voices need to match.
You actually don't need much to achieve this. The guitarist just needs a modest amp - one step up from a practice amp, something like the Roland Cube (not the MicroCube). The bassist needs something a bit bigger, because bass needs to shift a lot of air.
I'd suggest that the keyboard also be plugged into a cabinet. It could be a similar size/power to the guitar amp, unless your keyboard is expected to provide bass elements, in which case it will need to be larger and more powerful. But do make sure it's a keyboard/PA amp, designed to cleanly amplify without adding distortion or tone.
That just leaves microphones. It's possible your first venue will have its own PA, in which case, use it. Even if it doesn't, your second might - so hire (rent) a PA instead of buying one at that stage. You don't need much - a mixer with as many inputs as there are voices, and another small PA amp/cabinet.
At this level, monitors are a bit of a luxury, but you'll be grateful for them. So if they're on offer, take them. You might be able to improvise monitors by using the practice amps you use at home.
If and when you move on to bigger venues, it becomes all the more reasonable to expect the venue to have its own PA. I would resist the urge to buy instrument amps that will fill large venues. Play at the volume you practice at; point mics at your on-stage cabinets and have the house PA amplify them at the audience. It should be quieter on stage than in the crowd. DI where it makes sense.
Some acts fill the stage with huge cabinets. Some of them are actually using them. Lots of them, however, are just for show -- the real sound is from a small mic'd up cabinet. Seasick Steve plays festival main stages with a MicroCube.
It may be that you find yourself on a circuit in which you frequently play larger venues that don't have their own PA. Only when that turns out to be the case, should you consider buying your own PA -- by which time you will have picked up enough experience with hired equipment and house equipment that you'll know what you want.
Comment: +1 for pointing out that a lot of venues will have their own PAs. Even small dive bars will often have them if they regularly invite musicians to play there.
Answer: I'm going to play devil's advocate here. A PA is a collection of parts. That means you can start out simply and add pieces as the need arises.
Here's what I would do: Look at the plastic-bodied powered speakers. They have amps, EQ and one or more inputs. You can begin with only one or two and plug mics directly into them and off you go. If money is an issue, buy inexpensive ones. I have a pair of 12-inch Harbinger budget units from GC that cost me all of $300 on sale. They don't sound as nice as QSC, but they are surprisingly good. Later when you build out your PA by getting a mixer and better powered speakers, the cheap ones will make great monitors. If you have more than one singer, monitors are really important. I have a good ear while singing, but my other singer needs to hear herself clearly to stay on pitch.
For small gigs, you shouldn't need to mic the drums. One important word of advice is to learn to control your volume. Bands sound better when they are not drowning out the room. This has several benefits: you will more easily get a good balance, the crowd and venue won't hate you, and, you will be better able to hear each other.
Answer: Mainly, you should consider the number of inputs, as well as the wattage. You mentioned that you have a pianist, electric guitarist, bassist, and drummer, who all share vocals. So first and foremost, you're going to need at least 4 mic inputs, as well as 3 quarter inch inputs, if your guitar players and pianists are going to be plugged directly into the PA system, which could make mixing easier, since you can control most of the sound from a central location.
If you're going to be playing smaller venues, then you will have to be clever with drum placement so that you can get a good sound. If you sought to mic the drums, then you're going to need a mixer with a lot of mic inputs. You should also definitely get some monitors so that the band can hear themselves. Having monitors is very beneficial for the performers.
This is a pretty decent All-in-one sort of PA package, that should produce plenty of volume for smaller venues. http://www.sweetwater.com/store/detail/PassVenue/
Answer: Hold on for now - things may change, you may decide that actually two mics will suffice, since you could share, no need to mic up drums/gtr/bass, etc. Use two or three rehearsal studios, and try out their gear. Talk to the guys there to get some more ideas.I'm going to disagree with slim and state that you shouldn't need monitors. Place a p.a. right, use sensible volumes and they won't be needed., Used badly, all they will do is increase the sound pressure already on stage.


Where to export i18n mode for menus in features?

Question: I'm using a combination of Entity Translation and Node Translation for a site and when I go and set up the menu, I need to edit each menu and select Translate and Localize.
Where is the feature to export this?
Answer: This is stored in the menu itself. Menu_links aside, the menu features wil be stored in some custom.inc file.


Wrong timezone in Views output

Question: I'm using Services Views to create a JSON output of my Drupal site's nodes. These nodes has a start and stop date and time regarding an event. On the site, viewing the node, the time is correct, but in my Services view it is shown in UTC instead of my Drupal site's timezone (UTC +2).
I've seen other questions regarding this issue with a DB and site timezone being different, with all the issues it creates - especially in cases just like this.
Eg.:
http://dropbucket.org/node/559 and
Drupal timezone and database and Printing the correct date value in a view
In this case, however, I do have a problem converting the value into the correct timezone and therefore the correct time.
I have the site set to UTC +2 (Sweden/Stockholm), users arn't allowed to have any other timezones, also the date field is set to save the date in the site's timezone, not the DB.
My view wont let me rewrite my output so I can't convert the date inside the view - nor would I like to run PHP in a view anyway.
Is there another way of converting, or at least changing the setting for the date save, so that this won't be a problem?
Cheers,
Daniel
Answer: I'm not exactly sure why you are having this trouble... Though in a quick attempt to test (in Drupal 7), it does seem a little screwy.
However, since you don't seem worried about other timezones and no need to convert timezones, it would seem easiest to set the "Time zone handling" on the field to "no time zone conversion"
Then the views should pick up whatever date and time is there to begin with.

Wrong timezone in Views output


sql database convention

Question: Apologies in advance if this is a stupid question. I've more or less just started learning how to use SQL.
I'm making a website, the website stores main accounts, each having many sub-accounts associated with them. Each sub-account has a few thousand records in various tables associated with it.
My question is to do with the conventional usage of databases. Is it better to use a database per main account with everything associated with it stored in the same place, store everything in one database, or an amalgamation of both?
Some insight would be much appreciated.
Answer: Will you need to access more than one of these databases at the same time? If so put them all in one. You will not like the amount of effort and cost 'joining' them back together to do a query. On top of that, every database you have needs to be managed, and should you need to transfer data between them that can get painful as well.
Segregating data by database is a last resort.

sql database convention


AWS Opswork puppet does not get github code

Question: I've set up a new AWS Opswork puppetmaster
It is supposedly configured with a ssh key that should allow access to github
However, it doesn't and fails very early on in the configuration steps.  I would like to know if there are any configuration items I can check and/or how I might be able to get the puppetmaster to pull puppet code from github
I have my own puppet configuration files and custom modules for local use on a private repository on github
However, if I do a "puppet-access login --lifetime 180d" to set up the token and then try and get it to work...
<code># puppet-code deploy --dry-run
--dry-run implies --wait.
--dry-run implies --all.
Dry-run deploying all environments.
Errors while collecting a list of environments to deploy (exit code: 1).
ERROR    -> Unable to determine current branches for Git source 'puppet' (/etc/puppetlabs/code-staging/environments)
Original exception:
Invalid credential type
</code>
The path <code>/etc/puppetlabs/code-staging/environments</code> does not exist
The ssh key definitely works however
<code># ssh -i /etc/puppetlabs/puppetserver/ssh/id-control_repo.rsa -T email@example.com
Hi billybob22! You've successfully authenticated, but GitHub does not provide shell access.
</code>
And the ssh key is readable by pe-puppet
<code># su pe-puppet -s /bin/bash -c 'test -r /etc/puppetlabs/puppetserver/ssh/id-control_repo.rsa; echo $?'
0
# ls -l /etc/puppetlabs/puppetserver/ssh/id-control_repo.rsa
-r-------- 1 pe-puppet pe-puppet 3243 Dec 19 14:45 /etc/puppetlabs/puppetserver/ssh/id-control_repo.rsa
# ls -ld /etc/puppetlabs/puppetserver/ssh
dr-x------ 2 pe-puppet pe-puppet 4096 Dec  6 16:32 /etc/puppetlabs/puppetserver/ssh
</code>
I have tried using the github url in the form
<code>"puppet_enterprise::profile::master::r10k_remote": "email@example.com:myorg/my-puppetrepos"
</code>
and also
<code>"puppet_enterprise::profile::master::r10k_remote": "ssh://github.com/myorg/my-puppetrepos"
</code>
Both forms give identical results as outlined above
Not got much idea where to take it from here!  The docs (both Puppetlabs and AWS ) cover some problems but not this.  Just to repeat my question: what further diagnostics should I do to try and resolve this problem?
Answer: The correct format for the repository location is
email@example.com:myorg/my-puppetrepos
I couldn't find any way of changing this value in an existing Opsworks puppetmaster so I just blew it away and started another one, giving the correct value at the start
I assume my problem was caused by giving the incorrect GitHub URL


Laravel com erro no no composer install

Question: eu movi o laravel para o servidor de homologação e quando rodei o composer install, tive esse problema.
alguém já teve algo assim?
na minha maquina que roda sob o vagrant roda liso.
O ambiente é laravel 5.4, redhat 7 e php 7
Generating optimized autoload files
> Illuminate\Foundation\ComposerScripts::postInstall
> php artisan optimize
PHP Warning:  Uncaught ErrorException: require(/var/www/html/gemeos-backend/vendor/rachidlaasri/laravel-installer/src/Providers/../routes/web.php): failed to open stream: No such file or directory in /var/www/html/gemeos-backend/vendor/laravel/framework/src/Illuminate/Support/ServiceProvider.php:71
Stack trace:
#0 /var/www/html/gemeos-backend/vendor/laravel/framework/src/Illuminate/Support/ServiceProvider.php(71): Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(2, 'require(/var/ww...', '/var/www/html/g...', 71, Array)
#1 /var/www/html/gemeos-backend/vendor/laravel/framework/src/Illuminate/Support/ServiceProvider.php(71): require()
#2 /var/www/html/gemeos-backend/vendor/rachidlaasri/laravel-installer/src/Providers/LaravelInstallerServiceProvider.php(27): Illuminate\Support\ServiceProvider->loadRoutesFrom('/var/www/html/g...')
#3 /var/www/html/gemeos-backend/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(574): RachidLaasri\LaravelInstaller\Providers\LaravelInstallerServiceProvider->register( in /var/www/html/gemeos-backend/vendor/laravel/framework/src/Illuminate/Support/ServiceProvider.php on line 71
PHP Fatal error:  Illuminate\Support\ServiceProvider::loadRoutesFrom(): Failed opening required '/var/www/html/gemeos-backend/vendor/rachidlaasri/laravel-installer/src/Providers/../routes/web.php' (include_path='.:/usr/share/pear:/usr/share/php') in /var/www/html/gemeos-backend/vendor/laravel/framework/src/Illuminate/Support/ServiceProvider.php on line 71

  [Symfony\Component\Debug\Exception\FatalErrorException]
  Illuminate\Support\ServiceProvider::loadRoutesFrom(): Failed opening requir
  ed '/var/www/html/gemeos-backend/vendor/rachidlaasri/laravel-installer/src/
  Providers/../routes/web.php' (include_path='.:/usr/share/pear:/usr/share/ph
  p')

Script php artisan optimize handling the post-install-cmd event returned with error code 255

Comment: A pasta `/var/www/html/` tem permissão de escrita e esta associada ao seu usuário principal? Por acaso você não esta rodando em `root` algo né? Porque o composer não deve ser rodado em root, se fez algo anteriormente com root, talvez tenha criado pastas sem permissão.
Comment: a pasta /html é root:root porém a pasta do projeto é com meu usuário
Comment: Mas você não rodou anteriormente nenhum outro comando acidentalmente com `su`/`sudo`?
Comment: o único comando que eu rodei foi esse:
 sudo chown -R danilo.dorgam gemeos-backend/
para tirar o root da pasta e filhas
Comment: Danilo qual comando usou para instalar? Foi o `composer global require "laravel/installer"` e depois o `laravel new blog`?
Comment: no meu pc sim, nesse servidor ele pega do github enviando pelo jenkins
Comment: Danilo talvez seja algo que esteja desatualizado e o composer esteja misturando alguma coisa de versão, tente seguir os passos da resposta.
Answer: Existem duas maneiras de instalar o Laravel, a primeira e talvez mais comum seja instalado o "laravel/installer", primeiro rode o comando em qualquer pasta, não precisa ser na onde irá criar o projeto:
composer global require "laravel/installer"

Isso irá instalar "globalmente", então o instalador irá permitir usar, claro que o composer precisa estar instalado globalmente também, para isso terá que adicionar $HOME/.composer/vendor/bin ao $PATH do sistema operacional.
O após garantir que esta tudo global, execute navegue até a pasta do Apache e tente criar um novo projeto:
cd /var/www/html
laravel new gemeos-backend2

Veja se o problema ocorre ainda.
A maneira alternativa, sem o comando laravel é instalar via create-project do composer, navegue até a pasta e execute o comando:
cd /var/www/html
composer create-project --prefer-dist laravel/laravel gemeos-backend3

Resolvendo possíveis problemas
Pela mensagem de erro:

Uncaught ErrorException: require(/var/www/html/gemeos-backend/vendor/rachidlaasri/laravel-installer/src/Providers/../routes/web.php): failed to open stream: No such file or directory in /var/www/html/gemeos-backend/vendor/laravel/framework/src/Illuminate/Support/ServiceProvider.php:71

Presumo que algo ou tenha sido baixado na versão errada ou misturada, primeiro devemos garantir que tudo esteja atualizado, para atualizar o composer rode o comando:
composer self-update

Se não estiver global, rode:
php composer.phar self-update

Se estiver usando o Laravel/Installer então remova-o primeiro:
composer global remove laravel/installer

E então em seguida tente instalar novamente ele e criar um projeto:
composer global require "laravel/installer"
cd /var/www/html
laravel new gemeos-backend4

Nota: mudei o nome da pasta (gemeos-backend2, gemeos-backend3 e gemeos-backend4) para cada teste feito, acaso seja um problema de usuário/permissão
Nota: o laravel/installer irá instalar a versão 5.5 do Laravel
Comment: eu percebi essa diferença de versão, no meu pc é a 1.4.2 e no servidor 1.5.1 será que um downgrade é uma boa?
Comment: @Danilo depende se estiver conflitando com outra lib, framework, verifica o teu composer.json. Uma nota, tanto o Laravel 5.1, quando 5.2, 5.3 e 5.4 ainda não mantidos e podem ser usados, o lançamento do 5.5 não impede o uso das versões anteriores.
Comment: meu laravel é 5.4, porém acho que não é ele, eu instalei a lib direto no servidor mas deu na mesma
Comment: @Danilo toda sugestões acima ocasionaram `Uncaught ErrorException: require(/var/www/html/gemeos-backend/vendor/rachidlaasri/laravel-installer/src/Providers/../routes/web.php)`?

Laravel com erro no no composer install


problem on homeomorphism

Question: i am facing problem in showing that:
show that the maximum number of closed curves along which the surface
may be cut without dividing it into two or more disjoint parts is
 a topological invariant.
i am not able to understand which property of homeomorphism is not satisfied in this case
Answer: If $f\colon X\to Y$ is a homeomorphism and there exist $n$ closed curves $\gamma_i\colon S^1\to X$ such that $X\setminus\bigcup \gamma_i[S^1]$ is not connected, then we are to show that there are also $n$ curves in $Y$ with this property. Trying the curves $f\circ \gamma_i$ suggests itself.

problem on homeomorphism


How to set a read only mode for a share in celerra

Question: I  need to find out if the  Celerra NAS (NS 700 Model) in my location  allows me  to set a read only mode for a share.
Specifically, this is for the terminated employees folder.  They want to be able to make it read only before backing it up so nothing changes.
I am not able to locate where the permissions are and if it allows me to set this read only mode.
Please guide me on this, it's little urgent.
Thnaks!!
Answer: Without knowing what type of share you are talking about (CIFS\NFS) and what sort of users are accessing it it's not easy to tell you precisely how to do what you are asking but a quick way to do what you need is to create a read only snapshot of the share and back up what you need from that.
If this is a Windows only environment, and you are talking about a CIFS share then you should be able to use the standard Windows Server Manager MMC to connect to the Celerra's Netbios identity and use that to change the Share permissions to Read only. You can achieve a similar result by using Explorer (or any other Windows utility that enables you to change NTFS permissions) to change permissions to read only across the board. This only applies for Windows only environments where you are using Usermapper - in mixed mode environments this is a bit more involved and of course none of this applies if you are talking about an NFS share.
Comment: Yes - if you change it from Read\write to Read using the Radio button that should disallow writes to that share. One thing to be careful of is that only makes that share read only - if you want to be 100% certain you should change the NTFS permissions on all the files and subfolders. Taking a Read-Only Snapshot of it would guarantee that you have a fixed copy that can't be changed while you back it up.
Comment: I 'm sorry Helvick  for not giving the proper information. The protocol in question is CIFS.From Celerra ,i see a "termemployee" share name, and when i go to the properties under Mount Tab, i see the option which says Read/write ( clicked radio button) and another says only read.If i click on that would it allow me to make it a read only folder ,so that i can take the backup of it?
I am using celerra manager GuI to do this..


Outputting recent comments in a different part of the node

Question: I have created a custom node, and at the bottom of this node I would like to show the latest three comments made on that node. I have added the code below to my template.php, and then loop through the array to get the data in my node:
<code>if ((arg(0) == 'node') && is_numeric(arg(1)))
{
    $result = db_query_range('SELECT c.cid, c.nid, c.subject, c.name
    FROM {comment} c WHERE c.nid = :cid ORDER BY c.cid DESC', 0, 3, array(':cid' => arg(1)));

    $i = 0;
    foreach ($result as $record) {
        $variables['NewComments']['NewSubject'][$i] = $record -> subject;
        $variables['NewComments']['NewName'][$i] = $record -> name;
        $i++;
    }
}

else {
    $variables['errorCheck'] = t('nope fail');
}
</code>
However, I am having trouble outputting this into the node.tpl. Is there an easy way to do this, or should I try something else to tackle this issue?
Thanks
Answer: You can do that using views.

Then you can either add this view as a block or you can use http://api.drupal.org/api/views/views.module/function/views_embed_view/7 in node.tpl.php
Comment: Thanks, this worked very well. I'm going from D6 to D7 and the views module seems to have changed... Is there a way to make it show just comments subjects without them becoming links?


Get multistage dockerfile from image

Question: I have tried docker history and dfimage for getting the dockerfile from a docker image.
From what I can see, any information about the multistage dockerfiles is not there.  As I think about it, it makes sense.  The final docker image just knows that files were copied in.  It probably does not keep a reference to the layer that was used to construct it.
But I thought I would ask just to be sure.  (It would be really helpful)
For example: I have a multistage docker file that, in the first stage builds a dot.net core application, then in the second stage copies the files from that build into an Nginx container.
Is there any way, given the final image, to get the dockerfile used to do the build?
Answer: Unfortunately this wont be possible since your final docker image won't contain anything from the "builder" stage. Basically the builder stage is a completely different image which was built, the files were copied from it during the build of the final image and than it was discarded.
The stages from the builder stage will live on in your build cache and you could even tag them to run some kind of docker image analyzer against them. However this does not help you, if you only have access to the final image...
Answer: No it is not possible. Docker image will only have its own history and not the multi stages that may have been used before it

Get multistage dockerfile from image


Applying Dynamic Time Warping (DTW) instead of Euclidean Distance for Clustering Synchronized Time series data

Question: I am trying to cluster members based on hourly login data. As this is mostly synchronized, I first applied Euclidean and it failed to cluster them into groups with sensible patterns. I tried DTW thinking it might be more accurate for time series, it did show some sensible patterns.
My question is, can we apply DTW for data that have the same length and is synchronous instead of Euclidean in K mean? Are there any issues with using DTW for synchronized time series data?
Answer: Yes - if the time series are the same length and aligned, DTW will give you the same result as the Euclidean distance (ED).
There are two possible issues I can think of with using DTW. Firstly, in some time series it may not make sense to allow warping - these small mis-alignments may be important, so as always it pays to check the algorithm is appropriate for the data.
Secondly, DTW is computationally expensive for long time series, especially if you use unconstrained DTW. Although there are ways of speeding it up, a naïve implementation has complexity of $\mathrm O(n^2)$ (assuming the time series are the same length) compared to $\mathrm O(n)$ for ED, where $n$ is the length of the time series. While most implementations will be faster than that, DTW will still be slower than ED.


How do I create a full project from a sandbox project?

Question: We have created a module for Drupal 8 on drupal.org, but it is a sandbox project. How do I make it a full project?
Answer: You need to have your account elevated to be able to promote a project to full status, meaning you have to go through the project application process if you have not already.
https://www.drupal.org/node/1011698