Postfix increment into if, c#

Question: Code example:
using System;

public class Test {

    public static void Main() {
        int a = 0;
        if(a++ == 0){
            Console.WriteLine(a);
        }
    }
}

In this code the Console will write: 1. I can write this code in another way:
public static void Main() {
        int a = 0;
        if(a == 0){
            a++;
            Console.WriteLine(a);
        }
}

These two examples work exactly the same (from what I know about postfix).
The problem is with this example coming from the Microsoft tutorials:
using System;

public class Document {

// Class allowing to view the document as an array of words:
public class WordCollection {
    readonly Document document;

    internal WordCollection (Document d){
        document = d;
    }

    // Helper function -- search character array "text", starting
    // at character "begin", for word number "wordCount". Returns
    //false if there are less than wordCount words. Sets "start" and
    //length to the position and length of the word within text
    private bool GetWord(char[] text, int begin, int wordCount,
                         out int start, out int length) {

        int end = text.Length;
        int count = 0;
        int inWord = -1;
        start = length = 0;
        for (int i = begin; i <= end; ++i){
            bool isLetter = i < end && Char.IsLetterOrDigit(text[i]);
            if (inWord >= 0) {
                if (!isLetter) {
                    if (count++ == wordCount) {//PROBLEM IS HERE!!!!!!!!!!!!
                        start = inWord;
                        length = i - inWord;
                        return true;
                    }
                    inWord = -1;
                }
            } else {
                if (isLetter) {
                    inWord = i;
                }
            }
        }
        return false;
    }

    //Indexer to get and set words of the containing document:
    public string this[int index] {
        get
        {
            int start, length;
            if(GetWord(document.TextArray, 0, index, out start,
                                                     out length)) {
                return new string(document.TextArray, start, length);
            } else {
                throw new IndexOutOfRangeException();
            }
        }
        set {
            int start, length;
            if(GetWord(document.TextArray, 0, index, out start,
                                                      out length))
            {
                //Replace the word at start/length with
                // the string "value"
                if(length == value.Length){
                    Array.Copy(value.ToCharArray(), 0,
                               document.TextArray, start, length);
                }
                else {
                    char[] newText = new char[document.TextArray.Length +
                                              value.Length - length];
                    Array.Copy(document.TextArray, 0, newText, 0, start);
                    Array.Copy(value.ToCharArray(), 0, newText, start, value.Length);
                    Array.Copy(document.TextArray, start + length, newText,
                               start + value.Length, document.TextArray.Length - start - length);
                    document.TextArray = newText;
                }
            } else {
                throw new IndexOutOfRangeException();
            }
        }
    }

    public int Count {
        get {
            int count = 0, start = 0, length = 0;
            while (GetWord(document.TextArray, start + length,
                    0, out start, out length)) {
                        ++count;
            }
            return count;
        }
    }
}

// Class allowing the document to be viewed like an array
// of character
public class CharacterCollection {

    readonly Document document;

    internal CharacterCollection(Document d) {
        document = d;
    }

    //Indexer to get and set character in the containing
    //document
    public char this[int index] {
        get {
            return document.TextArray[index];
        }
        set {
            document.TextArray[index] = value;
        }
    }

    //get the count of character in the containing document
    public int Count {
        get {
            return document.TextArray.Length;
        }
    }
}

//Because the types of the fields have indexers,
//these fields appear as "indexed properties":
public WordCollection Words;
public readonly CharacterCollection Characters;

private char[] TextArray;

public Document(string initialText) {
    TextArray = initialText.ToCharArray();
    Words = new WordCollection(this);
    Characters = new CharacterCollection(this);
}

public string Text {
    get {
        return new string(TextArray);
    }
}

class Test {
    static void Main() {
        Document d = new Document(
            "peter piper picked a peck of pickled peppers. How many pickled peppers did peter piper pick?"
        );

        //Change word "peter" to "penelope"
        for(int i = 0; i < d.Words.Count; ++i){
            if (d.Words[i] == "peter") {
                d.Words[i] = "penelope";
            }
        }

        for (int i = 0; i < d.Characters.Count; ++i) {
            if (d.Characters[i] == 'p') {
                d.Characters[i] = 'P';
            }
        }

        Console.WriteLine(d.Text);
    }
}

}
If I change the code marked above to this:
if (count == wordCount) {//PROBLEM IS HERE
                        start = inWord;
                        length = i - inWord;
                        count++;
                        return true;
}

I get an IndexOutOfRangeException, but I don't know why.
Comment: _Well_, [What is an "index out of range" exception, and how do I fix it?](http://stackoverflow.com/questions/24812679/what-is-an-index-out-of-range-exception-and-how-do-i-fix-it)
Comment: Where exactly is the exception thrown? What are the values of the variable (inside the `[]`) at this point? (use breakpoints, use debugger)
Comment: Try putting your examples in a loop and see what the difference is.
Comment: The line you've marked as a 'problem' will not thrown an `IndexOutOfRange` exception. Which line is throwing that?
Comment: It's the exception thrown by the get of the WordCollection indexed property.
Answer: In your version of the code, count is only being incremented when count == wordCount; in the Microsoft version, it's being incremented whether the condition is met or not.
Comment: True; I assumed, since this was the only functional difference between the working code and the broken code, that it would eventually lead to the `IndexOutOfRangeException` seen by the OP.  But you're right that I didn't take the time to trace things all the way through to that exception, which would have made for an even better answer.  If you've done the work, by all means add a better answer and earn some rep.  (Edit: I see you have added an answer.)
Comment: you didn't explain why this causes an exception
Answer: Your initial assumption is incorrect (that the two examples work exactly the same). In the following version, count is incremented regardless of whether or not it is equal to wordCount:
if (count++ == wordCount)
{
    // Code omitted
}

In this version, count is ONLY incremented when it is equal to wordCount
if (count == wordCount)
{
    // Other code omitted
    count++;
}

EDIT
The reason this is causing you a failure is that, when you are searching for the second word (when wordCount is 1), the variable count will never equal wordCount (because it never gets incremented), and therefore the GetWord method returns false, which then triggers the else clause in your get method, which throws an IndexOutOfRangeException.
Comment: @Selman22 Or whoever downvoted, I added the explanation for why this is causing the exception (I thought it was kind of obvious given my original explanation of the error in assumption, but maybe not?).
Answer: using System;

public class Test {

    public static void Main() {
        int a = 0;
        if(a++ == 0){
            Console.WriteLine(a);
        }
    }
}

Is not quite the same as:
public static void Main() {
    int a = 0;
    if(a == 0){
        a++;
        Console.WriteLine(a);
    }
}

In the second case a++ is executed only if a == 0. In the first case a++ is executed every time we check the condition.
Answer: There is your mistake:
public static void Main() {
        int a = 0;
        if(a == 0){
            a++;
            Console.WriteLine(a);
        }
}

It should be like this:
public static void Main() {
        int a = 0;
        if(a == 0){
            a++;
            Console.WriteLine(a);
        }
        else
            a++;
}

a gets alwasy increased. This means, that in your code example count will get only increased when count == wordCount (In which case the method will return true anyway...). You basicly never increasing count.
Comment: You answer is correct, I don't know why you've been downvoted. I've choosen another answer because it explain also why the exception it thrown.
Comment: Thanks a lot. I got one downvote before i was able to edit my answer (the code formating was gone :( )

Postfix increment into if, c#


Javascript: how can I return an empty string (i.e "")

Question: I am making a function that returns greatest commmon prefix. When input is: ["flower","flow","flight"], output should be: "fl".
But there is an exception, when input is an empty array the output should be an empty string. This is where my function is not working.
var longestCommonPrefix = function(strs) {
    let prefix = '';
    let word = '';

    for (let i = 0; i < strs.length; i++){
        for(let j = i + 1; j < strs.length; j++) {
          for (let k = 0; strs[i][k] === strs[j][k]; k++) {
              prefix += strs[i][k];
              //console.log(prefix);
          }
          prefix += ',';
          //console.log(prefix);
        }
    }
    prefix = prefix.split(',').sort().slice(1);
    console.log(prefix);
    // if(prefix[0].length === 0) {
    //     return "";
    // }
    return prefix[0];
};
console.log(longestCommonPrefix(["flower","flow","flight"]));

Comment: show full code please
Comment: my guess is that you have a callback function and you return a value inside of it, but its just a guess. show us your code
Comment: Posted the code @brk
Answer: Following should work:
function returnEmptyIfNull(arr) {
    if(!arr?.length)
        return "";
    return "not empty";
}

Comment: I answered the question, hopefully he will make it production ready by self.
Comment: What if `arr` isn't an array?
Comment: Improved the answer.
Answer: Check the array for null and a size of 0. If either of these conditions are true, return an empty string.

function joinItems(items) {
  return items == null || items.length === 0 ? '' : items.join(', ');
}

console.log(joinItems(['Hello', 'World'])); // "Hello, World"
console.log(joinItems([]));                 // ""

You can simplify this the the following expression:

const joinItems = (items = []) => items?.join(', ') ?? '';

console.log(joinItems(['Hello', 'World'])); // "Hello, World"
console.log(joinItems());                   // ""
Answer: return "" will return an empty string. If the function is returning undefined, there's something else wrong with your function.
function fn () {
  return "";
}
console.log(typeof fn());
// 'string'

Answer: function check(param){
    if (param.length == 0){
        return "";
    }
}

console.log(check([]));

Works fine for me, check if the array is empty by checking if the length is 0.
You are getting undefined because your ' return "" ' line is not being run.
Answer: You need to check that your input is an array, then check that its length is 0.
function checkArrayIsEmpty(arr) {
    if(Array.isArray(arr) && arr.length === 0) {
        return "";
    } else {
        return "not an empty array";
    }
}

Comment: not an empty array won't help if it's not even an array.
Comment: @HamzaArshad we do not know the intent of the author's function, so the else block is a placeholder for demonstration purposes. Furthermore, "not an empty array" is logically sound even when the input is not an array, because strictly speaking, a non-array is not an array, nor an empty one.
Answer: if (strs.length==1)
  return strs[0]

This worked for me.
Comment: Welcome to Stack Overflow! Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the [help center](https://stackoverflow.com/help/how-to-answer).


Error and flat notes

Question: Lilypond gives me an error in the second line but I can't find out where it is.
Plus in the last line all the F note are flat (ff) but the second F note even if it is written correctely do not show the flat sign b, why?
Thank you.
here the exemple: http://lilybin.com/a000qh/1
Answer: The square bracket [ indicating the stat of a beam group should be attached at the end of the first note in the group.
So the part:
. . . \bar "||" [ff8 \melisma ef df] . . .
should be changed to:
. . . \bar "||" ff8[ \melisma ef df] . . .

Some of the f-flats are not all showing up with flat symbol because LilyPond thinks that you are still in the same bar as a previous f-flat that is marked.
In music notation, an accidental symbol usually effects a note, and all preceding notes in that bar that are in the same staff position.
One option to get more accidental symbols is to use an exclamation point ! directly after a pitch is given.
So the part:
. . . ff16 [ef ff8] gf2 ff4 df8 ef ff2. \bar "|" . . .
can be changed to:
. . . ff16 [ef ff!8] gf2 ff!4 df8 ef ff2. \bar "|" . . .
However, there are other ways to deal with this problem such as changing the time signature, or setting a different accidental style.

Error and flat notes


Line-Height VS Padding in Nav (Correct Method)

Question: I am just getting back into coding and I would like to know what is the best method for adding heigh to my btn.
Here is the code -
Padding method
.nav-main li a {
  display: block;
  padding: 70px 10px 70px 10px;
  color: #6CF784;
  border-bottom: 10px solid white;
  text-decoration: none;
}

Line-height method
.nav-main li a {
  display: block;
  padding: 0 10px 0 10px;
  line-height: 150px;
  color: #6CF784;
  border-bottom: 10px solid white;
  text-decoration: none;
}

Answer: I like to use line-height because it positions the baseline correctly to make the text appear in the middle of the element (whereas with padding it may be off-centre one way or the other based on the font)
Of course, this relies on you using a pixel value for line-height (as you are doing in your question) - using a numeric value like 1.5 may produce different results depending on the font.
Answer: I personally use padding as it gives me more control across browsers, as line height can vary on which font you are using, along with what fonts are installed/not installed on the clients' browser.
Answer: .link {
   text-decoration: none;
   color: aqua;
   border: 2px solid aqua;
   margin: 30px auto;
   display: block;
   width: 160px;
   height: 40px;
   line-height: 35px;
   text-align: center;
   position: relative;
   overflow: hidden;
}
.link::before {
   content: attr(data-text);
   position: absolute;
   width: 100%;
   top: 0;
   left: 0;
   transform: translateX(-100%);
   transition: 0.5s;
}

You will show the difference between the padding and line height
when you use pseudo element (before and aftere) =>
with line height the pseudo element take the same height of his parent
with padding the pseudo element do not take the height of his parent


Can football players be penalised for an action against a teammate that is normally a foul if done to the opponent?

Question: I saw this video of a player slide tackling his teammate.
What are the rules on players tackling their own teammates like that?
Would it just be to show fair play and kick the ball out to treat the player?
Comment: I've added a late answer which I believe better covers the scenario you've highlighted. The answer you've accepted assumes that the action is bad enough to be a cautionable or sending-off offence.
Comment: @Metro Boomin Yes studro is right, just for an action against teammate which is not excessive enough players can't be penalized, whereas I assumed action is excessive. So, if you could accept the answer of studro I will delete mine.
Answer: No, a player cannot be penalised for an action against a teammate that is normally (only) a foul if done to the opponent.
Most free kick offences listed in Law 12 under direct free kicks and indirect free kicks that involve physicality against another player (e.g. a careless trip or tackle, or impeding) contain the wording "against an opponent", either directly in the wording of the offence, or in its definition (e.g. playing in a dangerous manner), meaning they cannot be committed against a teammate.
The only exception to this would be if the action was reckless or excessive enough to make it misconduct (i.e. a cautionable or sending-off offence) This free-kick offence is listed in Law 12 - Fouls and Misconduct, Section 2 - Indirect Free Kick:

An indirect free kick is awarded if a player:
...

commits any other offence, not mentioned in the Laws, for which play is stopped to caution or send off a player

Note that there is no requirement for this offence to be committed against an opponent. This would include committing violent conduct (i.e. using excessive force) or unsporting behaviour (i.e. recklessness) against a teammate.
For these offences, after the offender is either cautioned or sent off, the restart would be upgraded from an indirect free kick offence to a direct free kick offence as per Law 12 - Fouls and Misconduct, Section 4 - Restart of Play After Fouls and Misconduct and Q6 & Q7 of Law 12 FAQ.
Comment: In response to your second comment, you got in first - so if you incorporate my information into your answer, I'll delete mine. The only reason I left a new answer was because it was so vastly different to yours and it would have been strange to incorporate such a large edit.
Comment: @studro Yes that's why I mentioned your answer in mine.
Comment: The question doesn't say "fouls against an opponent", it says "actions against a teammate that are normally a foul if done to an opponent". I think you've read the conditional in the wrong order.
Comment: The logic could have been clearer, but I believe the conclusion is still correct. I've edited the answer based on your suggestions. Thanks for the suggestions.
Comment: @studro I think you are confused with word "Penalise" and "Caution", what does this mean in your answer "the indirect free kick offence of commits any other offence" and at last I think you meant "Q6".
Comment: I'm not confused by these terms at all. Can you please provide context as to which part of the answer suggests that I am, so it can be corrected? "*commits any other offence, not mentioned in the Laws, for which play is stopped to caution or send off a player*" is the only physical free kick offence in Law 12 (it is listed in Law 12.2) that a player can commit against a teammate, and it requires misconduct to have been committed. I guess Q6 is also applicable, but Q7 clearly highlights that only verbal misconduct against a non-opponent results in an indirect free kick.
Comment: @studro Wouldn't Penalise mean just stopping play and awarding a free kick, whichever that may be.
Comment: @studro Thanks for being patient and explaining me the situation, retracted my wrongly done downvote and upvoted, as soon as OP accepts your answer I will delete mine.
Comment: From the glossary of the LOTG penalise is defined as: "To punish, usually by stopping play and awarding a free kick or penalty kick to the
opposing team". I would say that a caution or sending-off are also punishments, so cautioning or sending-off a player is also penalising them.
Comment: @RamChandraGiri - upon reflection, I think there is enough difference in our answers to warrant leaving mine here.
Answer: (The situation explain in this answer assumes action against a teammate which involve misconduct and wouldn't be only foul. See this answer)
Can football players be penalised for an action against a teammate that is normally a foul if done to the opponent?
(Answer is no, for an action against a teammate that is normally a foul if done to the opponent.)

In short yes, laws of the game allows it.
From IFAB Laws of The Game :

Law 12 fouls and misconducts (emphasis added)

DISCIPLINARY ACTION
A player who commits a cautionable or sending-off offence, either on or off the field of play, against an opponent, a team-mate, a match official or any other person or the Laws of the Game, is disciplined according to the offence.
RESTART OF PLAY AFTER FOULS AND MISCONDUCT
If the ball is in play and a player commits an offence inside the field of play against:

a team-mate, substitute, substituted or sent off player, team official or a match official – a direct free kick or penalty kick

From FAQ of Law 12

Q6: Why is an offence against someone who is not an opponent now a direct free kick? Does this include dissent/offensive language?
If, for example, a player strikes a team-mate, substitute, team official or, perhaps even worse, a match official this is serious but only restarting with an IDFK suggested that the offence was not serious so it is now a direct free kick for any offence (directly) against anyone (except an opponent). This does not include dissent/offensive language etc. as this is not a direct/physical offence against a person (see below).
Q7: What is the restart of the referee stops play for dissent/offensive language etc.?
If the referee stops play to penalise a player for dissent/offensive language etc. the restart is an IDFK.

In 1994, Hearts teammates Graeme Hogg and current Hearts manager Craig Levein were sent off for scrapping during a pre-season friendly against Raith Rovers. Source
Update: From the IFAB Glossary

Penalise
  To punish, usually by stopping play and awarding a free kick or penalty kick to the opposing team

For Violent Conduct player can be sent-off. (see: SENDING-OFF OFFENCES)

VIOLENT CONDUCT
  Violent conduct is when a player uses or attempts to use excessive force or brutality against an opponent when not challenging for the ball, or against a team-mate, team official, match official, spectator or any other person, regardless of whether contact is made.
In addition, a player who, when not challenging for the ball, deliberately strikes an opponent or any other person on the head or face with the hand or arm, is guilty of violent conduct unless the force used was negligible.

See: Newcastle men sent off for fighting each other

However for the mention case, where Jack Hendry of Dundee tackles his own team-mate Cammy Kerr in a match against Rangers which they lost 4-1, I could not find anything that happened after the incident but I'm sure that Jack did not get booked.
Comment: This might be a better example - https://www.youtube.com/watch?v=u7_ygd9k24w
Comment: Fouls can only be committed against an opponent. See the wording in Law 12 for each offence. However, it is possible to commit misconduct against a team-mate, which is what your quotes are referring to.
Comment: @studro My answer does not state "whether fouls can be committed against an opponent" but only states that "players can be penalised for an action against a teammate"
Comment: But that's not the question. The question is "can players be penalised for an action against a teammate that is normally a foul if done to the opponent"? And the answer is no, unless the action also constituted misconduct.
Comment: None of the examples given here are actions that would result in simply a foul if committed against a teammate. They all involve misconduct.


Finding inverse matrix two different ways

Question: Let A be an invertible matrix. Thus, A A' = I where I is the identity matrix and A' the inverse of A. We can find A' two ways (that I know of; Linear Algebra I&II).
First method:
Straightforward multiplication of A by an arbitrary matrix A' (I assign variables to each element in the n by n matrix). Thus, I get simple equality and I can easily find matrix A'.
Second method:
Using the Gauss-Jordan method I can use elementary row operations to convert A into an identity matrix. Each row operation I do to A I also do to I. Thus, I transforms into the inverse of A.
I have attached an example:

I know that there must be something fundamentally wrong with the first method, but I am not sure why. I know I am technically just finding an arbitrary matrix in the first method so it is not really the inverse. Someone, please explain.
Comment: Your first method is perfectly okay, and can be used to find the inverse matrix in all situations (although this can be a little tricky for larger matrices, especially without 0s in them). In fact, your first answer is correct and your second answer is incorrect. Your method is correct, but you forgot to apply the $R_2-2R_1$ operation to the matrix on the right side.
Comment: "I know I am technically just finding an arbitrary matrix in the first method so it is not really the inverse" - not true! If $A$ is a square matrix and you can find a matrix $B$ such that $AB = I$, then $B$ is the inverse of $A$. (The inverse is unique if it exists.) Similarly, if you can find a matrix $C$ such that $CA = I$, then $C$ is the inverse of $A$, and hence $C = B = A^{-1}$.
Comment: @TomKern true, thanks
Answer: There's nothing wrong with either method. In fact, they are equivalent. Unfortunately, you made an error in calculating the row operation $R_2 \rightarrow R_2 - 2R_1.$ (Edit: this error was later corrected by the question asker.)
When one is doing a row operation on an augmented matrix like
$$\left[\begin{matrix}
4 & -2 \;\\
2 & 0 \;\\
\end{matrix}\right\rvert \left.\begin{matrix}
\;1 & 0 \\
\;0 & 1 \end{matrix}\right],$$
this is the same as left-multiplying the system
$$\begin{bmatrix}
4 & -2 \\
2 & 0
\end{bmatrix}\begin{bmatrix}
a & b \\
c & d
\end{bmatrix} = \begin{bmatrix}
1 & 0 \\
0 & 1
\end{bmatrix}
$$
by the elementary matrix that the row operation represents.
The augmented matrix method is usually preferred because the symbols $a,$ $b,$ $c,$ and $d$ are unchanged if we are only multiplying by matrices on the left; so, there's no real need to "keep track" of them. Of course, the goal is the same.
Once we reduce the matrix on the left to identity, the matrix on the right must be the inverse. There is only one matrix that could possibly satisfy that equation if $A$ is invertible. But since we're really doing the same operations no matter which presentation we choose, we usually choose the augmented matrix because it's more compact. The result is the same.
Comment: Yes, I realized the mistake but was too lazy to take another picture. As long as the first method is valid it's ok. Thanks!


Centralized IIS to redirect to other IIS servers

Question: Basically what i'm after is to have a centralized IIS Server on the Local LAN where port 80/443 would be forwarded to from the router. Then through this server it can forward/redirect the requests to other servers in order to access the exchange OWA and for example the Remote Desktop web apps which are located on other local servers, the Exchange server and RDS Server respectively? For example I would access www.example.com and redirect me directly to this IIS centralized Server and www.example.com/OWA will redirect me to the Exchange server and www.example.com/RDWEB will redirect me to the RDS server. I need to know if such setup can be done so that I can have one main domain (example.com) and also one public IP Address corresponding
Answer: By the sounds of it you want IIS to do the request on behalf of the user and deliver the content as such since externally the user could not otherwise access these resources (due to NAT).
The best way to achieve this I think would be to setup a reverse proxy. There's a blog post on the subject that the developer for an IIS extension has made which explains how to do this: http://blogs.iis.net/wonyoo/archive/2008/07/09/application-request-routing-arr-as-a-reverse-proxy.aspx This extension is available in Web Platform Installer.
I've never done this before, personally, but I'm a bit interested now and have a lab with multiple IIS servers rearing to go and will give it a shot just now.
Addendum
I've just finished making a rule and it seems to work with IIS 8.0 with no problems. I was able to rewrite to an internal network using specific patterns and I can provide an accompanying screenshot. So keep in mind that the GUI is slightly different and to access the bit that the guy in the blog was going on about you need to go to (from within your site) URL Rewrite -> Add Rule(s)... -> Blank Rule.
What you'll insert should look a bit like this depending your needs:
Comment: : Ok so how can I specify then, if for example http://test.com/rds will take me to http://rds-srv/rds and if http://test.com/owa will take me to http://exch-srv/owa ? and I can't manage to get https internal sites.. do you have any idea why ? when I try to access the remote desktop website which is https by default through the re write I get this error message "Error 502 - Web server received an invalid response while acting as a gateway or proxy server"


how I can use Haml file for making a static website?

Question: I want to write html pages that  I need to write in haml format  (I want this because someone want me to made design in haml format that they can use in their dynamic website).  Do someone know anything that I can use to write haml on windows computer.
I need something that make me able to see the code worked on browser. I means a compiler in editor or something that is easy to do haml to html.
I have installed Nodejs in my computer and used it work on Jade and Ejs but nothing of those thing relate to my question. Do someone have idea if I can compile haml in nodejs. I heve heared from people that they compile their coffeescript In nodejs. Do someone know if nodejs have something that make me able to compile my haml in anyway.
I just want to write haml and want to get html that I can simply run locally in my browser.
Comment: What about `haml input.haml output.html`? http://haml.info/docs/yardoc/file.HAML_REFERENCE.html#using_haml
Answer: You can use http://middlemanapp.com/ to create your site using Haml and Scss. You can also compile it down to static html/css. Great tool!


Explanation of WCF application life cycle in IIS 6 hosting environment

Question: Hi all and thanks for reading,
I have a delay issue where my application takes a long time to start up when first called after an determinate period since the last call. The web application is a WCF service and we are talking about a delay of ~18seconds before the actual processing starts. Now, I believe I know how to reduce this delay so that is not my question (it's more a stackoverflow deal anyway)
My question is, Can anyone explain to me why is it that despite me disabling worker process shutdown, and worker process recycling the application still 'winds down' after a indeterminate period of time of inactivity?
To understand this I need to know more about the innerworkings of WCF services hosted in IIS. I fully expect there to be a straight forward answer to this.
Thank you v. much for any help you may offer,
DC
Comment: Can you please share what caused the issue you described here?
Answer: If everything is unchecked on the Recycling and Performance tab of the worker process, IIS should not be terminating the processes.  Are there any event log entries that correspond to the time the process "winds down"?  It sounds to me like the WCF app is potentially crashing out.  WCF doesn't log exceptions to the event log like a standard .NET app so if you aren't writing your own logs, you may want to turn on WCF tracing to see if perhaps thats the issue.
The quick ugly solution to your problem in the meantime may be to create some sort of cheap test or read only transaction in your WCF service and just configure a monitoring app or script to poll it every X seconds to keep the worker process alive with the code pre-JIT'd.
Answer: I believe the issue was unrelated to WCF, and the fault lay with nHibernate sorting out it's mappings.  I solved it by compiling the nHibernate mapping files so nHibernate didnt have to.


Índice em JavaScript

Question: Eu tenho uma tabela onde posso adicionar linhas dinamicamente, toda vez que clico no botão eu adiciono uma nova linha para preenchimento do campo, minha primeira linha vem com índice 0
<input type="text" name="data[Ticket][0][descricao_ticket]" size="20" placeholder="Informe aqui">

Minha primeira informação eu gravo normalmente no banco de dados, mas quando preciso adicionar uma nova linha preciso ir no JS e alterar o índice 0 para 1 para que não sobrescreva a informação, como faço para deixar esse índice incrementar sozinho quando solicitar uma nova linha? Não manjo muito de javascript
(function($) {
    remove = function(item) {
      var tr = $(item).closest('tr');

      tr.fadeOut(400, function() {
        tr.remove();
      });

      return false;
    }
  })(jQuery);

(function($) {
    AddTableRow = function() {

      var newRow = $("
");
      var cols = "";
      //var indice = 0;

      cols += '<input type="text" name="data[Ticket][1][descricao_ticket]" size="20" placeholder="Informe aqui">	';

      cols += '';
      cols += '<button type="button" class="btn btn-danger" onclick="remove(this)">Remover</button>';
      cols += '	';

      newRow.append(cols);
      $("#details-table").append(newRow);

      return false;
    };
  })(jQuery);

Answer: Você pode contar quantos elementos input a id #details-table possui e acrescentando +1 no total:
var indice = $("#details-table input[type='text']").length+1;

E concatenar na variável:
cols += '<input type="text" name="data[Ticket]['+indice+'][descricao_ticket]" size="20" placeholder="Informe aqui">	';

Dica
Pode concatenar a variável cols desta forma abaixo para enxugar o código:
cols += '<input type="text" name="data[Ticket]['+indice+'][descricao_ticket]" size="20" placeholder="Informe aqui">	'
+''
+'<button type="button" class="btn btn-danger" onclick="remove(this)">Remover</button>'
+'	';

Comment: Show de bola, deu certinho, obrigado pela ajuda
Comment: @Henrique Valeu! Só uma obervação: quando vc remover uma linha, o indice irá diminuir de novo. Vai dar problema?
Comment: Não tem problema, o importante é apenas não sobrescrever a informação, desta forma me atende perfeitamente.
Comment: @ÐvÐ e Henrique, uma pergunta: tem necessidade de se preocupar com o indice? Porque pode ser usado o recurso de array do atributo name do input text: name="data[Ticket][descricao_ticket][]". Assim todos os inputs com o nome com 'nome_input[]' são submetidos como um array.
Comment: @pss1suporte Teoricamente faz sentido, mas teria que ver com o Henrique se cabe na programação dele.
Comment: @ÐvÐ, sim por isso eu não postei a minha resposta. A sua ficou mais coerente com a pergunta, isto é, ficou mais pertinente. E não é teoria. Geralmente eu uso assim mesmo! Sempre que necessito deste tipo de solução, eu uso o array no nome do input text mesmo e não sobre escreve os dados.
Comment: @pss1suporte Acho válido postar a sua resposta sugerindo o que vc considera melhor, mesmo não sendo exatamente o que foi perguntado, e, claro, explicando o porquê de fazer da forma que sugere. Mesmo que não ajude na pergunta ou não for ser útil ao autor da pergunta, pode ser válido no futuro para outras pessoas.

Índice em JavaScript


How can i iteratively stack rows in numpy using for loop

Question: I am trying to iteratively add rows to my two dimensional np.array
A = np.zeros((1,14),dtype = float)
for i in arr:
    A = np.vstack(fn(i))# function returns array

And as a result i always get only last array i stacked
Can someone please explain me how to stack all rows and why is this not working
Comment: Does this answer your question? [Concatenate all rows of a numpy matrix in python](https://stackoverflow.com/questions/13252781/concatenate-all-rows-of-a-numpy-matrix-in-python)
Answer: You should not vstack while iterating, as it will artificially increase memory usage, as explained in this similar question but related to pandas.
Secondly, assuming fn(i) returns a new array that you want to append to A, then that line should be A = np.vstack((A, fn(i))
Considering all this, a better option would be to create and collect all your arrays into a list that you can later stack.
A = np.zeros((1, 14), dtype=float)
arrays = [A] + [fn(i) for i in arr] # assuming `arr` is an iterable
A = np.vstack(tuple(arrays))

You can read more in the numpy.vstack docs
Comment: It's useful although I don't think usage growth is exponential. It's rather a quadratic one.
Answer: You must add A on vstack:
A = np.zeros((1,14),dtype = float)
for i in arr:
    A = np.vstack([A,fn(i)])# function returns array


Getting 2 string variables out of a getline

Question: I'm curious if it's possible to put letters out of a getline function into 2 separate string variables, sorry if it's hard to understand but I'll explain this further.
Let's say I have a 'string x;' variable, I use a 'getline(cin, x)' and then I were to run this and type in for example 'hello world'. Would it be possible to put 'hello' and 'world' into 2 separate string variables?
For example: It will store the first letter keep on adding letters to a variable until it hits a whitespace, then keep on adding letters to the next variable until it reaches another whitespace.
I understand I might have explained this poorly, and if it's not understandable let me know and I'll try explain more.
Answer: the stream operator>> functions already handle whitespace formatting for you, the canonical way to handle an unknown number of tokens on each line is to do something like the following:
std::string line;
getline(std::cin, line);

std::istringstream iss(line);
std::string token;
while (iss >> token) {
  // Do something with token
}

If you don't care about what kind of whitespace is used to separate the tokens this can be simplified to
std::string token;
while (std::cin >> token) {
  // Do something with token
}

Comment: Appreciate the effort, I'll have to experiment some with your examples and read up on sstream.
Comment: It's really no different from any other stream, only that it operates on `string`s instead.
Comment: std::istringstream iss(line);

Isn't completely understandable to me, so I'll have to figure out what that does, the rest is understandable though.
Comment: `std::istringstream iss(line);` creates a new `istringstream` with its content set to that of `line`.
Comment: I figured I should probably use a string vector instead of storing it in separate strings.
Comment: Was wondering if you could help me out a bit more.

So, if I used your first example and I were to write 'hello world' in the console. Then how would I store these words separately in a vector? How do I make it performing a push_back() for that specific word, then do the same for the rest of the words?
Comment: [Here](http://pastebin.com/sUvNg6sL) are two ways to do this, you might want to avoid the first if you haven't had a look at the relevant parts of the standard library yet.
Comment: Alright, it's working the way I wanted it to. There's just 1 bug at the moment, if I only type a single word and then hit enter I get a unhandled exception > memory out of range or something similar. Any way to fix that? Edit: I mean enter, not space.
Comment: You might be doing something invalid with the input in the read loop, post the relevant code on pastebin or somewhere.
Comment: For my project to work I'll need the getline to be able to handle only 1 word too.
Comment: Works fine for me, what compiler and version / platform are you using? It's worth mentioning that you don't need to use `getline` unless you specifically need to know when you've read any given line, `while (std::cin >> token)` works just as well.
Comment: Not sure what compiler I am using tbh. I'm using Visual studio ultimate 2013 atleast. But, I'll give you some more information on what I'm working on. I'm working on a text based adventure game where everything the player does will be controlled by user input, so every time the user hits enter I would assume that he entered a command. Why I need to use a getline is because the commands will hold different amounts of words. A few examples on commands I have planned: 'walk area' 'use itemname' 'buy itemname quantity' etc. I already have quantity part done to convert the numbers to an int.
Comment: I just built your code in VS 2013 and it ran without a hitch, input was "foobar"
Comment: The unhandled exception only happens with the getline. Still trying to figure out if I can get along with everything fine with just using the while (cin >> token)
Comment: Actually, I'm not having that issue any more. I have no clue why I had it and I have no clue why I'm not having it now. Thanks a ton for your help. Is there anywhere else I can reach you incase I have questions? You seem like a cool lad.
Comment: Just post your questions to SO, if I don't answer someone else (probably with more knowledge than me) will.
Answer: You need a way to parse the string using a delimiter (in this case a space ' ').
This post has about a thousand different functions that can solve what you are trying to do.
Split a string in C++?
Easiest way to do this if you know how many variables you will need would be to take advantage of the default std::cin implementation of using space as a delimiter:
std::string x1, x2;          // define two strings
std::cin >> x1 >> x2;        // user enters "Hello World"
std::cout << x1 <<" "<< x2;  // x1 = "Hello", x2 = "World"

Comment: Your code is perfectly understandable, but this won't work with the idea I have. I need to use a getline and then somehow get variables out of it. Thanks though!


Completing inductive step of proof of Cochran's theorem?

Question: On slides 23-26 here, they prove the case for $k=2$ of Cochran's theorem. I don't see why you can use induction to prove it for general $k$.
In more detail, they already prove the following:

If $$ Q = \sum_{i=1}^n x_i^2 = x'A_1 x + x'A_2 x = Q_1 + Q_2 $$ where
  $A_1$ and $A_2$ are PSD with ranks $r_1, r_2$ such that $r_1+r_2=n$,
  then there exists an orthogonal matrix $C$ such that, with $x=Cy$,
$$ Q_1 = y_1^2 + \cdots + y_{r_1}^2, \\ Q_2 = y_{r_1+1}^2 + \cdots + y_n^2. $$

I don't see how to use this to show it's true for general $k$ not just $k=2$ as above by induction.
If you split $Q_2$ into $Q_{21}+Q_{22}$ where $Q_{21}$ and $Q_{22}$ have ranks $a$ and $b$ for example, then you'd have a different orthogonal matrix $C_1\neq C$ such that, for $\hat{x}=(x_{r_1+1},\ldots,x_n)$,
$\hat{x}=C_1 y$ and
$$Q_{21}=y_{r_1}^2 + \cdots + y_{r_1+a-1}^2,\quad Q_{22}=y_{r_1+a}^2 + \cdots + y_{r_n}^2$$
I don't see how you can show from $k=2$ that this is true for general $k\geq 2$, i.e. that there exists an orthogonal matrix $C$ that simultaneously gets us $$Q_i = y^2_{r_1+\cdots+r_{i-1}+1} + \cdots + y^2_{r_1+\cdots+r_i}$$ for $i=1,\ldots,k$. Anyone know how to complete this proof?
Answer: Sup Y9,
Note that the assumption $r_1 + \cdots + r_n = n$ will be problematic if you try to set up the induction directly, since if you handle $A_1$ first, you are left with $r_2 + \cdots + r_n$ which is not equal to $n$. This suggests that the induction involves looking at a lower-dimensional problem, i.e. the "new $n$" when you apply the induction step after handling $A_1$ is $\tilde{n} = r_2 + \cdots + r_n$, as described below.

It might be easier to state the result as follows: if $A_1, \ldots, A_n$ are PSD with ranks summing to $n$ satisfying $I = A_1 + \cdots + A_n$, then there exists an orthonormal basis $\{c_1, \ldots, c_n\}$ such that

$A_1$ is the identity on the subspace $\text{span}\{c_1, \ldots, c_{r_1}\}$, and zero on the orthogonal complement,
$A_2$ is the identity on the subspace $\text{span}\{c_{r_1 + 1}, \ldots, c_{r_1 + r_2}\}$, and zero on the orthogonal complement,
and so on.

[Note that $c_1, \ldots, c_n$ here correspond to the columns of $C$ in the original formulation of the result.]

Using the $k=2$ result, we can handle the situation $I = A_1 + B$ where $B := A_2 + \cdots + A_n$.
This implies $A_2 + \cdots + A_n$ is the identity on the subspace $\operatorname{span}\{c_{r_1 + 1}, \ldots, c_n\}$, and zero on the orthogonal complement i.e. $\operatorname{span}\{c_1, \ldots, c_{r_1}\}$.
Since $\operatorname{rank}(A_2) + \cdots + \operatorname{rank}(A_n) = r_2 + \cdots + r_n = n - r_1 = \operatorname{rank}(A_2 + \cdots + A_n)$, each individual $A_i$ must also be zero on $\operatorname{span}\{c_1, \ldots, c_{r_1}\}$.
So we can restrict our attention to this $(n-r_1)$-dimensional subspace $\operatorname{span}\{c_{r_1 + 1}, \ldots, c_n\}$,  and we have another instance of the theorem's conditions, since the sum of $A_2, \ldots, A_n$ is the identity, and the sum of their ranks is the dimension of the space ($n - r_1$). By induction, we may apply the theorem to this smaller problem and obtain the result.

It is possible to translate the above proof into strictly matrix notation if you wish. The gist of it is that you can modify certain subsets of columns of $C$ at a time without messing up previous steps.
When you make lots of money from your cushy job, please remember us.
Comment: @Glassjawed $\text{colspace}(A_2 + \cdots +A _n) \subseteq \text{colspace}(A_2) + \cdots + \text{colspace}(A_n)$ always holds in general. The rank condition further implies equality of these subspaces. Then $\text{colspace}(A_i) \subseteq \text{colspace}(A_2 + \cdots + A_n)$.
Comment: Thank you! Yeah hoping to land a postdoc somewhere first but if that doesn't work out...welp.
Comment: Why is it that $\operatorname{rank}(A_2) + \cdots + \operatorname{rank}(A_n) = r_2 + \cdots + r_n = n - r_1 = \operatorname{rank}(A_2 + \cdots + A_n)$ implies each individual $A_i$ must also be zero on $\operatorname{span}\{c_1, \ldots, c_{r_1}\}$?


terraform "element" and "concat" used together

Question: we have a module that builds a security proxy that hosts an elasticsearch site using terraform. In its code there is this;
elastic_search_endpoint = "${element(concat(module.es_cluster.elasticsearch_endpoint, list("")),0)}"

which as I understand, then goes and finds the es_cluster module and gets the elasticsearch endpoint that was outputted from that. This then allows the proxy to have this endpoint available so it can run elasticsearch.
But I don't actually understand what this piece of code is doing and why the 'element' and 'concat' functions are there. Why can't it just be like this?
elastic_search_endpoint = "${module.es_cluster.elasticsearch_endpoint}"

Comment: It is probably an archaic type conversion pattern from Terraform <= 0.11.
Answer: Let's break this up and see what each part does.
It's not shown in the example, but I'm going to assume that module.es_cluster.elasticsearch_endpoint is an output value that is a list of eitehr zero or one ElasticSearch endpoints, presumably because that module allows disabling the generation of an ElasticSearch endpoint.
If so, that means that module.es_cluster.elasticsearch_endpoint would either be [] (empty list) or ["es.example.com"].
Let's consider the case where it's a one-element list first: concat(module.es_cluster.elasticsearch_endpoint, list("")) in that case will produce the list ["es.example.com", ""]. Then element(..., 0) will take the first element, giving "es.example.com" as the final result.
In the empty-list case, concat(module.es_cluster.elasticsearch_endpoint, list("")) produces the list [""]. Then element(..., 0) will take the first element, giving "" as the final result.
Given all of this, it seems like the intent of this expression is to either return the one ElasticSearch endpoint, if available, or to return an empty string as a placeholder if not.

I expect this is written this specific way because it was targeting an earlier version of the Terraform language which had fewer features. A different way to write this expression in current Terraform (v0.14 is current as of my writing this) would be:
  elastic_search_endpoint = (
    length(module.es_cluster.elasticsearch_endpoint) > 0 ? module.es_cluster.elasticsearch_endpoint : ""
  )

It's awkward that this includes the full output reference twice though. That might be justification for using the concat approach even in modern Terraform, although arguably the intent wouldn't be so clear to a future reader:
  elastic_search_endpoint = (
    concat(module.es_cluster.elasticsearch_endpoint, "")[0]
  )

Modern Terraform also includes the possibility of null values, so if I were writing a module like yours today I'd probably prefer to return a null rather than an empty string, in order to be clearer that it's representing the absense of a value:
  elastic_search_endpoint = (
    length(module.es_cluster.elasticsearch_endpoint) > 0 ? module.es_cluster.elasticsearch_endpoint : null
  )

  elastic_search_endpoint = (
    concat(module.es_cluster.elasticsearch_endpoint, null)[0]
  )

Answer: First things first: who wrote that code? Why is not documented? Ask the guy!
Just from that code... There's not much to do. I'd say that since concat expects two lists, module.es_cluster.elasticsearch_endpoint is a list(string). Also, depending on some variables, it might be empty. Concatenating an empty string will ensure that there's something at 0 position
So the whole ${element(concat(module.es_cluster.elasticsearch_endpoint, list("")),0)} could be translated to length(module.es_cluster.elasticsearch_endpoint) > 0 ? module.es_cluster.elasticsearch_endpoint[0] : "" (which IMHO is much readable)

Why can't it just be like this?
elastic_search_endpoint = "${module.es_cluster.elasticsearch_endpoint}"

Probably because elastic_search_endpoint is an string and, as mentioned before, module.es_cluster.elasticsearch_endpoint is a list(string). You should provide a default value in case the list is empty
Comment: *"Why is not documented?"* - probably because it is not document-worthy. As you say one sentence later *"There's not much to do"*.
Comment: There's not much to do with just that single line of code. We don't know the types of each value!


MLE for parameter n in Binomial

Question: How is the MLE for n calculated if p and k are given? I've been stuck on this forever and cannot seem to even find a similar example of calculating MLE of n.
Comment: See also https://stats.stackexchange.com/questions/123367/estimating-parameters-for-a-binomial/123748#123748
Comment: You can avoid votes to 'close' a textbook question by showing what you have tried and why you need help. Also, a 'self-study' tag seems appropriate. Perhaps 'take the tour' of our site.
Answer: First, $k = 25$ and $p = 1/19,$ so the method-of-moments estimator (MME) is
$k/p = 475.$ We don't know whether the maximum likelihood estimator
is the same, but it may be similar. I will do a grid search in R, where a binomial PDF is denoted dbinom,
to find the MLE.
p = 1/19;  k = 25;  n = 200:800
like = dbinom(k, n, p)
mle = n[like==max(like)];  mle
[1] 474
plot(n, like, type = "l")
 abline(v = mle, col="red")
 abline(h=0, col="green2")

Check for uniqueness (because R rounds to some number of places):
like[n==474]
[1] 0.08170127
like[n==475]
[1] 0.08170127

So the MLE is either 474 or 475. We might as well use the MME.
I will leave it to you to provide an analytic argument that
this answer is correct. (For discrete quantities, a common approach to find a maximum is to look at ratios.)
Of course, all of this assumes that the usual rules of probability apply to extraordinarily beautiful Eastern European princesses playing roulette at the Bellagio.

MLE for parameter n in Binomial


How do I change the image style for avatars displayed in comments

Question: I'd like to use a custom image style for the comment avatars, but I don't know where the setting in Drupal is to change it.
I thought if I changed the user image style at admin/config/people/accounts/display that might work, but it doesn't. There's no image field at admin/structure/comment/manage/comment/display, so I can't change the style there.
I did this on a site a couple weeks ago on another site, but I can't remember for the life of me how I did it. I don't think I needed to make code modifications. Help?
Answer: You can modify the image style used for displaying avatars in comments by editing the "compact" display mode for user accounts.
The setting can be found at /admin/config/people/accounts/display/compact. Or by navigating the administration interface:

Admin -> Configuration
Account Settings
'Manage display' tab
'Compact' sub tab.
On the 'Picture' row, click the edit field settings button (Cog image) located on on the right.
Then select your image style.
Comment: Ah, there it is. I have a bad habit of missing that row of different displays on the "Manage display" tab. Thanks for the help!


cartesian product of two metric spaces separable if and only if each of them is separable

Question: Let $(X,d)$ and $(Y,d')$ be two nonempty metric spaces. We consider in $X\times Y$ the metric $d_{\infty}$ defined as $\max\{d(x_1,x_2),d'(y_1,y_2)\}$. Prove that $(X\times Y,d_{\infty})$ is separable if and only if $(X,d)$ and $(Y,d')$ are separable.
I could prove that if the two metric are separable, then the cartesian product is separable. What I did to prove it was: We know that $X$ and $Y$ are separable, so take $E$ and $E'$ dense countable sets of $X$ and $Y$ respectively. Let's prove that $E\times E'$ is a dense countable. $\operatorname{cl}(E\times E')=\operatorname{cl}(E)\times\operatorname{cl}(E')=X\times Y$.
I don't know how to prove the other implication.
Comment: You need to assume that neither space is empty, otherwise the conclusion is wrong. Can you prove that a subspace of a separable metric space is separable?
Comment: But if the two spaces happen to be empty, then they are trivially separable and their product is separable. If one of the two is empty and the other is non-empty, I don't see why the conclusion is wrong.
Comment: If one of the two spaces is empty and the other not separable, the product is empty, hence separable.
Comment: You're right, I'll edit my post and add the nonemptyness condition.
Answer: Let $A$ is the dense subset of $X\times Y$ and $\pi_X:X\times Y\to X$ and $\pi_Y:X\times Y\to Y$ are projection. We will prove that $\pi_X(A)$ is dense subset in $X$. Let $V$ is open subset of $X$, then $V\times Y$ is open subset of $X\times Y$. Since $A$ is dense subset of $X\times Y$ so $V\times Y$ contains some element of $A$, so $\pi_X(V\times Y)=V$ contain the some elements in $\pi_X(A)$. Similarly you can prove that $\pi_Y(A)$ is dense subset of $Y$.
Answer: Let $E$ be dense in $X\times Y$ and let $E'$ be its projection to $X$. Then $E'$ is dens in $X$ because for any nonempty open set $U$ of $X$, there is a point of $E$ in the nonempty open set $U\times Y$ of $X\times Y$, hence a point of $E'$ in $U$.


Resource lock waiting for user interaction in client-server solution

Question: I have a client-server process that after a long-running operation (2-5 minutes) server side, ask the user to confirm or change the operation results.
User can take an hour or more to check the work done by the service, make changes and send those back to service.
In a perfect world nobody would change underlining source data used by the service to build the operation results.. but this isn't a perfect world!
How can I lock in order to prevent damage on my source data? I don't want SQL table lock... I'm thinking about a software mechanism like an in-memory table with all my operation requests  and some interlock condition in order to put in a wait state operation that can damage other operation data.
Any other hint about?
Edit
More info about the process is probably necessary..
I have a timestamped entity that represent a point in time of an electrical network topology.
The entity contains a list of all elements not energized.
The server process when called must take all entities not already processed and for each element create a list of
<code>public class ElementRecord{
public string ElementName {get;set;}
public DateTime OffTimeStamp {get;set;}
public DateTime OnTimeStamp {get;set;}
}
</code>
Based on some business rules the server process aggregate the elements and wait for user ack or changes.
The problem is that after entities are loaded, real network can change and the table will change; also in a single point of time more elements can be de-energized so server process must invalidate.
If user UI is already changing data I have to alert soon that probably some data is invalid.
What you will do?
Answer: I has encountered the similar requirement in one past project.
Our solution was: after the server finished all operation, we copied all data which needs user to confirm to some temp data tables with timestamp for every row. And then, send mail to user to ask confirming, after the confirming, merge the temp data tables to our real data tables. We could not lock any data table, because other users need to change the table online.
Answer: How about adding an extra column to your tables to show that the data has been verified.
Data that doesn't have the verfied field set is then ignored. In a legacy system this would mean creating new tables and migrating the data over, but after that all you need is to ensure that only results where the verified field is set are returned to your code.
edit
What I was suggesting was that processes reading data can only use data that has been verified. If your user process is using and changing verified data then it must set the data unverified on retrieval, but it cannot retrieve that data if it has already been marked as unverified.
For new data you just create a new row with default data and get the row index back before verifying the new data. Your code then has the index and so the user can take as long as they like to verify the data and if they don't then you have the index so that you can delete the data already created.
Comment: I have already a Done column that must be set after user acknowledge. The only problem I see if I add another column is that insertion of another row between (timestamp is an index of the table) results of the service process can change depending of other factor.. So if a user start the long-running process and don't finish it with an ack, I'm stuck with semi-processed entities that I can't link to a dead task..
Comment: See my edit - does this answer your question? If not then can you be a bit clearer about the order in which the data is processed e.g. whether it uses data from the DB that must be locked, memory caching etc.
Comment: I edited my question adding more details about the process, take a look


Removing many Exchange full access permissions on a mailbox

Question: I'm trying to use Powershell to remove certain full access permissions on an account as part of a disable user process.
I need to remove all full access permissions on the account except for:
NT AUTHORITY\SELF
and
DOMAIN\svcEnterpriseVault
How can I go about doing this using the Remove-MailboxPermission cmdlet?
Thanks
Edit:
I've gotten a little further with the command below, but I am having trouble passing the list of full-access users to the Remove-MailboxPermission cmdlet.
Get-MailboxPermission -Identity $TheUser | Select User | where {($_.User -notlike
 "NT AUTHORITY\SELF") -and ($_.User -notlike "DOMAIN\svcEnterpriseVault")} | Remove-MailboxPermission -Identity $TheUser -User [ALL THE USERS FROM THE GET-MAILBOX COMMAND]

Answer: Can you just do this?  I removed the "Select User" since that is for display purposes only and used no parameters on "Remove-MailboxPermision" since it accepts input.  Haven't tested though.
Get-MailboxPermission -Identity $TheUser | where {($_.User -notlike
"NT AUTHORITY\SELF") -and ($_.User -notlike "DOMAIN\svcEnterpriseVault")} |
Remove-MailboxPermission

Answer: Due to this site I tried to add -Identity at the end of the line, as in the line on the top. This worked for me.
I excluded also some other users, because I don't know exactly what they do, am afraid to delete too much. I also added -confirm:$false:
Get-MailboxPermission -Identity $TheUser | where {($_.User -notlike "NT AUTHORITY\SELF") -and ($_.User -notlike "NT AUTHORITY\SYSTEM") -and ($_.User -notlike "DOMAIN\Exchange Servers") -and ($_.User -notlike "DOMAIN\Exchange Trusted Subsystem") -and ($_.User -notlike "S-1-5-21*") -and ($_.User -notlike "DOMAIN\Domain Admins") -and ($_.User -notlike "DOMAIN\Organization Management") -and ($_.User -notlike "DOMAIN\Enterprise Admins") -and ($_.User -notlike "DOMAIN\Administrator") -and ($_.User -notlike "DOMAIN\Public Folder Management") -and ($_.User -notlike "NT AUTHORITY\Network Service") -and ($_.User -notlike "DOMAIN\Delegated Setup")} | Remove-MailboxPermission -Identity $TheUser -AccessRights FullAccess -confirm:$False


Syncfusion (Essential Studio) - AutoComplete open after CTRL+SPACE (Buttons)

Question: we are using Syncfusion's Essential Studio for windows forms.
At the moment iam working on a small code-editor for pascal which uses the EditControl. The IntelliSense like autoComplete Function opens after typing the lexems we just defined (eg. ".") and gives us all defined Methods of our API. Thats ok.
But we need to open the AutoComplete dialog after just pressing the Buttons CTRL + SPACE and showing us all api methods, regardless of whether we typed a lexem or not. Since it is Pascal without any OOP, thats the only way it makes sense.
How is that possible?
Greez Chris
Answer: Query : How to open Context choice after pressing STRG + Space?
Please make use of below code and sample for open ContextChoice list after STRG +Space
<code>Code [C#]:

  // Adds "<?" word processing for global context.
  ConfigLexem lexemId = GetConfigLexem((IConfigLexem)editControl1.Language, "STRG");

 lexemId.Type = FormatType.Text;

// "<?" starts it`s own context. It does not have EndBlock specified, so the first unprocessed token will force parser to exit from "this"'s context.

  lexemId.IsComplex = true;

  //To open the Context Choice after space
  ConfigLexem lexemQues = GetConfigLexem((IConfigLexem)lexemId, " ");
  lexemQues.Type = FormatType.Operator;
  // "?" can drop context choice list
  lexemQues.DropContextChoiceList = true;
  lexemQues.IsComplex = true;

Code[VB]:

   ' Adds "<?" word processing for global context.

 Dim lexemId As ConfigLexem = GetConfigLexem(CType(editControl1.Language, IConfigLexem), "STRG")

   lexemId.Type = FormatType.Text

   ' "<?" starts it`s own context. It does not have EndBlock specified, so the first unprocessed token will force parser to exit from "this"'s context.

   lexemId.IsComplex = True

   'To open the Context Choice after space
    Dim lexemQues As ConfigLexem = GetConfigLexem(CType(lexemId, IConfigLexem), `enter code here`" ")
    lexemQues.Type = FormatType.Operator
    ' "?" can drop context choice list
    lexemQues.DropContextChoiceList = True
    lexemQues.IsComplex = True
</code>
Sample C#: http://www.syncfusion.com/downloads/support/directtrac/general/ze/EditControl_Intellisense1331161585
Sample VB: http://www.syncfusion.com/downloads/support/directtrac/general/ze/EditControlVb-143548194
Note: I work for Syncfusion
Comment: Maybe i wrote it a little misleadingly, because i wrote "STRG" instead of "CTRL".

What we want is to open the contextCoiceList after Pressing the **Buttons**:
_CTRL_ + _SPACE_. Just like in VS.

Not after typing the String "STRG " or "CTRL ". (edited the question)
Comment: Just a reminder, because the answer got already 2 upvotes.
The above answer is **wrong**.
Comment: @Chris, what is the correct answer if you don't mind sharing it?


VmWare image to HDD

Question: !Hello, I am virtualizing a Windows 2003 Server in VMWare Server 2.0.2. My goal is to take the virtualized HDD and make it a physical one so that i can boot a real server from it and run it outside of a virtualized environment. I know of this answer which shows how to do this clearly, my only issue is that they use vmare workstation and vmware server doesn't have the "Use physical drive" option when following these steps. Here's the link to that answer.
http://www.howtoforge.com/converting-a-vmware-image-to-a-physical-machine
So after you have possibly reviewed that 3rd party answer could anyone suggest another way of doing so while using VMWare Server 2.0.2? Thanks to Everyone!
Comment: VMware Server 2.0.2? *Why*? It went end of general availability in 2008!
Comment: Here's how:
http://serverfault.com/questions/17624/what-is-a-system-state-backup-for/247908#247908
See my answer in the post.
Comment: @MDMarra: I guess because this the only VMware product that is not a stand-alone hypervisor. Isn't it?
Comment: However I'd recommend to migrate to [VMware ESXi](http://www.vmware.com/products/vsphere-hypervisor/) or Microsoft Hyper-V (doesn't require stand-alone hypervisor).
Comment: @abatishchev - no, there are others. Player, Workstation, etc.
Comment: @MDMarra: I'm not familiar with Workstation but Player is not a server solution, just player, pure desktop. That's what I mean.
Comment: @abatishchev neither are meant for use on a server, but VMware Server hasn't been meant for use on a server since 2008 either. That was my point.
Comment: So any other VMware server visualization solutions not requiring stand-alone hypervisor? No. That's was my point. I used VMware Server for a long after 2008 by myself. But it's (almost) 2014 and you find a better solution easily. The same for running Windows Server 2003.
Answer: Back up the server with the backup tool of your choice. Follow that tool's procedure for a restore to dissimilar hardware.
Comment: At some point you're going to have to do some research on your own. That point is now. Part of being a *professional* is reading and understanding documentation. It's a critical skill that will carry you far.
Comment: Do you have a suggestion to such a tool? Also if it were free it would be much appreciated
Comment: [Windows has NTBackup built in](http://technet.microsoft.com/en-us/library/aa998799(v=exchg.65).aspx). [Google is your friend](https://www.google.com/#q=server+2003+backup+tool).
Comment: Thank You SOSOOOOOOOOOOOOOOO MUCH!!  I have not completed the backup yet but this seems to be very assuring!
Comment: although i must ask, will i have to have the installation disk to restore this "backup"? or can I just copy it to a usb and boot from it?

VmWare image to HDD


What are "apparent octaves and unisons"?

Question: In the workbook for "Harmony and Voice Leading" (5th edition), there is an exercise on page 14 for which I need to write an accompaniment.
As you can see in the instructions, octaves and unisons between the three upper voices and the solo line are permissible. Can someone explain what this means?
Answer: An apparent octave (or fifth) occurs when a note is double but is not intended to create another "voice." For example, in strict four-part harmony, one tries to keep all four voices independent so the listener is able to hear four moving melody lines. The "bad" parallel octaves (or fifths) occur when two voices undergo parallel movement in octaves (or fifths.) For example, moving from a C major chord to a D major chord could be problematic. C-E-G-C followed by D-F#-A-D doesn't give the impression of 4 voices, rather it sounds like a single (somewhat complex) voice.
In the example quoted, there is a melody voice with a piano accompaniment to be filled in. In such a case, the piano may play sections using a different number of voices. Often anywhere from 2 to 5 voices are common in such accompaniments. One has to be careful that there is a consistent 3 or more voice texture but some voices may be doubled. One rarely gets away with doubling the bass or the melody but in a full orchestra, lots of doubling happens.
Comment: Ok so if the melody line goes C D E and an inner voice in the accompaniment does the same then this is fine? It is almost like you are saying that even though there are four voices required for the accompaniment and one voice given, there will only be 4 real voices not 5 since one will just be a double of the melody within the accompaniment, is this the way I am to understand it?
Comment: A bit like that. One thing that happens often is that the bass line is duplicated an octave lower.  Sometimes the melody is duplicated in octaves; not in the posted score though; it has a separate melody line so the piano probably shouldn't duplicate it. If the piano is accompanying in both hands (as it seems), chords may be duplicated. In a block chord setting one might have C-G-C in the bass and C_E-G-Bb in the Treble. without violating the rules. (It's more monophonic and the chords need not be heard as independent voices.) The bass still should be independent of the melody.
Comment: The melody will have to be doubled in one of the inner voices of the accompaniment since this is not going to be a thing where you have the soprano as the top voice is it? The register of the melody is too low to have chords built underneath it. Here is another example from the same textbook where they suggest two first chords. Look at the melody and look at the accompaniment. You can see the melody notes in different voices of the accompaniment. First the E as the alto of the accompaniment and then the C as the soprano https://ibb.co/9TKRhYg
Comment: I think that example also demonstrates "apparent" unisons. One thing that seems clear to me after seeing this later exercise is that while the top voice of the accompaniment is not always the same as the melody note as provided but the accompaniment seems to span the range of the melody. Not sure why this is the case but that seems to be deliberate here


Objective C shenanigans

Question: In my quest to be the grandmaster of Objective C, I keep running into it's subtleties, which I  want to share with ya'll and gain an understanding why
1) I have two init methods, the one that is inherited by NSObject for my Objective C class and one is a custom method that I create off my own, let's say
initCustomMethod:(int)par1 argument2:(int)par2;

My Aim is to call initCustomMethod through the provided init method, essentially
-(id)init{
    return [self initCustomMethod:1 argument2:3];
}

Naturally, maintaining the order, I have init appearing before initCustomMethod in the .m file. Xcode warns me telling me that the initCustomMethod is not found, I go ahead and shuffle the order and have init appearing after initCustomMethod is declared and there is no such warning message anymore and everything is fine.
I concur that the order is important since it's essentially derived from C, however I am not sure of this. Because, i shuffled the order of some properties and their custom methods, with the properties @synthesize being declared after the custom setter method for a given property, but there was no such error replica.
Can anyone point out the malice here?
Thanks guys!!!

Very cool guys, thanks for helping me out with this. Also, since I have a custom init method, I am initializing the super in this method and using the original init method to call the custom init method.
Anything wrong with this?
Answer: Before you reference it anywhere, you should declare initCustomMethod:argument2 in your interface, which would usually be in your header file.
For example, you would usually have a .h file that looks like:
@interface MyClass
{
    //instance variables
    int anInstanceVariable;
}

// properties
@property (nonatomic, assign) int aProperty;

// methods
-(id)initCustomMethod:(int)par1 argument2:(int)par2;

@end

And if you did this, the order in which you define init and initCustomMethod:argument2: won't matter.  This is because the declaration tells the compiler that you are going to define the method, and what it will look like, so it isn't confused when you use it later.
Answer: It's a bad idea in Objective-C to use a function or a method before it is either declared or defined. Putting initCustomMethod:argument2: before init means that the former is already defined in the latter. But if you'd just declare it in the header, it wouldn't matter which order they went in.
Answer: Add your custom method name in your header file - the compiler just goes through things in order.  If you don't have a forward declaration, the compiler won't know what to do with that call.  You're going to need to put it in the header if you want other parts of your program to be able to call it anyway.

Objective C shenanigans


Why Benetton Treviso and Zebre Parma plays Pro12 League?

Question: Why do Benetton Treviso and Zebre Parma do not play in Italian Eccellenza (the most important national league) and play abroad in Pro12 League with teams from Great Britain and Ireland?
The winner of Eccellenza is the national champion team or not?
Answer: For the same reason that the top Welsh, Irish and Scottish teams play in the Pro12: because it's a higher standard of play, giving entry to things like the European Cup. As such, there isn't really a "national champion", just as there isn't in Wales, Ireland or Scotland.


What does a DI box do?

Question: I'm not new to recording music but I've almost always used a microphone to gather the sound.
I have heard people referring to a "DI box" when plugging an instrument (guitar/bass) directly into a recording/mixer input.
I have tried a DI box but not knowing what it's supposed to do, I couldn't really hear that it was doing anything.
I realise the signal could go via effects etc as well, with amp simulators etc, but my question is this :

Is this how a DI box is generally used ? Instrument -> effects -> DI box ->
recording device ?
What does a DI box actually do to the signal ?
What is the resulting effect?
Especially this : What would I listen for in the recorded sound to know that the DI
box is doing something ?
Answer: A DI box breaks the galvanic connection.  It's most important use is breaking ground loops, and also for changing unbalanced signals to balanced (the latter transfering better over long connections).
If your effect boxes are running on battery and are not mounted on metal and go to an instrument amp (rather than a mixer) next, the DI box will not do much in its main function (it might still change impendances and levels, partly depending on whether it is an active or passive box).
If you are connecting devices that are intended to be connected, and there is no separate signal path, you won't need a DI box as a rule.
The most common "definitely needed" case is going from one amp to another, or from amp into mixer.  This will usually even be the case when using a preamp output from one amp, for example in order to get the amp effects (like a coil reverb) into the mixer via a direct path.  Since you connect two grounded amps in that case, the DI box will save you from getting ground loop hum.
At any rate, it is a good idea to have a few spare DI boxes in your toolbox and play with them.  That way you develop a feeling for when throwing one in might make a difference, and when not.
Comment: Hi - re "The most common "definitely needed" case is going from one amp to another, or from amp into mixer." - is that because those are devices whcih have their own power supply and thus a potential for creating a ground loop ?
Comment: sorry forgot to tag you
Comment: tags aren't needed when the recipient is "obvious", like author of post and author of immediately preceding comment @see-what-I-mean?
Answer: Very simply: a DI (direct input) box is a utility, not an effect. It lets you run the input of an instrument directly into, say, the mixing board. This is sometimes necessary for the grounding/balance reasons user15196 mentions. Other times, it's desirable for aesthetic reasons.
For example, I've seen bass sometimes recorded directly: bass -> di box -> mixer, rather than bass -> amp -> microphone -> mixer. Personally, I usually prefer to record both and mix the two signals to taste, which requires:
<code>bass -> di box -------> mixer (channel 1)
           |
           v
          amp -> mic -> mixer (channel 2)
</code>
The path from the DI box to the amp is the "bypass".
Also, di boxes sometimes have inputs/outputs that boost or dampen (pad) the signal, which might be necessary if the signal you're recording is, for example, too hot (loud).
To answer your question #4: "What would I listen for in the recorded sound to know that the DI box is doing something?" Answer: you are able to hear/record the signal directly (without the use of a microphone) in your mixer/recorder cleanly, and the levels/volumes are appropriate.
Lastly, DI boxes sometimes have phantom power. So if you have a condenser microphone, but your mixer doesn't provide phantom power, you can instead plug it into a DI box that can be used to power the microphone.
Comment: Thank you- this is the most useful answerr (for me at least). I was listening for some change in the sound when recording and hadn't realised reduction of hum is a factor.
Answer: A DI box makes an instrument look like a microphone electrically, so it may be plugged into a mic input on a mixer or recording interface, using a long cable if needed.  There will also probably be a ground-lift switch, which can cure hum problems when the instrument uses mains power. But a DI box is a bit more than just an isolating transformer.

What does a DI box do?


update @form não funcionando, Java EE

Question: Ja tentei com as opções @form, :matricula, matricula_form... e nada.
Quando excluo a matricula do banco, apenas após atualizar a página ela some, estou esquecendo de algo???
Segue abaixo código "matricula_lista"
<!DOCTYPE html>

        <h:outputText value="#{matricula.numero}" />

        <h:outputText value="#{matricula.aluno.nome}" />

        <h:outputText value="#{matricula.curso.nome}" />

        <h:outputFormat value="#{matricula.dataMatricula}">
            <f:convertDateTime pattern="dd/MM/yyyy" />
        </h:outputFormat>

Answer: As vezes (que não sei explicar exatamente pq :D) o javascript da página desabilita.
Uma opção seria atualizar o componente via bean da página.
RequestContext.getCurrentInstance().update("id_componente");

update @form não funcionando, Java EE


Flooring Number Theory

Question: How should one approach the floor function of a binomial expansion mod an integer? For instance, what is
$$\left\lfloor\left(\sqrt{2}+\sqrt{3}\right)^{2020}\right\rfloor$$
mod $101$?
I tried to expand using the Binomial Theorem, and then taking the each term of the resulting expansion mod 101, but stumbled upon cases like $\binom{2020}{101k}$. I don't really know how to go from there. Any help would be appreciated!
Comment: Hint:  Let $a_n=(\sqrt 2+\sqrt 3)^{2n}+(\sqrt 3-\sqrt 2)^{2n}$ Argue that $a_n\in \mathbb N$ for all $n$ and that the second term goes to $0$ for large $n$.
Comment: Hmm... I'll think about it. Thanks!
Answer: Let $x_n=(\sqrt{2}+\sqrt{3})^{2n}, y_n=(\sqrt{3}-\sqrt{2})^{2n}$.
We have $x_n+y_n=2((\sqrt{3})^{2n}+\tbinom{2n}{2}(\sqrt{3})^{2n-2}(\sqrt{2})^2+...+\tbinom{2n}{2n-2}(\sqrt{3})^2(\sqrt{2})^{2n-2}+(\sqrt{2})^{2n})\in \mathbb N$.
Also $y_n\in (0,1)$, so $\lfloor x_n\rfloor = 2((\sqrt{3})^{2n}+\tbinom{2n}{2}(\sqrt{3})^{2n-2}(\sqrt{2})^2+...+\tbinom{2n}{2n-2}(\sqrt{3})^2(\sqrt{2})^{2n-2}+(\sqrt{2})^{2n})-1$.
Let $n=1010$, then $\lfloor x_{1010}\rfloor = 2((\sqrt{3})^{2020}+\tbinom{2020}{2}(\sqrt{3})^{2018}(\sqrt{2})^2+...+\tbinom{2020}{2018}(\sqrt{3})^2(\sqrt{2})^{2018}+(\sqrt{2})^{2020})-1\equiv 2(3^{1010}+2^{1010})-1\pmod {101}$
Then you can finish it by yourself.

Flooring Number Theory


How can I create my desired template name suggestion?

Question: For example, Imagine that I designed two main-menu with different style and template one for the header region (top bar, primary menu section)
and another for the footer region as a "footer map" on my site as it's common in the most sites.
Since Drupal 8 it's not possible with template naming conventions to load a specific block template according to the region it is placed in ("Per-region block markup and per-region block templating feature removed").

In Drupal 7 it was possible to specify separate block templates per
  region, such as block--header.tpl.php and block--footer.php to output
  different HTML for blocks placed in the header and footer regions. It
  was also possible to adjust variables based on the region in
  hook_preprocess_block(). Both of these features have been removed.

I decide to use below code, by using the below code I can add block region and id to the block template name suggestion:
function MYTHEME_theme_suggestions_block_alter(array &$suggestions, array $variables) {
  if (!empty($variables['elements']['#id'])) {
    $block = Block::load($variables['elements']['#id']);
    $suggestions[] = 'block__' . $block->getRegion() . '__' . $variables['elements']['#id'];
  }

If I have considered tree or even more footer region in my theme then my theme users should have this freedom to change the order
of displaying this designed footer menu independent of which sub-footer region that's inserted in;
It is more useful if we design in LTR languages (Like English) and RTL languages(Like Persian)Simultaneously.
But what's that become outputted from above code is something like this:
block--footer-1--mainnavigation-2.html.twig
I think it's a good idea to design the different menu with different semantic name template separately.
It's quite obvious if I need multi instances of a block then Its must probably be in different region, therefore, this difference in positioning make a good and sufficient semantic name convention to assign name to templates and get rid of complication.
for this reason, I want to remove the numbers from the end of block identifier because I think this is very dedicated and I want to achieve something like this:
block--footer--mainnavigation.html.twig
Something else that I want to pay attention to it is if I choose another footer names for example:
footer_menue instead of footer_1 then this hasn't necessary dynamics in theme layer due to the above reasons.
Anyway, the name convention that I like and follow out is:
What's this?(Most common part) it's block or page or....
Where should be placed? header, footer....
What is his name or usage? main-menu, Search Block,...
Like:Block+Region Name without Number+ Block(id) name without number
Comment: ```$suggestions[] = 'block__' . explode('-', $block->getRegion())[0]``` .. very very simple example. You have to check the content first of course.
Comment: Or ```preg_replace('[^a-zA-Z]', '', $block->getRegion())```
Comment: You could use preg_match or explode on those two values to get only the first portion.
Comment: If you ever create another menu based on the Main Navigation, now you will have templates that collide.
Comment: Same for regions named footer_1, footer_2, etc
Comment: @Clive: Yes I have some footer like: footer_1, footer_2.
Comment: @Kevin: Thanks for your comment, But I think this template name suggestion pattern has enough dedication because I use other menus in other regions.
Answer: If you want to have more meaningful template suggestions, why don't you use better region names and block ids?
Region names are up to your theme, so instead of footer_1, use footer_something, and block configuration names are also up to how you configure/name your blocks.
You could use PHP to filter those things out, that's nothing really drupal specific, but that's likely increasingly complicated as you will have blocks and regions without those number suffixes, so you need to be caruful in not cutting those off.
Also, you could use suggestions based on the block plugin ID, not configuration ID, then placing the same menu multiple times will give you the same template suggestion.
Edit: If you really want to get rid of those kind of suffixes, then you could for example use trim:
rtrim('footer_1', '123_');

You can put whatever characters in there that you want, and it will remove them all from the right side of the string (there is also ltrim for left and just trim for both sides). Note that this will also remove a _ at the end if you have that.
Comment: Thank you so much, I appreciate you a lot for your beneficial answer, But I think I not clearly explained my mean, That's why I updated my post, Please read my new post. I'm eager to know your new opinion about it. Thanks.
Comment: Updated the answer.


how to score a time dependent cox analysis data?

Question: I have trained a data set with survival analysis using the cox method with time dependent covariates.
The training data is set up to do the time-dependent analysis, where there are multiple rows for a single ID dependent on when the time-dependent covariates occur. The prediction is the "event".
For example, here is how a single observation is set up to do the time dependent piece.

My question is, after I trained the model, what format does my holdout set need to be for scoring?  my scoring dataset is currently one row per observation. Do I need to deliberately duplicate my each observation multiple times so it has 4 rows with the same time start and time end dates?
my goal is that for each scored observation, I can look at the survival curve from 0 to 20.
Comment: I don't know if you use SAS or R for your analysis, but if you use R, [this link](https://cran.r-project.org/web/packages/survival/vignettes/timedep.pdf) on time dependent covariates and coefficients might be helpful
Answer: With time-dependent covariates but time-independent hazard ratios, all that matters with respect to the probability of an event at a given time is the set of covariate values in place at that time. So if you want to do predictions on new cases for such a model, you simply treat those new cases as you did for those you used to build the model: one separate row representing each different set of covariate values for an individual, indicating the times over which that set of covariate values holds.
That said, be warned that predictions with time-dependent covariates can be tricky, presenting a risk of ending up with survivorship bias. Also, unless you have a very large set of data, your setting aside a completely separate holdout data set presents a risk of having an under-powered model along with too few cases to judge model performance reliably. Validation approaches based on bootstrapping will typically be better with most reasonably sized data sets.


Are the Application life cycles for Windows phone 7 and 8 the same?

Question: Are the Application life cycles for Windows Phone 7 and Windows Phone 8 the same? If not, please guide me to the differences in the application life cycles of both.
Answer: They are the same. MSDN article on app activation and deactivation has a note:

Applies to Windows Phone 8 | Windows Phone OS 7.1


Getting repetitive pattern from multi-step-ahead prediction on timeseries data using LSTM

Question: We are using LSTM to learn sequences on timeseries data. Ask is to do multi-step-ahead predictions using the trained models. We are using a standard multi-layered Sequential model.
The model learns the pattern nicely and can re-play the entire trained data closely.
However, when it comes to doing multi-step-ahead prediction, it seems to fall into some sort of repetitive pattern. (please see the second graph in the Colab notebook)
The idea for doing multi-step-ahead prediction is:

Take timestep_count existing sequence, run predict() on it and get the y_dimension outputs:
Xt-9, Xt-8, Xt-7, Xt-6, Xt-5, Xt-4, Xt-3, Xt-2, Xt-1, Xt ==> Model ==> Pt+1, P t+2,...P t+m

Take the y_dimension predicted values (P) and push them at the end of X.
Xt-7, Xt-6, Xt-5, Xt-4, Xt-3, Xt-2, Xt-1, Xt, Pt+1, Pt+2 ==> Model ==> Pt+3, P t+4,...P t+2+m

Run this new X through the same cycle until we get the future_steps predictions required.

The problem is this technique generates a repetitive pattern as seen in the second graph in colab notebook.
Is this the right approach to do multi-step-ahead prediction?
Other solution is to train the model to give more number of future_predictions. But our requirement is to predict many timesteps in the future and we are not sure if this is the right approach.
Colab link to working sample: https://colab.research.google.com/drive/1ImLBSmM875OouCLoCwh6JeFKFCmwLbby
Please note: The colab notebook has limited training set. In actual production we train on 10000 to 50000 samples and still see the problem.
Answer: After analysing your code, I think the problem is in the way you build the input for the model to test it. You use a different process that involves a different random function.
As another observation... the data you are trying to predict is completely random...no relationship between the inputs and outputs. There must be a way to relate input and output(right?). Otherwise what are you modeling?
I created an alternative dataset and problem formulation to yours. It's related and you can take a look at it here.
Comment: I have updated the question. In production, we train on a much larger data set.
Comment: @CodeRain by repetitive you mean "constantly" increasing?
Comment: yes, either it keeps increasing or it keeps decreasing.
Comment: thanks for the notebook. However am afraid it does not have the "multi-step-ahead" prediction part. I see that your model is predicting 5 future timesteps. But we would like to predict more timesteps and for this we feed the output back into the input and repeat this pattern. And that is when we are seeing the problem.


Any interesting properties of $\sqrt{\sqrt{100x+1}-1}=y$

Question: Are there any interesting properties of: $$\sqrt{\sqrt{100x+1}-1}=y$$
Where $x$ and $y $ are non-negative real intergers.
I'm thinking about what is the digit root? Are there any interesting quirks on divisibility?
Or alternatively (may not be found from previous equation)
$$\sqrt{100x+1}=100a+1$$
Comment: You can write it as $\,100x = y^2(y^2+2)\,$, but it's not clear what you are asking.
Comment: If $100 x = y^2 (y^2 + 2)$ is to be square then one must find values of $y$ such that $y^2 + 2$ is square. It is evident that if $y$ is an integer then this is not possible to be square and leads to $100 x$ in this manor not being square.
Comment: @PintOfMilk `does that mean 100x+1 isn't a square number` No, it means no such thing. On the contrary, $\,100x+1=(y^2+1)^2\,$ is always a square. It does, however, mean that $\,100x\,$ is not a square, as pointed out by Leucippus in a previous comment. Seriously, you should make up your mind on what the question is that you want to ask.
Comment: @dxiv does that mean $100x+1$ isn't a square number?
Comment: Given that say $y\geq10$?
Comment: @leucippus can you prove it?
Comment: @dxiv I apologise
Comment: @PintOfMilk No need to apologize, but the question still needs to be fixed as to make it answerable at all.
Comment: Though if $x=0$ and $y=0$ then they and $100x$ and $100x+1$ and $y^2+1$ are all squares
Comment: @Henry I should have labelled it as a positive note non-negative
Answer: Upon squaring both sides we come up with $$ 100x=y^4 + 2y^2$$
Some integral solutions are found by $y=10k$ and $x= 100k^4+2k^2$ for integer values of $k$.
For example for $k=1$, we get $x=102$ and $y=10$


Why do we need Poincaré inequality to deduce the equivalence of the norms $\|\cdot\|_{H^1_0}$ and $\|\cdot\|_{H^1}$ on $H^1_0(\Omega)$?

Question: In my functional analysis course, my teacher told us that if $\Omega$ is bounded, the two following norms
$$u \mapsto \|\nabla u\|_{L^2(\Omega)} = \|u\|_{H^1_0(\Omega)} \quad \text{and} \quad u \mapsto \|u\|_{L^2(\Omega)} + \|\nabla u\|_{L^2(\Omega)} = \|u\|_{H^1(\Omega)}$$
are equivalent on $H^1_0(\Omega)$ thanks to Poincaré inequality. However, the other day I was reading a corollary of the open mapping theorem that states the following:

Let $E, F$ be two Banach spaces and $T$ be linear, continuous and bijective from $E$ to $F$. Then $T^{-1}$ is continuous from $F$ to $E$.

From this we easily deduce that if $\|\cdot\|_1, \|\cdot\|_2$ are two norms on a Banach space $E$ such that there exists $C> 0$ with
$$\|x\|_1\le C \|x\|_2, \quad \forall x \in E,$$
then there exists $c > 0$ with
$$\|x\|_2\le c \|x\|_1, \quad \forall x \in E,$$
and the two norms are equivalent.
In our case, clearly
$$\|u\|_{H^1_0(\Omega)} \le \|u\|_{H^1(\Omega)},$$
on $H^1_0(\Omega)$ whatever is $\Omega$ (no need to be bounded). Therefore, why do we need Poincaré inequality (and hence $\Omega$ bounded) to deduce the equivalence of the norms ? Isn't it  straightforward by the corollary above ?
Comment: It is important that $E$ is a Banach space in both norms for your corollary. So you'd have to prove that $H^1_0(\Omega)$ is complete with respect to $u\mapsto \lVert{\nabla u}\rVert_2$.
Comment: In case $\Omega = \mathbb R^n$, $u \mapsto \|\nabla u\|_2$ is not even a norm on $H_0^1(\Omega) = H^1(\Omega)$.
Comment: And it is not possible without $\Omega$ bounded?
Comment: Awesome question!
Answer: As mentioned in the comments, you would have to show that $H^{1}_{0}(\Omega)$ with this new norm is a Banach space to apply this argument. Note however that it is not necessary that $\Omega$ is bounded for the Poincaré inequality to hold:
If $\Omega \subset \mathbb{R}^n$ and there exists some $j \in \{1,...,n\}$ and $M>0$ such that $\forall x \in \Omega$ we have $|x_j| \le M$ then there is some $C$ such that
$$\|u\|_{H^{1}_{0}(\Omega)} \le \|\nabla u\|_{L^2(\Omega)}$$
for all $u \in H^{1}_{0}(\Omega)$ and thus the two norms are equivalent.
A proof can be found here - note that it is sufficient to prove the statement for the dense subset of smooth functions with compact support in $\Omega$.
If $\Omega$ is even bounded then by the Rellich-Kondrachov theorem $H^{1}_{0}(\Omega)$ is compactly embedded in $L^{2}(\Omega)$, which immediately gives equivalency of the two norms.


MongoDB - Database Profiler does not capture queries sent to secondaries replicas

Question: I'm new to MongoDB and need some help to understand how profiler works with replication in Mongo.
I have a replica set with three instances and the secondaries are used for read only by the application. When I try to profile by connecting to the cluster it only returns commands issued on the primary.
How can I get all commands, especially the ones which were executed on the secondaries replica set?
Answer: I found out the answer in the documentation:

You can enable and configure profiling for individual databases or for all databases on a mongod instance. Profiler settings affect only a single mongod instance and will not propagate across a replica set or sharded cluster.


GPOs are on users gpresult but not updating settings

Question: I have the GPOs setup correctly for WSUS and even just adding a favorite in IE but none of these are working. Is there another setting somewhere I'm missing to get these things to force? Windows Server 2008 and all clients are Windows 7.
Comment: How have you configured the GPOs?  Linked to an applicable OU containing the users? Or the computers?  Security filtering?  WMI filtering?  What's the resultant set of policy tool say?
Comment: I have configured the GPO's.  Linked them to my OU that all of my domain users are in.  Security filtering just has authenticated users.
Comment: The IE Favorite one was applied but the WSUS settings were not
Answer: Your WSUS policy is not being applied because WSUS policies are computer configuration.  The GPO that contains those settings must be linked to an OU which contains the relevant computer objects.
Comment: @Intelwalk Your comment makes no sense. As Shane has explained, your COMPUTER objects need to be in the same OU that has the GPO applied, if you want the computer settings to be applied. You stated in your comment to your question that you applied the policy to your USER OU. Computer settings apply to computer accounts. User settings apply to user accounts. See also [loopback processing](http://support.microsoft.com/kb/231287).
Comment: GEEZ  I have no idea why the computers are not in GPO
Answer: On the clients run:

gpupdate /force /sync /boot

Then on the client run

gpresult > c:\gpresult.txt

Review the result and confirm if the newly created GPO is correctly being applied. As Shane mentioned, you can also run the resultant set of policy tool from the DC.
Comment: The IE Favorite one was applied but the WSUS settings were not.
Comment: +1 for resultant set of policy from group policy management. This is always my first port of call when diagnosing group policy issues.


How to block an IP using iptables

Question: So this should be a simple issue, but for whatever reason I can't figure it out.
Here are my current rules:
<code>Chain INPUT (policy ACCEPT)
target     prot opt source               destination
block      all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination
block      all  --  anywhere             anywhere

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination
block      all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere

Chain block (3 references)
target     prot opt source               destination
DROP       all  --  hit-nxdomain.opendns.com  anywhere
</code>
I'm trying to block the "hit-nxdomain.opendns.com" location (dummy location).  When I put in a real IP address can I can use from another location.  If I try to hit my server from that location it still connects just fine.  How can I get it to drop all requests from that IP address?
I'm using a chain because I will be dynamically modifying the blocked ip address(es) using a script, so I need to be able to clear out just the block chain without breaking the INPUT chain and add in new addresses. Can you show me what I'm doing wrong with it the way it currently is? As I said, the "hit-nxdomain.opendns.com" is just a dummy name. But if I have a valid IP there it's not blocking it.
Comment: @Psiclopz - just FYI, your additional post was deleted because it was a non-answer posted in the "answers" section. In the future, just edit the post and add additional information there.
Answer: Get the IP of that hostname:
<code>$ host hit-nxdomain.opendns.com
hit-nxdomain.opendns.com has address 184.108.40.206
</code>
Block it:
<code>$ iptables -I INPUT -s 188.8.131.52 -j DROP
</code>
Comment: Or put another way, ipchains will happily let you set a rule using a hostname, but doesn't work without using an IP address/subnet.
Answer: I don't see a problem with the rules.
To block an IP address, you use
<code>   # iptables -A INPUT -s 127.0.0.100 -j DROP
</code>
If you are still able to connect from that IP address, then check with tcpdump, if you are actually connecting with that IP, or if for some reason (Proxy, VPN, ...) you are visible on the host with the iptables rules as another IP address.

How to block an IP using iptables