How to try-catch a RPC call to an offline RPC server?

Question: I'm searching for hours how to proceed if we make a RPC call to a server who is online but who don't run the RPC server.
The only thing i'm doing in my code is to ping our failover IP address to check if the server is runnning, but if i make a RPC call with my C# application, it's crash.
The RPC Call function :
public string Call(string message)
{
    var corrId = Guid.NewGuid().ToString();
    var props = channel.CreateBasicProperties();
    props.ReplyTo = replyQueueName;
    props.CorrelationId = corrId;

    var messageBytes = Encoding.UTF8.GetBytes(message);
    channel.BasicPublish(exchange: "", routingKey: "rpc_queue", basicProperties: props, body: messageBytes);

    while(true)
    {
        var ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue();
        if(ea.BasicProperties.CorrelationId == corrId)
        {
            return Encoding.UTF8.GetString(ea.Body);
        }
    }
}

Does anyone have a solution ?

PS : RabbitMQ confesses to don't solve these following problems :
Our code is still pretty simplistic and doesn't try to solve more complex (but important) problems, like:
How should the client react if there are no servers running?
Should a client have some kind of timeout for the RPC?

Thanks.
Comment: Have you read about Paxos Fault Tolerant Algorithm? If not, please go through it.
Comment: Sorry ... edited ! I read Paxos but it looks complicated :)
Answer: For those who have this problem, I solved this like :
try
{
    var task = Task.Run(() => rpcClient.Call(data_encoded));
    if (task.Wait(TimeSpan.FromSeconds(3)))
    {
        response = task.Result;
    }
    else
    {
        throw new Exception("Timed out");
    }
    Console.WriteLine("RESPONSE : " + response);
}
catch (Exception e)
{
    // Some code here ...
}

Answer: I am new to RabbitMQ and RPC, but am using the following check to see if the server is alive before making an RPC call from my client:
private bool IsRpcServerAlive()
{
   // create a temporary channel since it will not be
   // reusable if an exception is thrown
   using (var tempChannel = connection.CreateModel())
   {
      try
      {
         // throws an exception if the Queue does not exist
         var declareResult = channel.QueueDeclarePassive("rpc_queue");
         // RPC server is the only consumer of the Queue
         return declareResult.ConsumerCount > 0;
      }
      catch (RabbitMQ.Client.Exceptions.OperationInterruptedException)
      {
         return false;
      }
   }
}

This works for me as my server is the only consumer of the Queue. For more information on passive declaration see https://www.rabbitmq.com/dotnet-api-guide.html#passive-declaration


Is it true that "there's no wrong in music"

Question: In the following question…
Why do some of the chord choices in measures 18 through 20 of "Study #1 William Leavitt - Melodic Rhythms For Guitar" sound... "wrong"?
…a pupil says to their teacher that something sounds wrong. And the teacher responds by saying "there's no wrong in music".
Is the teacher correct?
Comment: You play me a nice chord sequence in C maj & i'll sing along with it in C♯. See how long you last ;) Also see Les Dawson - https://www.youtube.com/watch?v=9nNGlaiVypU also a much longer one at https://www.youtube.com/watch?v=LQ0G2Z8k1Gg He was actually a consummate pianist, but he knew just exactly which would be the *worst* notes in any given situation.
Comment: It depends on your definition of "wrong" (and also on your definition of "music"). VTC as opinion-based
Comment: Note that even when people agree that there's no "wrong" in music, there can absolutely be "wrong" in music *school*, so whatever you believe after you get an answer to this question, keep in mind that you can still get bad grades in a music class.
Comment: @MichaelCurtis Yes, this present question, besides dealing in vague terms with broad concepts, seems to deliberately misunderstand the misunderstanding. It seems the student suggested to the teacher that the composer had done something "wrong," when in fact the performer had incorrectly executed what was written. The abstruse argument about "no wrong in [music]" makes sense only when discussing creative output ("no wrong in [composing, improvising, etc.]"). Of course there is such a thing as errors in reading, and to induct them into an abstruse argument about aesthetics is sophistry.
Comment: @Tetsujin - It's actually not that easy to play proper Dawson style. I've tried many times. As far as C/C# goes, my party piece is r.h. key C, l.h. key C#, which isn't too easy. Great when trying out a used piano to buy...
Comment: This question would be perfect for the chat room, since it's more a discussion topic than a question that can be answered factually.
Comment: I don't understand the basis of this question when it links to another post with answer explaining the performance in question _includes a performance mistake._ The "wrong" is playing the music not as notated, which isn't a matter right/wrong in the sense of aesthetics.
Answer: Yes, and no. The teacher shouldn't respond with a glib "there's no wrong in music", if they're a good teacher. It may depend on the level of the student, but at any level, a far better answer should be forthcoming. "It sounds wrong because...", or "You could say it's wrong because..." would be the way I'd answer, at whatever appropriate level of musicality and understanding.
I would encourage students to ask 'demanding' and 'awkward' questions, which would either be answered directly (even though it may take us off track), or find an answer for next lesson. If they had the interest to ask the question, surely I, as teacher, should have the interest/experience to respond in a way that was palatable.
However, some students aren't ready for more of a stock answer than that - albeit few and far between. And some teachers just don't know, or care enough. Or can encapsulate the answer in a comprehensible way. So, far more incorrect than correct.
Answer: It largely depends on the musical genre one is dealing with.
A sequence of melody notes may sound very 'off' in one genre but perfectly fine in another genre. The same applies to types of harmonies, chords, and chordal sequences. What may be typical in one genre (e.g. heavy rock) will probably sound very wrong in another genre (e.g. classical music).
Some genres, though, will lend themselves to fusing with others. So, you get hybrid genres whose individual genre rules don't clash and sound very wrong. (Country rock is an example.) Gospel or Blues will fuse and not sound wrong if mixed with the typical note/chord patterns of rock. But, I can't imagine Hip Hop sounding right blended with other genres, though you sometimes hear small sections of just hip hop spoken in parts of some pop songs.
What makes a piece of music sound wrong is if you break some of the essential rules that define its genre (eg the distinctive 12 bar, 8 bar etc blues chord sequence), or if you start to try and make very rhythmic hip hop with no melody, minimal instrumentation,  and heavy emphasis on clear, sharp diction to sound sweet and melodic. It just won't work.
But, oddly enough, some heavy rock/pop can sound OK given a classical interpretation/style. I have even heard some interesting heavy metal renditions of intensely profound religious music. Not surprising, since much metal genre music is preoccupied with death and spiritual stuff. Some classical music also sounded interesting, given a quietened down heavy metal treatment.
A person with an open mind might be able to appreciate this, but most classical musicians would be outraged and--surprise, surprise--if you asked some heavy metal bands to give you their rendition of a classical piece, they wouldn't have a bar of it. But the more creative, innovative ones might find it interesting to experiment, try something new, and see how it sounds.
I once watched such a metal band experimenting with various classical composers and, interestingly, the Germanic composers could be adapted to sound reasonable played as heavy metal/rock, or even deep wailing blues. But, the Latin composers (e.g. Italian) sounded very wrong given a metal treatment, though fine given a jazz or pop feeling. Spanish stuff sounded OK given a rock treatment, and some sad, wailing flamenco tunes sounded good given a blues interpretation.
It was great fun doing all this experimentation. I guess what's right or wrong depends on the genre and whether your ears like the sound waves produced or not.
Answer: I play a fixed pitch instrument (concertina). I sometimes have the experience of playing with a violin player who has very dubious tuning, sometimes a quarter tone or more flat and increasingly flatter as they move further down the neck from (the already out-of-tune) open string.
That is wrong. There's no room for nonsense about temperament or 'violin tuning', just wrong. Rather like the teacher in the OP.


Tool for viewing structural xib differences?

Question: Is there a diff tool for viewing differences in XIB's? It could display what graphical elements are in one xib while missing in other?
Answer: XIB files are regular XML files. You can diff them using your favorite diff tool.
Comment: my favorite diff tool shows only textual, but not visual differences. After all - each element has it's own unique ID which means that EVERY element will be different from it's counterpart in other document.
Comment: Yeah, I know, that is a problem. I have never seen a visual tool for diffing XIB files. :-(
Comment: There's no way to determine equality or differences between two files with different IDs in them. In the case of three or more windows (for example) between the xibs, how would you know which two windows to compare?
Comment: comparison should be done on two windows. and i think it should be more of a hierarchical differences (views -> subviews recursion) thingie.
Answer: There isn't a tool that will do this visually. Only textual comparison is currently possible (diff, FileMerge, etc.) which is still a big advantage over the older nib format.
Answer: You can filter both through nib2objc (http://github.com/akosma/nib2objc) and then compare the results. It will then show you the differences in code.
Comment: Seems like a good idea, but it crashed when processing one of my xib files. Your mileage may vary.


how to convert a propositional logical tree into conjunction normal form (CNF) tree

Question: I have a string like string
     s="(=> P (OR (AND A (NOT B)) (AND B (NOT A))))";

and convert it output the CNF of this string,like
( OR ( NOT P ) ( OR A B ) )
( OR ( NOT P ) ( OR ( NOT B ) ( NOT A ) ) )
do I need to make a struct TreeNode to keep the value?
     struct TreeNode {
            string val;         // The data in this node.
            TreeNode *left;   // Pointer to the left subtree.
            TreeNode *right;  // Pointer to the right subtree.
            //TreeNode *farther;//should I use farther or not in convert to CNF?
      };

how to make it to CNF, which is conjunctive normal form?
please give some algorithm detail.
from my point of view, maybe use recursive function is better for solving this problem, but I still can not think out how to use recursion. Or you have other suggestion for solving this problem?
Comment: @Rebecca No prob. Like Jim Balter said, remember to use proper spelling and punctuation and edit the question if it seems vague for the community. That makes the interaction with the other users much more efficient. Also remember to use the accept answer feature in the correct manner - use it when an answer solves your question; until it does, don't accept an aswer and don't ask the same question in a new post. Instead, ask for clarification under the answer. Netiquette aside, what I think would best help you right now would be to leave your problem at hand aside and instead try to find some
Comment: (@Rebecca cont'd:) introduction texts about grammars and grammar parsing. Preferably those, that provide exercises, which ask the reader to code a simple parser. You can ask for help with those exercises on StackOverflow if you get stuck. Completing the exercises should help you understand how you can code the convertion of your proposition string into a tree, what fields do you need to define in the tree node's struct etc.
Comment: Please do you own work. When you get stuck, ask a specific question. But here's a hint: "recursive descent parser". Another hint: What's the first thing that the program needs to do?
Comment: I just want to know some algorithm and learn something from it, so that I can do my own work, I do not want someone to post source code for me.  I do do really hard find useful information and still can not figure out, that's why I ask question here, am I wrong?
Comment: In the time you wrote that, you could have googled "recursive descent parser" and been long on your way.
Comment: Rebecca, I've already posted an answer that should easily lead you to a complete program.
Comment: @AdrianPanasiuk Hmmm .. actually the OP has asked two quite different questions ... we have each answered one of them. I'm voting to close as the headline only matches the second question.
Comment: I think she asked the other question. Maybe her english is not perfect, but the post seems to be: "I have a string input that looks like s, now I have converted it to a tree like this and my implementation includes the following structure type definition. What is the general idea behind normalizing propositions I will later on apply to my representation?"
Comment: @Rebecca, care to clarify your question?
Comment: @AdrianPanasiuk Ah, I see. I took "I have convert it" as "I have to convert it" whereas apparently she meant "I have converted it". I do wish that people who come here for help and wouldn't be so sloppy and lazy with their questions ... it's not helpful. And when I wrote about recursive descent parsers, why didn't she say she had already done that? And she didn't say what `farther` is supposed to be or why she thinks it might be needed.
Comment: @AdrianPanasiuk Actually, I wasn't wrong ... see the OP's comment on my question.
Comment: @JimBalter Heh yeah, and I also found this http://stackoverflow.com/questions/16088344/how-to-convert-a-logic-expression-in-to-a-prefix-tree and http://stackoverflow.com/questions/16073637/temporary-pointer-point-to-a-using-vector-address , so she divided the problem into small questions, but I agree there's some carelessness to how she formulates questions and reacts to answers.
Comment: @AdrianPanasiuk ,sorry for the confusion, actually My english is not very good, and as well as my algorithm, thanks for your answer very much!
Comment: "sorry for the confusion" -- how about eliminating it by providing the requested clarification.
Comment: @JimBalter sorry for the confusion, I just want to get some help, as  my english is not very good, sometimes, I can not get the idea of others answer
Comment: Rebecca, you have asked the same question many times, can't formulate it properly, and can't comprehend the answers. You are abusing SO ... please stop. If you need that much help, get a tutor.
Answer: Let's say you name your function CNF, taking a tree and returning the tree in CNF.

First, replace equivalency p<=>q with AND(p=>q,q=>p) then replace implications p=>q with OR(q,NOT(p)).
Convert to negation normal form: move all NOT operations down the tree, so that the NOT operations bind only to atoms (A, B).
Then, the result of CNF(AND(x,y)) is simple: AND(CNF(x),CNF(y)), as it is CNF-like to have ANDs high in the tree.
The result of CNF(OR(AND(x,y),z)) is a little bit more complicated. Here we will use the rule of distribution of disjunction over conjunction, which is OR(AND(x,y),z) is equivalent to AND(OR(x,z),OR(y,z)). In effect, CNF(OR(AND(x,y),z)) will be AND(OR(CNF(x),CNF(z)),OR(CNF(y),CNF(z)).

And you're done.
Comment: @Wyvern666 Try treating `AND` and `OR` as n-ary instead of binary -- so `a&b&c|d` becomes `OR(AND(a,b,c),d)` instead of `OR(AND(a,AND(b,c)),d)`.
Comment: so you algorithm is recursion or not? what about the imply (=>) in the bottom, X=>Y CNF:not x and Y, if the string is very long, things will be very complicated and a huge work
Comment: @Rebecca Adrian addressed implications. Yes, it's recursive ... any tree traversal is. Do you see "AND(CNF(x),CNF(y))", for instance? That's a recursive call of CNF. It's not all that much work for an experienced programmer. If you're not one, maybe you should start with a simpler problem.
Comment: @Rebecca The algorithm's output will be exponential in terms of the size of the input in some cases, for example for `OR(AND(x_1,y_1),AND(x_2,y_2),...AND(x_n,y_n))` the result will be the conjunction of all clauses of the form `OR(z_1, z_2, ..., z_n)` with each `Z_i` being `X_i` or `Y_i`.
Comment: @AdrianPanasiuk Im using the same approach you mentioned. But is possible to apply all the distributive laws in one traversal over the tree?. Mi problem is that something like a&b&c|d converts to ((a|d)&((b&c)|d)), so i have to do two traversals to have the desired: ((a|d)&((b|d)&(c|d))). Is that im doing something wrong or this is expected?
Answer: Simple recursive descent parser solution:
TreeNode* ParseExpression(const char*& p): If the string pointed to by p does not start with '(' then return ParseAtom(p), else move p past the '(', call ParseOperation(p), then move p past the ')' and return the value returned by ParseOperation.
TreeNode* ParseAtom(const char*& p): skip p past the atom (contiguous series of non-spaces). Return a TreeNode with the atom as value and NULL left and right.
TreeNode* ParseOperation(const char*& p): The string pointed to by p should start with an operator. Move p past the operator, then determine how many operands the operator takes. If one, Call ParseExpression(p) once; if two, call ParseExpression(p) twice. Then return a TreeNode with the operator as value and the results of the one or two ParseExpression calls as left and right (right should be NULL for an operator with only one operand).
Set a pointer pointing to the original string; call ParseExpression on that pointer; the return value is your tree and the pointer will point past the first expression in your string.
This addresses one of your questions: how to turn a string into a tree. Adrian Panasiuk addressed the other question, how to convert a tree to normal form. Since you're going to be doing additional tree transformations, "value" in your nodes should be called "op" or something like that to stand for "operator" (which is a reserved word in C++), and it should be an enum, not a string.
Comment: @Rebecca Of course there's a need to convert the string to a tree, and I just told you how.
Comment: so actually, there is no need to convert the string in a tree, which will make things complicated, right? would it be possible that I can use something like substr() and find() and strcpy() to make it into CNF?
Comment: Why would someone downvote this without explanation 8 years after it was posted?


Give an example of subsets $A$ and $B$ of $\mathbb{R}$ such that all three of the following conditions hold.

Question: (a) Neither A nor B is open;
(b) $A \cap B = \emptyset$;
(c) $A \cup B$ is open.
I've considered $A = (0,1] $ and $B=(1,2]$, and $A = (0,1] $ and $B=[1,2)$, but neither possible subset pairs satisfy all three conditions. Is this even possible?
Maybe it is possible if we consider infinite union subsets for $A$ and $B$. As in,
$A=\bigcup\limits_{n=0}^{\infty}(2n, 2n+1]$ and $B=\bigcup\limits_{n=0}^{\infty}(2n+1, 2n+2]$
so that $A \cup B = (0, \infty)$ which is open.
Comment: $A=\Bbb Q$ and $B=\Bbb R\setminus\Bbb Q$
Comment: @azif00, https://www.youtube.com/watch?v=BOEYSLlQy9s
Answer: A very basic strategy could take two disjoint open intervals, and have them each "trade ownership" of a point from their interiors.
So, for example,
$$A = (0,1){\setminus}\{1/2\} \cup \{5/2\}$$
$$B = (2,3){\setminus}\{5/2\} \cup \{1/2\}$$
Comment: Wait, nevermind, I see that B is now a union of two open sets and is thus open. You do need to swap two isolated points. And this also answers my concern about including $\{1\}$ because we have $A \cup B = (0,1) \cup (1,2)$ which is open.
Comment: Wouldn't you want to include $\{1\}$ though? And is it necessary to swap two points? I think the following works: $$A = (0,1]\cup \{3/2\}$$

$$B = (1,2){\setminus}\{3/2\}$$.
Comment: I know you figured it out, but i thought it might be easier to see what's happening if the intervals don't abut each other, so I modified it.
Comment: In the version of your first comment you could also have left $\{1\}$ in $A$, but still swapped two points, and had a valid example that unioned up into a single interval, but I like the symmetric roles of $A$ and $B$ in my version.
Answer: Take any $A \subset \mathbb R$ which is neither open nor closed and define $B = \mathbb R  \setminus A$.
Let us observe that we cannot find any two intervals $A, B$ with the desired properties.
Assume $A, B$ are intervals with these properties. Then each of  $A, B$ must be either a (bounded) closed interval or a half-open interval.
Let $A$ be an interval boundary point of $A$. W.l.o.g. we may assume that it is the right interval boundary point (the other case can be treated similarly). In order that $a$ becomes an interior point of $A \cup B$, we must have $B = (a,b]$ with $b > a$. Note that $B$ cannot contain $a$ and cannot be open. But then $b$ is the right boundary point of the interval $A \cup B$, thus $A \cup B$ is not open.


Get Fields of a custom Content Type from Database in Drupal 7

Question: I'm trying to get custom fields of my custom content-type "slideshow". I've chosen to get the fields from template (.tpl.php) file for some reasons (mainly because I've to write lots of formatting HTMLs and modifying lots of template files did not sound good).
So far, What I've got is individual nodes:
$result = db_query_range('SELECT n.nid
                      FROM {node} n WHERE n.type = :ntype', 0, 10, array(':ntype' => 'slideshow'));
foreach ($result as $record) {
    $node = node_load($record->nid);
    // Got $node! What to do now????
}

The code works & I've got nodes in $node. Now What to do to get individual custom fields & work with the raw data of these fields? Please help.
PS I've tried Get content type with PHP from database but the code does not work... guess it's for older Drupal versions.
Answer: You could always try field_get_items if you know the names of the fields you want. field_get_items('node', $node, 'field_name');
Although node_load() should be providing the fields for you and can be found at $node->field_name
Also Attiks advice is sound, I would also not recommend doing this in tpl
Answer: First a bit of advise, take it or leave it: but don't do this in the tpl.php files, try to use some preprocessing hooks.
To see what fields are available on your $node, add a print_r($node) after the node_load, it will show you everything that's defined on the $node.
If you want total control over your display without writing lots of template files have a look at Display suite and custom_formatters
Comment: Thanks - I almost forgot about doing this within preprocessor!
Answer: Attiks is right!
first use  print_r($node), or var_dump($node). if you view the source of the page where the info is printed it will probably display in a readable form.
Use the following format or similar (depending on what you need) to get your data:
$node->field_my_cck_field['und'][0]['value']

Comment: Thanks. What does 'und' stand for? I've seen it in many places.
Comment: Language neutral uses the language code 'und', which means undefined and is specified to be used for such cases by the ISO 639 standard. You'll see this language code in Drupal source code all around, so good to know. (see http://hojtsy.hu/blog/2011-jan-31/drupal-7039s-new-multilingual-systems-part-4-node-translation)
Comment: it stands for language (undefined in this case...)
Answer: To get a list of fields for a node content type in Drupal 7, try the field_info_instances function. Here is an example usage that will retrieve all the fields for a custom node content type:
$my_fields = field_info_instances("node", "my_custom_content_type");

Answer: Use this function to get an array of content type with its fields
 function get_content_fields_array() {

$list = node_type_get_names(); //get the list of content types
$contenttypes = array();
$type_count =0;
foreach ($list as $key => $value) {
    $field_list = field_info_instances('node', $key); //get field list for content type
    $field_count =0;
    $field_max = count($field_list);
    foreach ($field_list as $field_key => $field_value) {
        if($field_count == 0) {
            $contenttypes [$type_count]['label'] = $value;
            $contenttypes [$type_count]['machine_name'] = $key;
        }
        $contenttypes [$type_count]['fields'][$file_field_count]['machine_name'] = $field_key;
        $contenttypes [$type_count]['fields'][$file_field_count]['field'] =  $field_value;

        if($field_count == ($field_max -1)) {
                $type_count ++;
        }
        $field_count++;
    }
}

 return $contenttypes;
}


How to convert HTML framesets / frames to iframes in a PHP setting - 2020 scenario and solution

Question: Much expert advice has been read here on this topic. Though, sometimes this was very general and did not incorporate the suggestion not to use Bootstrap's or Flexbox' solutions to this dilemma.
For all those of you who have a "historic" HTML frameset with several frames I would like to show you the way how I did this transformation from the original PHP code files. Being very grateful for all the professional advice I personally had been able to collect on stack overflow, I would like to return something here.
The basic layout structure is like this:
    +---------------------------------------------------------+
    | (1)                                                     |
    +---------------------------------------------------------+
    | (2)                                                     |
    +---------------------------------------------------------+
    | (3) |                 frameBody                   | (4) |
    |     |                                             |     |
    |     |                                             |     |
    |     |                                             |     |
    |     |                                             |     |
    |     |                                             |     |
    |     |                                             |     |
    |     |                                             |     |
    +---------------------------------------------------------+
    | (5)                                                     |
    +---------------------------------------------------------+

Legend:
(1) - headerTitle; (2) - frameMenu; (3) - userMenu; (4) - patientMenu; (5) - footerTitle.
After having logged in successfully from login.php, I am being forwarded to site.php which takes over the steering of the entire website. In this file, all the conditions for switching from conditions to conditions and, thus, to corresponding other PHP files is managed.
site.php, however, also takes care of the principal layout of the website, here in the old frameset / frame / noframes way (please excuse the lengthiness of the code example, but I want to show you how nicely short and well-structured an iframe solution can be):
    <?php
        // Lots of definitions and introductory stuff, not relevant here
    ?>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <meta http-equiv="content-type" content="text/html; charset=<?= strtolower($CHARSET) ?>" />
        <meta name="author" content="whoever" />
        <meta name="date" content="<?= date('r', filectime($_SERVER['SCRIPT_FILENAME'])) ?>" />
    <title><?= $sCompanyName ?></title>

    <frameset name="alles" cols="20,*,20" framespacing="0" frameborder="0" border="0" />
        <frameset rows="20,50,120,*,40,20" framespacing="0" frameborder="0" border="0" />
            <frame name="headerTitle" src="frameHeader.php" scrolling="no" noresize="noresize" />
            <frame name="frameMenu" src="frameMenu.php" scrolling="no" noresize="noresize" />

    <?php
        if (isset($_REQUEST['sBody']) && $_REQUEST['sBody'] == 'login')
        echo '<frame name="frameBody" src="login.php' . $sLanguageString . '">';
        else {
    ?>

            <frameset name="Frame1" cols="225,1,*,1,225" framespacing="0" frameborder="0" border="0">
                <frame name="userMenu" id="userMenu" src="userMenu.php" />
                <frame name="frameBody" src="<?= $sBody . (strlen($sURLParameterString) > 1 ? $sURLParameterString : '') ?>" />
                <frame name="patientMenu" id="patientMenu" src="patientMenu.php"/>
            </frameset>
            <frame name="footerTitle" src="frameFooter.php" scrolling="no" noresize="noresize" />
        </frameset>

    <?php
        }
    ?>

        <noframes>

    <?php
        setSysMsg($oSysMsg->getExpression('general', 'noFrameSupport', 'This site is based on frames. But your browser doesn\'t support frames.
Your should choose another internet browser.'));
        echo getLastSysMsg();
    ?>

        </noframes>
    </frameset>

What are the obstacles now for an easy conversion?
Answer: They all refer to my style of working only (apart from other professional skills you can read about in my profile I have developed large documentation and data analysis suites [WAMP, LAMP, MAMP] for handling special types of medical documentation), but if you find yourself in a similar timely condition, this situation may be similar to your own mindset:
Obstacle #1:
Ready-made solutions for the implementation of grids such as Bootstrap or Flexbox can be done as well, but using their CSS and JS files often needs a lot of individual adaptation if you want to have sizes, shapes, and colours your way.
Obstacle #2:
I personally prefer to experiment in a small, easy to conceive setting before embedding my solution into a bigger structure such as Bootstrap and Flexbox (and possibly others, too).
Obstacle #3:
I simply do not have the time to sit in front of the screen for hours and hours to check out some layout stuff when I dearly need to get data analyses and evaluations done.
Thus, after experimenting with WampServer on my localhost, I have found the following solution:
    <?php
        // Same lots of definitions and introductory stuff, again not relevant here
    ?>

    <!DOCTYPE html>

        <meta http-equiv="content-type" content="text/html; charset=<?= strtolower($CHARSET) ?>" />
        <meta name="date" content="<?= date('r', filectime($_SERVER['SCRIPT_FILENAME'])) ?>" />
        <title><?= $sCompanyName ?></title>

    <?php
        if (isset($_REQUEST['sBody']) && $_REQUEST['sBody'] == 'login')
        echo '';
        else {
    ?>

        <iframe style="top:160px; left:225px; width:100%; height:100%; border:2px blue; background-color:lightgrey; display:inline-block; position:fixed;" id="frameBody" name="frameBody" scrolling="yes" frameborder="1" marginheight="0px" marginwidth="0px" src="<?= $sBody . (strlen($sURLParameterString) > 1 ? $sURLParameterString : '') ?>" allowfullscreen />

    <?php
        }
    ?>

Please mind that, of course, it is a good if not essential step to cast the style="whatever" statements into an external CSS file, but this is not necessary here to show you what I mean.
It is important not to change the name="something" statements from frames to iframes as they are needed for the referral of, for instance, a menu link referring to the above-mentioned code with frameBody (see there):
    [... preceding code ...]

Do this

Do that

Do something completely different

    [... further code ...]

The allowfullscreen is just an optional element in case one of these iframes should be made fullscreen using an appropriate javascript code (not supplied here).
And, finally, the change of both <!DOCTYPE ...> and  corresponds to being able to make use of HTML 5 instead of the older HTML 4 declaration which had to refer to a DTD (Document Type Definition).
I hope this bit of code helps in a generic way to root from HTML framesets to HTML iframes on the way to a frameless solution as next possible step.


Definition of an ultra pre-filter

Question: I have come across the term "ultra prefilter" which has two possible definitions (that I can think of).  I tried googling this first I swear! (but google thinks I'm looking for filtered water or a water purifier)
The two most obvious meanings to assign to an ultra prefilter $F$ on a space $X$

$F$ is a prefilter on $X$ which is not properly contained in any other prefilter on $X$
$F$ is a prefilter on $X$ which is equivalent to any of its refinements

The first one is simply the definition of an ultra filter applied to a prefilter instead.  However the second one seems more appropriate, but I wanted to confirm it before I trust it too deeply.
Answer: An ultra prefilter is a prefilter, such that all supersets of the prefilter form an ultrafilter. That is, it is a filter base of an ultrafilter. You can take a look at 5.2. in Pete L. Clark's notes on convergence.
Comment: @Kyle: That was a typo. They are supposed to form an *ultra*filter. The terminology is not standard. The definition of a prefilter comes right after Proposition 5.5. on page 19. The conventions for how to relate filter-concepts and prefilter-concepts is on page 20.
Comment: Those are indeed the notes I am working through, but I couldn't find a definition for ultra prefilter.  As for your answer, I understand everything after the "That is," part.  But before that, can you clarify exactly what needs to form a filter?  The set of all supersets of sets *in* the prefilter *always* forms a filter I think.
Comment: It's funny, I know exactly what paragraph you are referring to when you mention the "conventions", I remember the paragraph exactly, yet I didn't make the connection.....

Thanks for the answer!

Definition of an ultra pre-filter


Sweep Views left-right

Question: We've got an application planned that is a very basic 7 page presetation. Our client wants to be able to sweep the views from right to left as a form of navigation, similar to the page control on the home screen.
I understand the presentModalViewController and pushViewController, but how do I detect a directional finger sweep?
Answer: You can use UIScrollView horizontal paging. An Apple's sample code here
Comment: Just to add to this - take a look at the WWDC 104 video in iTunes U too, very good.
Comment: I can't find the video you have recommended danny, I've done a search but all I can find is podcasts, nothing on iTunes U
Comment: to find the videos, go to developer.apple.com, login. there u find them and u will be redirected to iTunes U.
Answer: See UIScrollView, and its pagingEnabled property. UIKit does almost all of the work for you.

Sweep Views left-right


How to widen a dataframe - pandas

Question: Basically i want to just flatten ( maybe not good term )
for example having dataframe:
    A      B            C
0   1  [1,2]      [1, 10]
1   2  [2, 14]    [2, 18]

I want to get the output of:
    A  B1   B2    B3   B4
0   1  1    2     1    10
1   2  2    14    2    18

I've tried:
print(pd.DataFrame(df.values.flatten().tolist(), columns=['%sG'%i for i in range(6)], index=df.index))

But nothing good.
Hope you get what i mean :)
Comment: is the layout always the same? meaning there is a list with 2 values in B and the same for C?
Comment: @Cut7er Oh sorry but i just wanted to make the data shorter and forgot to update code, thanks for reminding me
Answer: General solution working also if lists have differents lengths:
df1 = pd.DataFrame(df['B'].values.tolist())
df2 = pd.DataFrame(df['C'].values.tolist())

df = pd.concat([df[['A']], df1, df2], axis=1)
df.columns = [df.columns[0]] + [f'B{i+1}' for i in range(len(df.columns)-1)]
print (df)
   A  B1  B2  B3  B4
0  1   1   2   1  10
1  2   2  14   2  18

If same size:
df1 = pd.DataFrame(np.array(df[['B','C']].values.tolist()).reshape(len(df),-1))
df1.columns = [f'B{i+1}' for i in range(len(df1.columns))]
df1.insert(0, 'A', df['A'])
print (df1)
   A  B1  B2  B3  B4
0  1   1   2   1  10
1  2   2  14   2  18

Answer: In more recent versions you can use explode:
>>> x = df.select_dtypes(exclude=list).join(df.select_dtypes(list).apply(pd.Series.explode, axis=1))
>>> x.columns = x.columns + x.columns.to_series().groupby(level=0).cumcount().add(1).astype(str)
>>> x
   A1  B1  B2  C1  C2
0   1   1   2   1  10
1   2   2  14   2  18
>>>

How to widen a dataframe - pandas


Servlet recuperar Objeto

Question: É possível uma servlet recuperar objeto populado no requestParameter?
Tipo vindo do Javascript?
req.getParameter("objeto");

Tenho o objeto Pessoa que possui
Nome
Telefone
no Javascript eu enviar
var obj = {nome: 'Carlos', telefone: '929999999'}

Como recuperar esse objeto populado no Servlet invés de String
Obj obj = req.getParameter("obj");

Comment: Poderia melhorar sua pergunta?
Não da pra entender o que você deseja atingir.
Comment: Sim, com certeza
Answer: De acordo com sua descrição, você deve estar enviando esse objeto via AJAX.
var obj = {nome: 'Carlos', telefone: '929999999'}
$.ajax("url", {
  data: obj,
  method: "POST"
  success:function(data){
          console.log(data);
  }
}

Em sua servlet, basta pegar esse objeto através do método getParameter() disponível no objeto HttpServletRequest.
Ficaria algo assim
doPost(HttpServletRequest request, HttpServletResponse response) {
  String nome = request.getParameter("nome");
  String telefone = request.getParameter("telefone");

  response.getWriter().write("Nome submetido foi: " + nome + "\n Telefone submetido foi: " + telefone);
}

Espero ter ajudado.
Qualquer dúvida poste nos comentários.
Comment: o request.getParameter(), sempre receberá String então, né?
Comment: Sempre. Se você quiser enviar outro tipo de dados, deve ir mais a fundo e pesquisar sobre Part, MultiPart etc.

Servlet recuperar Objeto


How to hide important string variable values in exe

Question: I want to hide important string variable values like passwords,username,ip and url,etc in .Net application (C#,VB.NET)
In process explorer we can view string in image or Memory ,I want to hide image string
Comment: Basically - you can't. .NET code will always be discoverable. You would need to properly encrypt your string - but that again would require a decryption key that would be stored somewhere in your code.
Comment: please show some source code... what exactly is your goal ? what have you tried ? what is your "risk scenario" ? Are the potential attackers in your scenario "normal users" or "sophisticated hackers" ?
Comment: I want to protect my code from hackers
Answer: You can stop static analysis like that by encrypting the strings and decrypting them at runtime into a SecureString.
The SecureString class is designed specifically to help prevent things like passwords being discoverable in memory.
However, note that it is still possible to attach a debugger to your process and see the strings, so you will need to also obfuscate using something like Dotfuscator to make it even more difficult to see the sensitive strings.
Here is an article about some of the problems with SecureString.
Despite its drawbacks, I think it's still your best best.
Answer: Encode it at compile time, decode at runtime? Someone may still find it since he can decompile your .exe and see the decryption algorithm but some defence > no defence.
Answer: There's an existing implementation in the framework: http://msdn.microsoft.com/en-us/library/system.security.securestring.aspx


Creating new Pandas DataFrame rows from multiple ID columns

Question: I have a Pandas dataframe where rows have attributes and the potential for multiple IDs. For example:
Name    Weapon    Color   ID1    ID2    ID3
Leo     Sword     Blue    11     12
Raph    Sai       Red     13
Don     Bo        Purple  14     15     16
Mike    Nunchuck  Orange  17

I'd like to make each of those IDs its own row while retaining the row's attributes. For example:
Name    Weapon    Color   ID
Leo     Sword     Blue    11
Leo     Sword     Blue    12
Raph    Sai       Red     13
Don     Bo        Purple  14
Don     Bo        Purple  15
Don     Bo        Purple  16
Mike    Nunchuck  Orange  17

How would I use chose specific columns to create rows from and which columns to retain the data from?
Answer: You can use:
df.melt(['Name','Weapon','Color'],value_name='ID').drop('variable',1).dropna()

    Name    Weapon   Color    ID
0    Leo     Sword    Blue  11.0
1   Raph       Sai     Red  13.0
2    Don        Bo  Purple  14.0
3   Mike  Nunchuck  Orange  17.0
4    Leo     Sword    Blue  12.0
6    Don        Bo  Purple  15.0
10   Don        Bo  Purple  16.0

Comment: Saver would be to sort on `['Name', 'Weapon', 'Color']`, since those are the columns which are _melted_, but good answer, upvoted
Comment: `df.melt(['Name','Weapon','Color'],value_name='ID').drop('variable',1).dropna().sort_values('ID')` if sorting on `ID` is required. :)
Answer: You can also use stack(), which keeps the original order of your data:
(df.set_index(['Name', 'Weapon', 'Color'])
   .stack().reset_index(level=-1, drop=True)
   .reset_index(name='ID'))

Output:
    Name    Weapon      Color   ID
0   Leo     Sword       Blue    11.0
1   Leo     Sword       Blue    12.0
2   Raph    Sai         Red     13.0
3   Don     Bo          Purple  14.0
4   Don     Bo          Purple  15.0
5   Don     Bo          Purple  16.0
6   Mike    Nunchuck    Orange  17.0

Note that this will ignore the index of the original dataframe.


Probability that all of some k colors of balls are contained in k/2 buckets

Question: I'd appreciate some help on the below problem.
Let's say you have $d$ each of $n$ colors of otherwise identical balls, and $m$ buckets. You cannot put more than one ball of the same color in any single bucket. All of the balls are distributed randomly and $\frac{1}{2}n<m<n$.
What's the probability that some set of $k$ colors are contained wholly in fewer than $k/2$ buckets, for any $k\in\mathbb{Z}^{+}$?
A nontrivial upper bound would be acceptable.
Thank you!
Edit: Just to clarify, $k$ isn't fixed. I'm asking about the probability that there is a $k$ such that the above condition is satisfied.
Comment: I haven't worked out the problem yet. But wouldn't you also need to impose the restriction $d < k/2$ since you state that there cannot be more than one of each color in any bucket? Otherwise the probability is upper bounded by 0.
Comment: It seems to me that you are confusing balls and colours somewhere.
Comment: @zcsttn Yes, I believe there's no $k\leq 2d$ for which the criteria would be met. Perhaps I should have clarified $k$ isn't fixed. I'm asking about the probability that there is a $k$ such that some set of $k$ colors (et cetera)
Answer: To begin, let's calculate the probability for a fixed $k$.
Since we have $k$ colors, we know we have our $k*d$ balls in (at most) $k/2$ bins. Let's fix the $k$ colors and $k/2$ bins we're considering, and handle combinations later.
For each color, the probability that all $d$ balls are in these fixed $k/2$ bins is
$$\frac{k/2}{m}*\frac{k/2-1}{m-1} * \dots * \frac{k/2-d+1}{m-d+1} $$
$$=\frac{(k/2)!/(k/2-d)!}{m!/(m-d)!}$$
Which we know since the $i$th ball to be placed has $m-(i-1)$ bins that it can be placed in total, and $(k/2)-(i-1)$ of those are in our set of $k/2$ and don't already have a ball.
Since there are $k$ colors, and they're independent, the probability that all colors are like this is simply
$$P(\text{fixed k colors in fixed k/2 bins}) = (\frac{(k/2)!/(k/2-d)!}{m!/(m-d)!})^k$$
Now, since we can have this happen for any $k$ colors (out of $n$ many) and any $k-2$ bins (out of $m$ many), we simply multiply by the number of combinations to get:
$$P(\text{any k colors in any k/2 bins}) = \binom{n}{k} * \binom{m}{k/2} * (\frac{(k/2)!/(k/2-d)!}{m!/(m-d)!})^k$$
Now, if this probability was independent for each unique $k$, we could sum these probabilities to get the probability that this is true for any $k$. However, I'm not convinced they are independent, and don't know how to prove they are even if I did, so instead we can just take the sum of the possibilities as an upper bound:
$$P(\text{any such } k) \leq $$
$$\sum_{k=2d}^{n} \binom{n}{k} * \binom{m}{k/2} * (\frac{(k/2)!/(k/2-d)!}{m!/(m-d)!})^k$$
Also, I will note that this doesn't handle rounding issues related to $k$ being odd, nor the strict inequality, as I thought it would over-clutter the equations. You can throw a floor function around $k/2$ for odd $k$ and a $k/2-1$ for even k if that distinction is important.
This is my first time posting, so apologies for any formatting errors or general mistakes!


Why does this JSON deserialization not work in MVC3 compared to MVC

Question: I have an MVC (v1) application that uses the following custom model binder to deserialize inbound JSON data.
  public class JsonModelBinder : DefaultModelBinder
  {
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
      if (!IsJSONRequest(controllerContext))
      {
        return base.BindModel(controllerContext, bindingContext);
      }

      // Get the JSON data that's been posted
      var request = controllerContext.HttpContext.Request;
      var jsonStringData = new StreamReader(request.InputStream).ReadToEnd();

      // Use the built-in serializer to do the work for us
      return new JavaScriptSerializer().Deserialize(jsonStringData, bindingContext.ModelMetadata.ModelType);
    }

    private static bool IsJSONRequest(ControllerContext controllerContext)
    {
      var contentType = controllerContext.HttpContext.Request.ContentType;
      return contentType.Contains("application/json");
    }
  }
}

The following DataItemColleciton class and contained DataItem class are deserialized properly in MVC (v1).

public class DataItemCollection
{

  #region Constructors

  public DataItemCollection()
  {
    this.dataItems = new List<DataItem>();
  }

  public DataItemCollection(string UserName, string UserInitials, int JobNum, int ObjectVersion, int StationID)
  {
    this.userName = UserName;
    this.userInitials = UserInitials;
    this.jobNum = JobNum;
    this.objectVersion = ObjectVersion;
    this.stationID = StationID;
  }

  public DataItemCollection(string UserName, string UserInitials, int JobNum, int ObjectVersion, int StationID, List<DataItem> DataItems)
  : this(UserName, UserInitials, JobNum, ObjectVersion, StationID)
  {
    this.dataItems = DataItems;
  }

  #endregion

  #region Properties

  public string userName { get; set; }
  public string userInitials { get; set; }
  public int jobNum { get; set; }
  public int objectVersion { get; set; }
  public int stationID { get; set; }
  public List<DataItem> dataItems { get; set; }

  #endregion

}

}

public class DataItem
{

  #region Enums

  public enum DataItemType
  {
    SignOff = 1,
    Material = 2,
    Task = 3,
    ShippingInfo = 4,
    Count = 5
  }

  #endregion

  #region Constructors

  public DataItem() { }

  public DataItem(DataItemType ItemType, int DataLength)
  {
    this.itemType = ItemType;
    //Creates array of specified item type for easier access later if necessary...
    switch (ItemType)
    {
      case DataItemType.SignOff:
        this.itemData = new ViewModels.JobTracking.SignOff[DataLength];
        break;
      case DataItemType.Material:
        this.itemData = new ViewModels.JobTracking.Material[DataLength];
        break;
      case DataItemType.Task:
        this.itemData = new ViewModels.JobTracking.Task[DataLength];
        break;
      case DataItemType.ShippingInfo:
        this.itemData = new ViewModels.JobTracking.ShippingInfo[DataLength];
        break;
      case DataItemType.Count:
        this.itemData = new ViewModels.JobTracking.Count[DataLength];
        break;
    }
  }

  #endregion

  #region Properties

  public DataItemType itemType { get; set; }
  public object[] itemData { get; set; }

  #endregion

  }
}

In MVC3 the deserialized JSON has the properties in DataItemCollection but it appears the DataItem objects were not deserialized properly.
DataItemCollection
  .userName
  .userInitials
  .jobNum
  .objectVersion
  .stationID
  .dataItems

The .dataItems property has a collection of generic objects w/ nothing in them.
What is different in the MVC3 deserialization compared to the original MVC which would cause this not to work? Also, any thoughts on how to fix it w/ the least impact on the existing code?
Answer: I'm not sure what is the difference between MVC 1 and MVC 3 in this case but I usually use JSON.NET which is much more powerful yet very lightweight to serialize and de-serialize to json.
http://json.codeplex.com/


Python error - name lengths

Question: Here's the requirement:
Write a program that checks how long a name is. The program should take a name as input from the user.
If the name has 3 or fewer letters, your program should work like this:

Enter your name: Lin
  Hi Lin, you have a short name.

If the name has between 4 and 8 letters (inclusive), your program should work like this:

Enter your name: Jimmy
  Hi Jimmy, nice to meet you.

Otherwise, if the name has more than 8 letters, your program should work like this:
Enter your name: Yaasmeena

Hi Yaasmeena, you have a long name.

Here's my attempt but it always returns "Hi XXXXXXX, nice to meet you" if the name length is > 3
name = input('Enter your name: ')

if len(name) <= 3:
    print ('Hi',name, ', you have a short name.')
elif len(name) >= 3:
    print ('Hi',name, ', nice to meet you.')
elif len(name) > 8:
    print ('Hi',name, ', you have a long name.')

Comment: Did you read the comments made on your last question? Your answer is there.
Comment: Solved
name = input('Enter your name: ')

if len(name) <= 3:
  print ('Hi',name, ', you have a short name.')
elif len(name) > 8:
  print ('Hi',name, ', you have a long name.')
elif len(name) >= 4:
  print ('Hi',name, ', nice to meet you.')
Answer: why don't you check for bounds first?
name = input('Enter your name: ')

if len(name) <= 3:
    r = 'you have a short name.'
elif len(name) > 8:
    r = 'you have a long name.'
else:
    r = 'nice to meet you.'

prins 'Hi {}, {}'.format(name, r)

Answer: name = input('Enter your name: ')

if len(name) <= 3:
    print ('Hi', name+', you have a short name.')
elif 8 >= len(name) >= 4:
    print ('Hi', name+', nice to meet you.')
elif len(name) > 8:
    print ('Hi', name+', you have a long name.')

Considering this is for grok learning, this would output the correct error, without white spaces.
Comment: I'd write the middle condition as `4 <= len(name) <= 8` to be a bit clearer.
Comment: Since its in an `elif` statements, you don't need both ends of that check. Just do `elif len(name) <-= 8` and it will work (shorter names will be caught by the first `if`). You can also drop the condition on the last block, and make the `elif` just an `else`.

Python error - name lengths


Comparing models with main effects and interactions

Question: I have two models:

Model 1: Only contains independent variable $x$, while $x$ is non-significant.
Model 2: Contains $x$, $m$, and $x * m$, and $x * m$ is significant.

How could I illustrate this result? Can I still say that $m$ has a moderating effect? If so, how can I determine the direction of $m$'s effect?
Comment: How best to illustrate this depends on what type of regression. OLS? Logistic? Something else?  Also, are x and m categorical or continuous or what?
Answer: Ignore "significance".  Pre-specify the full model, heavily informed by subject matter knowledge.  Get point and interval estimates of interest through pre-specified contrasts.  Use simultaneous contrasts if you want multiplicity adjustment.  Main effects are single-difference contrasts and interaction effects are double-difference contrasts.  See here for multiple examples using the R rms package contrast.rms function.  Note that for interaction contrasts, contrast() requires 4 list() arguments to specify the predictor variable settings to double difference.
Comment: thanks so much!
Comment: This is great. I want to make my whole faculty read this !! But I have a question: when you say "Pre-specify the full model", what do you mean by *"full"* - do you mean the largest model (including interactions, splines etc) as dictated by prior knowledge ? Not just every term that we can think possibly of ! ?
Comment: It's hard to be extremely specific without being Bayesian, because a Bayesian modeler would use the fullest model but put skeptical priors on interaction terms, thereby reducing their effective number of degrees of freedom and reducing sample size requirements.  But in general the full model includes all the terms that the investigator cares about and thinks might be non-zero.
Answer: When It Matters
I agree with Frank that statistical significance really shouldn't be the major criterion here for interpreting your data. If we simply step away from the statistics for a second, why would this interaction make sense? What is driving this interaction? Sometimes interactions are found by chance. Other times it can be because of complex phenomenon. You need to consider this first before you even go forward with interpretation.
Let's say we have a scenario where we obtain the measured temperature on a given day and the caloric intake of some frogs for that same day (see example of frog diet below...).

Sadly, frogs don't always get to live to have another meal. We decide to record the number of frog deaths that day given the number of flies they eat and the temperature outside. There is likely a lot better construction of this experiment (e.g. survival rates over time), but we can just keep the example simple for now. Let us say that during the course of measuring the frogs, we noticed that temperature doesn't really have any practical effect (frogs generally don't die from temperature alone), nor does food intake (I'm not a frog expert, but lets just assume they're efficient with calories).
However, after getting our measurements, our data ends up showing that the combination of high temperature and low caloric intake results in a substantial number of frog deaths. We could perhaps determine, with trepidation as an observational study, that the relationship between temperature and caloric intake is driving the frog deaths, but the influence of one or the other alone doesn't make a difference. It is surmised that frogs exposed to extreme heat and a lack of proper nutrition together causes higher death rates and this is then reported to the scientific community. This is the key to Frank's statements about subject matter knowledge. The context of the question will matter, and whether or not our regression fits the mold can only be rightfully determined by that knowledge.
See here that I have not highlighted statistical significance at all, a point I will elucidate as potentially misleading in the next part of this answer.
When it Doesn't Matter
We can easily simulate a similar scenario where the main effects are statistically non-significant and the interaction is significant. By creating very tiny effects, we can also show that this distinction may not really matter. Below I simulate some data in R to mimic this:
#### Simulate Data ####
set.seed(123)
x <- rnorm(1e4) # normally distributed predictor
z <- rnorm(1e4) # normally distributed control

#### Create Beta Weight and Error ####
b0 <- 0 # intercept
b1 <- .0001 # slope 1
b2 <- .0001 # slope 2
b3 <- .05 # interaction
e <- rnorm(1e4) # normal error term
y <- b0 + (b1*x) + (b2*z) + (b3 * x * z) + e # linear construction of y
df <- data.frame(x,z,y)

Note a few things before we fit the regression:

The sample size is large ($ n = 10,000$), so we should have excellent power to detect even minor effects.
The $\beta$ weights, the intercept and slopes, are quite tiny $\beta = .0001$, and I have only adjusted the interaction to have slightly more magnitude to flag our significance tests ($\beta_3 = .05$).

We fit the regression in R below:
#### Fit Regression ####
fit <- lm(y ~ x*z)
summary(fit)

With the following output:
Call:
lm(formula = y ~ x * z)

Residuals:
    Min      1Q  Median      3Q     Max
-3.9996 -0.6647  0.0066  0.6733  3.8627

Coefficients:
             Estimate Std. Error t value Pr(>|t|)
(Intercept)  0.006126   0.010077   0.608    0.543
x           -0.012349   0.010091  -1.224    0.221
z            0.004928   0.010062   0.490    0.624
x:z          0.053967   0.010239   5.271 1.39e-07 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 1.008 on 9996 degrees of freedom
Multiple R-squared:  0.002928,  Adjusted R-squared:  0.002629
F-statistic: 9.784 on 3 and 9996 DF,  p-value: 1.926e-06

Some things should already stick out:

The interaction is the only "significant" term here, but we must consider scale here for all of the betas. If we consider our frog example, with caloric intake and degrees Fahrenheit as predictors, are these effects practically meaningful?
The adjusted $R^2 = .002629$, which means the model has very little explanatory value despite the model being statistically significant.

Plotting the data can of course elucidate this point. If we simply look at the scatters of $x$ and $z$ on $y$, we can see these two giant clouds of data which seem to have essentially no association with the outcome:

What if we check the interaction between $x$ and $z$? We can do this by first creating some simple slopes:
#### Create Sequence of Values Controlling for +/- SD and Mean of Z ####
newdata1 <- data.frame(
  x = seq(
    min(x),
    max(x),
    length.out=200 # sequence of data to get prediction line for x
  ),
  z = mean(z) - (1*sd(z)) # 1 SD below mean of z
)

newdata2 <- data.frame(
  x = seq(
    min(x),
    max(x),
    length.out=200
  ),
  z = mean(z) # mean of z
)

newdata3 <- data.frame(
  x = seq(
    min(x),
    max(x),
    length.out=200
  ),
  z = mean(z) + (1*sd(z)) # one SD above mean of z
)

#### Get Prediction Data ####
pred1 <- predict(fit,newdata = newdata1)
pred2 <- predict(fit,newdata = newdata2)
pred3 <- predict(fit,newdata = newdata3) # predicts model with new data

Then we plot the scatterplot of $x$ and $y$ again, only this time we overlay the predictions when $z$ is at its mean or one standard deviation above/below that mean (indicated by the red lines):
#### Plot Interaction ####
par(mfrow=c(1,1))
plot(x,y,main="Interaction Plot")

lines(newdata1$x,
      pred1,
      col="red",
      lwd=5)

lines(newdata2$x,
      pred2,
      col="red",
      lwd=5)

lines(newdata3$x,
      pred3,
      col="red",
      lwd=5)

Shown below:

Now we can determine some additional facts:

While our interaction is statistically significant, the plotted lines show the interaction isn't incredibly strong (they almost overlap).
Looking at the axes of the plot, the scale here really matters. Note here that the values only range between about $[-4,4]$. Low-scale values can be considered large in some contexts (for example if $x$ is BAC content) or essentially meaningless (if $x$ is income in the thousands). The context and research question will determine if these effects and interactions are truly meaningful.
We still don't know from our simulated example what this means. I have purposely left out what this simulation was supposed to emulate to illustrate an important point: what we are measuring should be important to answering questions of scientific importance. If we don't have any background knowledge driving that inference, then it is hard to determine if it is indeed important. Something like statistical significance has an otherwise limited role in answering those questions.

Model Comparison
Most of this discussion did not really highlight what to do in terms of model comparison. Consider for our simulated example if we fit the models with and without an interaction:
#### Fit Models ####
fit1 <- lm(y ~ x + z)
fit2 <- lm(y ~ x * z)
summary(fit1)
summary(fit2)

As shown here:
> summary(fit1)

Call:
lm(formula = y ~ x + z)

Residuals:
    Min      1Q  Median      3Q     Max
-3.5771 -0.6799 -0.0077  0.6883  4.3606

Coefficients:
             Estimate Std. Error t value Pr(>|t|)
(Intercept) -0.006785   0.010013  -0.678    0.498
x            0.020496   0.010027   2.044    0.041 *
z           -0.003838   0.009998  -0.384    0.701
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 1.001 on 9997 degrees of freedom
Multiple R-squared:  0.0004315, Adjusted R-squared:  0.0002316
F-statistic: 2.158 on 2 and 9997 DF,  p-value: 0.1156

> summary(fit2)

Call:
lm(formula = y ~ x * z)

Residuals:
    Min      1Q  Median      3Q     Max
-3.4854 -0.6830 -0.0075  0.6905  4.3599

Coefficients:
             Estimate Std. Error t value Pr(>|t|)
(Intercept) -0.007047   0.010005  -0.704   0.4812
x            0.020198   0.010018   2.016   0.0438 *
z           -0.003170   0.009990  -0.317   0.7510
x:z          0.044362   0.010166   4.364 1.29e-05 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 1 on 9996 degrees of freedom
Multiple R-squared:  0.002332,  Adjusted R-squared:  0.002033
F-statistic: 7.789 on 3 and 9996 DF,  p-value: 3.43e-05

Comparing these two models by their significant terms doesn't really say much. What we would really need is some kind of other determinations, like AIC/BIC or some chi-square test. We can quickly check these to see if this interaction term is indeed important to include:
#### Check Model Comparison ####
anova(fit1,fit2, test = "Chisq")
AIC(fit1)
AIC(fit2)

The chi-square test is unsurprisingly statistically significant because of the sheer degrees of freedom present from the number of data points:
Analysis of Variance Table

Model 1: y ~ x + z
Model 2: y ~ x * z
  Res.Df   RSS Df Sum of Sq  Pr(>Chi)
1   9997 10023
2   9996 10004  1    19.057 1.278e-05 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

However, our AIC values have very little difference here:
> AIC(fit1)
[1] 28409.57
> AIC(fit2)
[1] 28392.54

So again, we need to consider the data, the theory, and other important factors when comparing such models even in a strictly statistical way.
Comment: thank u so much for your detailed analysis! this does help me a lot!
Comment: Great! Feel free to accept one of the answers here if it answered your question (by clicking the checkmark next to the answer).
Comment: Note that the chi-squared test you do tests the same hypothesis as the $t$-test for the `x:z` coefficient in the `summary(fit2)` table. More precisely, it is equivalent to the corresponding two-sided $Z$-test, i.e., a two-sided $t$-test with infinite degrees of freedom.
Answer: Adding a factor to a model can change the estimates and confidence intervals of the present factors. An example that is easily illustrated is the case of an intercept term. For example: Why do my (coefficients, standard errors & CIs, p-values & significance) change when I add a term to my regression model?
A simple example for a change in the main effect when an interaction term is added is a model like
$$y_i = a+b x_iz_i + \epsilon$$
Such model has only an interaction term and no main effect. So when you fit your model 1, you may observe a significant main effect because the main effect can correlate with the interaction term, and this 'disappears' when we include the interaction term. The interpretation of the main effect also changes when we include an interaction term.
In the figure below you can see an example.

With a main effect only the model fits reasonably and the coefficient for $x$ relates to the average slope.
With the interaction term included the model fit is improved. But now the interpretation of the main effect changes and the coefficient for $x$ relates to the slope when $z=0$. In the example this slope is very close to zero and 'not significant'.

R-code for the image:

set.seed(1)
n = 200
x = runif(n,0.5,3)
z = sample(6:9,n,replace = 1)
y = 30+2*x*z+rnorm(n)

plot(x,y, col = z-5, pch = 20, main = "fit with lm(y ~ x)", xlim = c(0,3.5), c(30,80))
legend(0.5,75,9:6, col = 4:1, pch = 20, title = "z")

xs = seq(0.5,3,0.01)
b = lm(y ~ x)$coef
lines(xs, b[1]+b[2]*xs)

plot(x,y, col = z-5, pch = 20, main = "fit with lm(y ~ x*z)", xlim = c(0,3.5), ylim = c(30,80) )
legend(0.5,75,9:6, col = 4:1, pch = 20, title = "z")

b = lm(y ~ x*z)$coef
lm(y ~ x*z)
for (z in 0:9) {
  lines(xs, b[1]+b[2]*xs + b[3] * z + b[4] * xs*z)
  text(3, b[1]+b[2]*3 + b[3] * z + b[4] * 3*z,
        paste0("z = ",z), pos = 4)
}

You can still call one of the variables a moderator, which one that depends on your viewpoint (One of the main effects not significant, but interaction term significant)
Also note that by translation of the variables we can change the specific slope that is regarded as the 'main effect'. The interpretation of the 'main effect' is subjective and often it doesn't matter whether it is significant or not when the interaction is significant.


Distribution of a Sum According to Skewness

Question: Given a list of numbers $L$, we can compute for the mean of the numbers, the standard deviation and then the median. Then use the (non-parametric) skew to compute for the skewness using:
$$S = \dfrac{\mu-v}{\sigma}$$
where $\mu$ is the mean of the numbers in $L$, $v$ is the median of the numbers in $L$ and $\sigma$ is the standard deviation of the numbers in $L$.
So say, we wish to reverse the process. Instead of being presented with a list and computing the skewness $S$, we are only given the sum $\mathcal{S}$ of the numbers in the list, $n$ as the number of numbers in the list, and its skewness $S$. Can we come up with a list of numbers $L$ (or a set as order doesn't matter) such that it has $n$ numbers, it has a sum equal to $\mathcal{S}$ and has a skewness value equal to $S$? Is this even possible? I can't seem to find a source anywhere about how to do this.
So for example if a list of $n=9$ numbers has a sum of $81$ and has skewness of $0.43$. All I know would be the mean to be $\mu=9$ but I'm left under the dark after that. Any suggestions or tips on how to proceed? Thanks so much!
Answer: You have a large amount of freedom: for example the scale of the dispersion is unspecified.
You know the median is less than the mean, so let's arbitrarily choose the median to be $8$.  Perhaps we can do this with only three numbers: $x_{(1)},x_{(2)},x_{(3)}$ with $x_{(2)}=8$ and mean $\frac{x_{(1)}+x_{(2)}+x_{(3)}}{3}=9$.  We minimise $\sigma$ and maximise your skewness when $x_{(1)}=8$ and $x_{(3)}=11$ giving a population standard deviation of $\sqrt{2}$ and a skewness on your definition of about $0.7071$.  That is more than $0.43$, so we can afford to increase the standard deviation and it seems that $x_{(1)}=6.78661, x_{(2)}=8, x_{(3)}=12.21339$ with a population standard deviation of about $2.32558$ gives your $0.43$ target figure.
You wanted nine rather than three numbers: that is not a problem as we can just repeat each value three times, though you might decide you want to spread out the nine values more, or to have a different difference between the mean and median.  There were other arbitrary choices there, and you might want to adapt the process, for example perhaps to use a so-called sample standard deviation.
An algorithm which says find the distribution which maximises the magnitude of your skewness figure, and then relax the data to increase the standard deviation to hit the target you want, should work so long as there is a solution. Sticking to odd-number sample sizes $n$ so the median is simple, I think you can get a solution so long as the magnitude of your target skewness is no more than $\sqrt{1-\frac{2}{n+1}}$.


Problem understanding integral evaluation

Question: I am having trouble understanding the evaluation of an integral. Do we just separate the integrals and evaluate them? Is it like normal integration?
I have provided an example below taken from one of my tutorial questions, it would be great if someone explains to me on how the evaluation of an integral takes place. I can try solving my other tutorial questions if i am able to understand the manner in which integrals are evaluated.
Evaluate the following Integral:
$$\int \cos x( \tan x +\sec x)\mathrm{d}x$$
Ans:
$ - \cos x + x + C$
Comment: Simplify $\cos(\tan(x)+\sec(x))$ first. Can you handle the integral after simplifying?
Comment: @GitGud Thank you, will try with the other problems :)
Answer: We can simplify the expression a good deal since $\tan x = \frac{\sin x}{\cos x}$ and $\sec x = \frac{1}{\cos x}$:
$$\int \cos x (\tan x + \sec x) dx = \int \cos x (\frac{\sin x}{\cos x} + \frac{1}{\cos x}) = \int (\sin x + 1) dx = -\cos x + x + C $$
Comment: @Phantom We are all here to learn :)
Comment: Oh god...thank you very much! I am such an idiot :)


Can a variable that is I(0) also be I(1)?

Question: After applying the ADF test for nonstationarity, I find that for both the test at level and the test at first differences, all my variables are both I(0) and I(1). I.e. the p-value is below 0.05 in both cases.
Is this an issue?
Comment: FenleyK, if you find the answer satisfactory, you may accept it by clicking on the tick mark to the left of the answer. Otherwise, let me know what is still unclear.
Comment: I was going through my old answers and noticed this one was not accepted. Do you perhaps need further clarification?
Answer: No, an I(0) variable cannot simultaneously be I(1).
The order of integration is defined as the number of differences that need to be taken to get rid of the unit roots. If the series has no unit root at levels, this number is zero. (The fact that you also reject a unit root at first differences is irrelevant then.)


Find a plane that contains two given vectors and a point.

Question: Write down the cartesian equation of the plane that contains the point (1,0,3) and the vectors $$u=(-1,1,2)$$ $$v=(1,0,-1)$$
So I cross product-ed vectors $v$ and $u$, substitute the point into the normal vector, and came up with this equation $$-x+y-z=-4$$ I'm not sure whether I'm doing this correctly so I need help with checking, thank you guys!
Edited: And would the vector equation of the plane be $$r=(1,0,3)+s(-1,1,2)+t(1,0,-1)$$
Comment: You're correct. Good job!
Answer: We can find the normal vector $\vec{\mathbf n}$ to the plane by finding the cross product of the vectors $\vec{\mathbf u}$ and $\vec{\mathbf v}$.
$$\vec{\mathbf u}\times\vec{\mathbf v}=\langle(1)(-1)-(2)(0),(2)(1)-(-1)(-1),(-1)(0)-(1)(1)\rangle=\langle-1,1,-1\rangle$$
This comes from the fact that $\vec{\mathbf u}\times\vec{\mathbf v}=\langle u_2v_3-u_3v_2,u_3v_1-u_1v_3,u_1v_2-u_2v_1\rangle$ [1]. We can place the components of this normal vector into the general equation of a plane [2].
$$-x+y-z+d=0$$
We can easily solve for $d$ by placing the coordinates of point $P(1,0,3)$ into the equation.
$$-(1)+(0)-(3)+d=0\implies-4+d=0\implies d=4$$
We now have the general equation of the plane containing the two vectors $\vec{\mathbf u}$ and $\vec{\mathbf v}$ and the point $P(1,0,3)$.
$$-x+y-z+4=0$$
We have the normal vector $\vec{\mathbf n}=\langle-1,1,-1\rangle$ to the plane and the position vector $\vec{\mathbf r}_0=\langle1,0,3\rangle$ of the point $P(1,0,3)$ in the plane, so we can find the vector equation of the plane [3].
$$\vec{\mathbf n}\cdot\left(\vec{\mathbf r}-\vec{\mathbf r}_0\right)=0\implies\langle-1,1,-1\rangle\cdot\left(\vec{\mathbf r}-\langle1,0,3\rangle\right)=0$$
Here, $\vec{\mathbf r}$ is the position vector of some arbitrary point in the plane. For example, the point $Q(2,-1,1)$ is in the plane because $-(2)+(-1)-(1)+4=0$.
$$\langle-1,1,-1\rangle\cdot\langle(2-1),(-1-0),(1-3)\rangle=(-1)(1)+(1)(-1)+(-1)(-2)=0$$


The array runs, but does not give the correct values when compiled?

Question: I simply don't know where I'm getting it wrong. I've included the whole code. I'm trying to get the percentage part to display 30 distinct values, but it keeps displaying 29. Is there a simple fix to this and am I making this too complicated?
private static final Scanner
   stdIn = new Scanner(System.in);

   private static Random
   rng;

   public static void main (String[] args){

    long
       rngSeed;

    int
       numberOfFlips,
       totalNumberOfRuns = 1,
       run = 0;

     boolean
       theCoin,
       tempVal = false;

   System.out.println("Welcome to the coin flip analyzer.\n" +
    "How many flips?");
   numberOfFlips = stdIn.nextInt();
   System.out.println("What do you want to seed the random number generator with?");
   rngSeed = stdIn.nextLong();

   int[]runLength = new int[50];
   rng = new Random(rngSeed);

   for (int i = 0; i < numberOfFlips; i++) {
       theCoin = rng.nextBoolean();
       if (i > 0 && theCoin != tempVal) {
          if (i < 50) {
              System.out.print(run + " ");
         }
          runLength[run - 1]++;
          totalNumberOfRuns++;
          run = 1;
      }
       else
           run++;
       if (theCoin) {
           if (i < 50) {
               System.out.print("H");
           }
           tempVal = true;
       }
       else {
           if (i < 50) {
               System.out.print("T");
           }
           tempVal = false;
       }
   }

   System.out.print("...");
   System.out.println();

   System.out.println("There were a total of " + totalNumberOfRuns +
    " distinct runs in the simulation.\nTheir breakdown follows.");

   // run length table header line

    System.out.println("[run length] = # (as percentage of all runs)");

   // your code to display the count and frequency percentage of each run length
   // should follow

    for (int i = 0; i < runLength.length; i++) {
        double percentageFreq = ((double) + (runLength[i]) / (totalNumberOfRuns) * 100);
        if (runLength[i] > 0)
            System.out.println("[" + (i+1) + "] = " + runLength[i] + " (" + String.format("%1.1f", percentageFreq) + " %)");
            }
      }
}

...............
Most Important Part of Outcome Using: 50 flips and a random seed value of 1200.

H1 T1 H1 T1 HHH3 TTTTT5 H1 T1 HHHH4 T1 HH2 T1 H1 T1 H1 T1 H1 T1 H1 TTT3 H1 TTT3 H1 TTTT4 H1 T1 HHH3 TT2 H1 T...

There were a total of 30 distinct runs in the simulation.
Their breakdown follows.

[run length] = # (as percentage of all runs)
[1] = 20 (66.7 %) (I need this to be 21 since the last value is "T").
[2] = 2 (6.7 %)
[3] = 4 (13.3 %)
[4] = 2 (6.7 %)
[5] = 1 (3.3 %)

...............
Comment: You should edit your question according to the guidelines in https://stackoverflow.com/help/mcve.
Answer: There are a few problems with your code. The ultimate reason why it's not working is that the final coin flip is not being counted.
The reason why your code is outputing There were a total of 30 distinct runs in the simulation. is because you start totalNumberOfRuns at the wrong value.
totalNumberOfRuns should start at 0 rather than 1.
Also notice how the end of the output for coin flips is T..., there should be a 1 following the T. You need to place that print statement at the end of the loop, otherwise it will only print the number from the previous iteration and simply not run at all for the final iteration.
Also, throughout your code you use magic numbers. E.g. if (i < 50), int[]runLength = new int[50]. Magic numbers are evil and you should never use them. An example of why magic numbers are evil: what if the user enters 100 when asked how many times the coin should be flipped? The code will not run properly in this case. Regardless even if you were not using a magic number here, these conditional statements are pointless because i will never be greater than 50 if you enter 50 for numberOfFlips.
I also am a bit bothered by the styling in your code. Please please please use curly braces even for blocks that are one line long. At the very least, at least be consistent with it. At some points you use curly braces for single-line if statements, but in one spot you don't use curly braces for a single-line else statement.
Also, your print statement where you output the frequencies is very messy. This is a perfect place to use System.out.printf, especially since you are already using String.format inside of the print method. The printf method is a beautiful thing and you should get comfortable with it. Here is what you should use:
System.out.printf("[%d] = %d (%1.1f%%)%n", i + 1, runLength[i], percentageFreq);
I got your code working, and I also cleaned it up a bit. Before you copy and paste this solution, I implore you to think about why my explanation above will fix your code, as well as what I did to clean up your code (e.g. rng should not be static)
Here you go :)
public class Main {
private static final Scanner stdIn = new Scanner(System.in);

public static void main(String[] args) {

    int totalNumberOfRuns = 0;
    int run = 1;
    boolean theCoin, tempVal = false;

    System.out.println("Welcome to the coin flip analyzer.\n"
            + "How many flips?");
    int numberOfFlips = stdIn.nextInt();
    System.out
            .println("What do you want to seed the random number generator with?");
    long rngSeed = stdIn.nextLong();
    Random rng = new Random(rngSeed);
    int[] runLength = new int[numberOfFlips];

    for (int i = 0; i < numberOfFlips; i++) {
        theCoin = rng.nextBoolean();
        if (theCoin != tempVal) {
            runLength[run - 1]++;
            totalNumberOfRuns++;
            run = 1;
        } else {
            run++;
        }
        if (theCoin) {
            System.out.print("H");
            tempVal = true;
        } else {
            System.out.print("T");
            tempVal = false;
        }
        System.out.print(run + " ");
    }

    System.out.print("...");
    System.out.println();

    System.out
            .println("There were a total of "
                    + totalNumberOfRuns
                    + " distinct runs in the simulation.\nTheir breakdown follows.");

    // run length table header line

    System.out.println("[run length] = # (as percentage of all runs)");

    // your code to display the count and frequency percentage of each run
    // length
    // should follow

    for (int i = 0; i < runLength.length; i++) {
        double percentageFreq = ((double) +(runLength[i])
                / (totalNumberOfRuns) * 100);
        if (runLength[i] > 0) {
            System.out.printf("[%d] = %d (%1.1f%%)%n", i + 1, runLength[i],
                    percentageFreq);
        }
    }
}
}

Comment: Flaom, I really appreciate it and that makes more sense. I knew it probably had something to do with what I was initializing my variables to. My only question remaining is how can I get rid of that first one, so that it simply starts at H1 or is that not possible? Again, I really appreciate it.

I knew I had some imaginary numbers that needed to go. I've heard of being able to use printf but never thought I could use it in this case.
Comment: Can you be more specific please? When I run it, it does start at H1. Are you getting something else?
Comment: Yes, mine starts with 1, because I need the specific values I mentioned in my reply. Yours does indeed start with H1, but mine starts with 1 because I had to rearrange one part so it would consolidate to what I had in my above comment.
Comment: I believe I got it working the way I need it based off your code and some minor edits to mine! Just needed to edit the percentage portion! Thank you so much for your knowledge!
Comment: Alright, I got everything working. I have another question if you don't mind. I want my output value value to always end at the "H1 T..." portion regardless of what seed value I put in. It will still get different distinct values and such in the process, but it won't display the random distinct values after the "H1 T..." to keep things tidy. Is there a way of doing that? I've tried rearranging my for loop, but it doesn't seem to work entirely.


When can the collapsed Gibbs sampler be implemented?

Question: I understand Gibbs sampling is a means of statistics inference, and it seems that sometimes certain variables can be integrated out in the sampling process, known as collapsed Gibbs sampling. I really want to know in what circumstances the collapsed Gibbs sampling can be applied, and which variables can be integrated out?
I did some search on Google, and it appears there are no detailed explanation on it. Though there are some papers on applying collapsed Gibbs sampling on Latent Dirichlet Allocation (LDA), I am no expert of MCMC and have no idea what LDA is, so it may be hard for me to read those papers. Can someone answer this question and it would be better, provide some examples? Much appreciated!
Answer: Suppose the density of the target distribution is $f(x, y, z)$ and the goal is to draw samples from this distribution. This is often difficult because the density is only known upto a normalizing constant. That is, $f$ is not known entirely but the function $g$ below is
$$f(x,y,z) \propto g(x,y,z) $$
The usual Gibbs sampler would require obtaining all three full conditionals and cycling through them. That is, for the $t$th sample

Draw $x_t$ from $x \mid y_{t-1}, z_{t-1}$
Draw $y_t$ from $y \mid x_t, z_{t-1}$
Draw $z_t$ from $z \mid x_t, y_t$

Naturally, in order to implement this Gibbs sampler, it must be straightforward to sample from all three full conditionals using standard software. Often, obtaining these full conditionals is not possible, in which case a full Gibbs sampler is not implementable to begin with. Then $\{(x_t, y_t, z_t)\}_t$ forms a Markov chain with invariant distribution having density $f(x,y,z)$.
To implement a collapsed Gibbs sampler, you first integrate either $x$, $y$, or $z$ out and then run a Gibbs sampler on the marginal of the remaining two. Suppose, you integrate $z$ out. Now that target density is
$$f(x,y) = \int f(x, y, z) \,dz\,.$$
Note that if a Gibbs sampler like the one above is possible, then it is straightforward to integrate out $z$, since
\begin{align*}
f(x,y) & = \int f(x, y, z) \,dz\\
& = c \int g(x,y,z) dz\\
& \overset{(a)}{=} c'g(x,y) \int f(z\mid x,y) dz\\
& \propto g(x,y)
\end{align*}
where the equality $(a)$ holds because a closed form expression of $f(z \mid x,y)$ is attainable since a usual Gibbs sampler (as described above) is possible.
Now, if it is possible to run a Gibbs sampler with $f(x,y)$ as the invariant distribution, then the resulting sampler is a collapsed Gibbs sampler. So if $f(x\mid y)$ and $f(y \mid x)$ are available in closed form so that for the $t$th sample

Draw $x_t$ from $x_t \mid y_{t-1}$
Draw $y_t$ from $y_t \mid x_t$

Then $\{(x_t, y_t)\}_t$ is a Markov chain with stationary distribution $f(x,y)$. Note that since $f(x,y,z) = f(z \mid x,y) f(x,y)$, the samples $z_t$ can be obtained drawing from density with distribution $f(z \mid x_t, y_t)$. Running this Gibbs sampler depends heavily on whether once can sample from $x\mid y$ and $y \mid x$.
To summarize, a collapsed Gibbs sampler can be implemented if for a group of three variables $x,y$ and $z$, one can sample from $x|y$, $y|x$ and $z|x,y$. One can choose which variable to integrate out based on which conditional distributions are available.
Some books on these topics are:
Monte Carlo Statistical Methods by C. Robert : Good for an introduction to Gibbs sampling
Monte Carlo Strategies in Scientific Computing by J. Liu : Has some discussion of collapsed Gibbs samplers (I think).
Comment: Thanks for answering my question. I am a little confused. Regarding  "where the equality (a) holds because a closed form expression of f(z∣x,y) is attainable since a full Gibbs sampler is possible.", which full Gibbs sampler are you referring to?
Comment: One more question, what is the invariant distribution of a Markov chain? Is it the same thing as the stationary distribution?
Comment: I realize that you are an expert in MCMC and Bayesian computation. I just start to learn MCMC and Bayesian statistics, it would be better if you could provide me some great books regarding to these topic. Thanks again!
Comment: @SteveYang  I have added some references. And yes, invariant distribution is another name for stationary distribution. By full Gibbs sampler, I meant the usual Gibbs sampler I described in the beginning.


How to deactivate a user without deleting him in parse.com?

Question: I want to deactivate a user in parse.com, so when he tries to connect, he will be informed that his accounts is deactivated.
Can anyone help me?
Comment: Have you tried anything? Add your attempt(s) here and specify what your problem is in your code
Comment: i can make the user authenticate but i really don't know how to proceed and modify the user class and how to check in the authentication. i'm new to parse so i'm reading the docs with no luck.
Answer: I am new to Parse, but could you add a bool column in your class that is called active.  Then you can check that column to see if it is true.  If false show your alert stating they are inactive.
Comment: Or a string column called 'state' would work even better, so that you can assign multiple states and wont be limited by just the two.
Comment: i'm new too to Parse and i really don't know how to do this, i downloaded Parse sdk and it work perfectly, the problem is how to add this kind of stuff and how to check this with it.
Comment: @AhmedCommando I'm sure there should be samples and a stack of documentation because it is an SDK. SO is not here to teach you how to use a specific technology etc. It is up to you to try things, and if you are stuck and don't know why because everything seems logical and correct to you, you can ask for help. Please read the http://stackoverflow.com/help items regarding asking questions. You must have at least a basic understanding what you are trying to accomplish before you ask a question, and you need to attempt something in the process


Como alterar datas do formato americano y/m/d para d/m/y?

Question: Comprei alguns sistemas porem todos vem com campos de datas em inglês, e também no padrão americano: ano/mês/dia.
Como faço para converter para o formato dia/mês/ano?
Comment: E esta data se encontra onde? No banco de dados? No arquivo PHP?
Comment: Anthony, bemvindo ao Stackoverflow. Pode explicar melhor a sua pergunta e ser mais claro no que procura. Eu percebo que quer converter o formato de datas mas não faço ideia de onde o quer fazer...
Comment: Se puder postar o código e o banco de dados ajuda bastante, lia o guia [ask] e depois [edit]e sua pergunta.
Comment: Ele quer converter o formato no PHP, a [resposta](http://pt.stackoverflow.com/a/25512/7210) é que o AP pretende.
Comment: Tome cuidado, se tiver alguma ligação com uma base de dados como o MySQL, você deve fazer todos os *inserts* no formato americano.
Answer: <?php
echo date('Y/m/d'); // retorna a data nesse formato ano/mês/dia, essa data é a atual do servidor você pode alterar da forma que desejar exemplo date('d-m-Y')

echo date('d/m/Y',  strtotime($variavel)); // convert a data da $variavel para o formato dia/mês/ano
?>

Te aconselho usar notepadd++ ou dreamweaver o recurso de pesquisar nos arquivos, assim você pesquisa onde tem date, data, $date algo assim ate encontrar e usar a segunda opção que convert para nosso formato mais comum
Answer: Talvez você possa utilizar o locale.
Veja um exemplo:
<?php
/* Define o local para Holandês(usar pt_BR para o Português(Brasil) ) */
setlocale (LC_ALL, 'nl_NL');

/* Mostra: vrijdag 22 december 1978 */
echo strftime ("%A %e %B %Y", mktime (0, 0, 0, 12, 22, 1978));

/* Tenta diferentes nomes de local para o Alemão apartir do PHP 4.3.0 */
$loc_de = setlocale (LC_ALL, 'de_DE@euro', 'de_DE', 'de', 'ge');
echo "Preferred locale for german on this system is '$loc_de'";
?>

Referências:

http://php.net/manual/pt_BR/function.setlocale.php
http://php.net/manual/pt_BR/class.locale.php
Answer: Você pode usar um conjunto de funcões da seguinte forma:
Passando do formato americano para formato brasileiro:
implode('/', array_reverse(explode('-', $data)));

E Passando do formato brasileiro para formato americano:
implode('-', array_reverse(explode('/', $data)));

Links:
explode(): http://php.net/manual/pt_BR/function.explode.php
implode(): http://php.net/manual/pt_BR/function.implode.php
array_reverse(): http://php.net/manual/pt_BR/function.array-reverse.php
Answer: Para converter as datas a partir de qualquer formato que essa data venha, você pode usar a classe nativa do PHP DateTime.
Veja um exemplo:
<?php
 $data = '2014/07/17';
 $data_brasil = DateTime::createFromFormat('Y/m/d', $data);

 print_r($data_brasil->format('d/m/Y')); //17/07/2014


How to show that $\int \limits_{-\infty}^{\infty} (t^2+1)^{-s} dt = \pi^{1/2} \frac{ \Gamma(s-1/2)}{\Gamma(s)}$

Question: I want to compute the integral
$$
\int \limits_{-\infty}^{\infty} (t^2+1)^{-s} dt
$$
for $s \in \mathbb{C}$ such that the integral converges ($\mathrm{Re}(s) > 1/2$ I think) in terms of the Gamma function. If I'm not mistaken, the answer I'm looking for is
$$
\int \limits_{-\infty}^{\infty} (t^2+1)^{-s} dt = \pi^{1/2} \frac{\Gamma(s-1/2)}{\Gamma(s)}
$$
so my question is how to prove the above formula?
Motivation
Since people sometimes ask for motivation, I'm reading a paper in which the author gives the evaluation of a certain Fourier coefficient but doesn't show the computations, just states the result. I was able to reduce the problem of checking the author's evaluation of the Fourier coefficient to proving the above formula for the integral.
Thank you for any help.
Answer: Hint: Let $x=\dfrac1{t^2+1}$ and then recognize the expression of the beta function in the new integral.
But first, using the parity of the integrand, write $\displaystyle\int_{-\infty}^\infty f(t)~dt~=~2\int_0^\infty f(t)~dt$.
Comment: Exactly, was just working this out. Make sure to use the evenness of your original integrand.
Comment: Thank you Lucian, it worked perfectly.
Answer: $\newcommand{\+}{^{\dagger}}
 \newcommand{\angles}[1]{\left\langle\, #1 \,\right\rangle}
 \newcommand{\braces}[1]{\left\lbrace\, #1 \,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\, #1 \,\right\rbrack}
 \newcommand{\ceil}[1]{\,\left\lceil\, #1 \,\right\rceil\,}
 \newcommand{\dd}{{\rm d}}
 \newcommand{\down}{\downarrow}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}
 \newcommand{\fermi}{\,{\rm f}}
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}
 \newcommand{\half}{{1 \over 2}}
 \newcommand{\ic}{{\rm i}}
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}
 \newcommand{\isdiv}{\,\left.\right\vert\,}
 \newcommand{\ket}[1]{\left\vert #1\right\rangle}
 \newcommand{\ol}[1]{\overline{#1}}
 \newcommand{\pars}[1]{\left(\, #1 \,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\vphantom{\large A}\,#2\,}\,}
 \newcommand{\sech}{\,{\rm sech}}
 \newcommand{\sgn}{\,{\rm sgn}}
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}
 \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}
 \newcommand{\wt}[1]{\widetilde{#1}}$
$\ds{\int_{-\infty}^{\infty}\pars{t^{2} + 1}^{-s}\,\dd t
     =\pi^{1/2}\,{\Gamma\pars{s - 1/2} \over \Gamma\pars{s}}}$

\begin{align}&\color{#00f}{\large%
\int_{-\infty}^{\infty}\pars{t^{2} + 1}^{-s}\,\dd t}
=\ \overbrace{\int_{0}^{\infty}\pars{1 + t}^{-s}t^{-1/2}\,\dd t}
^{\ds{x \equiv {1 \over t + 1}\ \imp\ t = {1 \over x} - 1}}
=
\int_{1}^{0}x^{s}\pars{{1 \over x} - 1}^{-1/2}\,\pars{-\,{\dd x \over x^{2}}}
\\[3mm]&=\int_{0}^{1}x^{s - 3/2}\pars{1 - x}^{-1/2}\,\dd x
={\Gamma\pars{s - 1/2}\Gamma\pars{1/2} \over \Gamma\pars{s}}
=\color{#66f}{\large%
\root{\pi}\,{\Gamma\pars{s - 1/2}\over \Gamma\pars{s}}}\,,
\\[3mm]&\color{#c00000}{\large\Re\pars{s} > \half}
\end{align}
Answer: $\int_{-\infty}^{+\infty}(t^2 + 1)^{-s}dt = 2\int_{0}^{+\infty}(t^2 + 1)^{-s}dt = 2\int_{0}^{\pi/2}(\sec^2u)^{1-s}du = 2\int_{0}^{\pi/2}\cos^{2s-2}udu$
But,
$$
2\int_{0}^{\pi/2}\cos^{2m+1}\theta\sin^{2n+1}\theta d\theta = \dfrac{\Gamma(m+1)\Gamma(n+1)}{\Gamma(m+n+2)}
$$
Thus,
$$
\int_{-\infty}^{+\infty}(t^2 + 1)^{-s}dt = 2\int_{0}^{\pi/2}\cos^{2s-2}udu = \dfrac{\Gamma(s - 1/2)\Gamma(1/2)}{\Gamma(s)} =\sqrt{\pi}\dfrac{\Gamma(s - 1/2)}{\Gamma(s)}
$$


How can I get views_save_view($view) to return TRUE when using Drush?

Question: I have a script that calls various views API functions, namely views_save_view() or $view->save().
When using Drush 5 to run the script, these functions return false. However, when I run these with cron while logged into Drupal through the config, it works fine and everything executes as normal.
How can I get these to return true while using Drush?
I have feeling this is a permissions issue, but can't figure out how to get Drush to execute with the permissions it needs. This is a follow up question to here:
How can I run Drush as user 1 in version 5?
Also there is a somewhat related issue here:
http://drupal.org/node/1515616#comment-6312604
Comment: note: This is not just happening with views_save_view(). It's also happening with views_get_view(). I even tried to write a separate script and execute it with drush php-script rather than having the code in cron in a module (was calling drush cron). Nothing will save; views_get_view() returns nothing.
Answer: You can run a script as a user with the right command line option. Basically:
drush php-script YOURSCRIPTNAME.php --user=1
or --user=UID where UID is a valid drupal user ...
Comment: Unfortunately this did not work. For whatever reason, I cannot get views functions to work correctly with Drush even with the user changed. Thoughts?


Hints on showing that the sequence $\frac{1}{\#S_n}\sum_{l\in S_n}\mu\circ f^{-l},S_n\subset\mathbb{N}$ converges to $f$-invariant probability measure

Question: Let $X$ be a metric space and $\mu$ be any probability measure on $X$. Suppose that $f:X\to X$ is a continuous $\mu$-measurable function and that $(S_n)_n$ is a sequence of subsets of the natural numbers $\mathbb{N}$ such that $\# S_n\to\infty,n\to\infty$ for the counting measure $\#$.
Define the map $\alpha_n(B) := \frac{1}{\# S_n}\sum_{l\in S_n}\mu(f^{-l}(B))$ for $B\subset X$. It is then not hard to see that $\alpha_n$ is a probability measure on $X$.
Suppose then that $(n_k)_k$ is a subsequence of indices such that the subsequence $(\alpha_{n_k})_k$ converges in weak* topology to a probability measure $\alpha$ over $X$, i.e. for any bounded continuous function $g:X\to\mathbb{R}$ we have
$$\lim_{k\to\infty}\left|\int_Xg(y)d\alpha_{n_k}(y) - \int_X g(y)d\alpha(y)\right| = 0$$
where
$$\int_Xg(y)d\alpha_{n_k}(y) = \frac{1}{\# S_{n_k}}\sum_{l\in S_{n_k}}\int_X(g\circ f^l)(y)d\mu(y)$$
as one can verify easily.
(Extra assumption:) Take it as granted that if $f:X\to X$ is a continuous map then its pushforward map $f_*\mu(B) := \mu(f^{-1}(B)), B\subset X$ is continuous in weak* topology. I.e. if $\mu_n\to\mu$ in weak* as $n\to\infty$ then $\lim_{n\to\infty}f_*(\mu_n) = f_*\mu$.
(Problem:) I want to show that the prior limit measure $\alpha$ is $f$-invariant, that for any $\alpha$ measurable subset $B\subset X$ we have $\alpha(B) = \alpha(f^{-1}(B))$.
(Solution attempt/thoughts:)
Let $g:X\to \mathbb{R}$ be a fixed bounded and continuous function. By continuity of $f_*$,
$$f_*\alpha = f_*\left(\lim_{k\to\infty}\alpha_{n_k}\right) = \lim_{k\to\infty}\frac{1}{\# S_{n_k}}\sum_{l\in S_{n_k}}\mu\circ f^{-l - 1}$$
Therefore I would want to conclude that the difference
$$I := \left|\frac{1}{\# S_{n_k}}\sum_{l\in S_{n_k}}\int_X(g\circ f^{l})(y) - (g\circ f^{l+1})(y)d\mu(y)\right|$$
can be made arbitrarily small after some sufficiently large $k$. But since nothing guarantees that $l\in S_n\implies l+1\in S_n$ I have no idea how to relate these two quantities of the integrand.
One could use triangle inequality and the fact that $\alpha_{n_k}$s are probability measures to show that
$$\left|\int_X(g\circ f^{l}) - (g\circ f^{l+1})(y)(y)d\mu(y)\right|\leq 2\sup_{y\in X}\left|g(y)\right|$$
for any $l\in S_n$. But without additional information you would get this same bound for every summand occurring in $I$ and so the averaging is lost.
What to do? I am not necessarily looking for a full-blown answer, but I'll appreciate any help/hints that you might be able to give. Thanks!
Comment: I believe you should assume $X$ is a locally compact Polish space if you want any old Borel measure $\alpha$ to be uniquely characterised by the integrals $\int g\d\alpha$ for $g\in C_c(X)$ (in polish space, all Borel measures are Radon measures, and then the Riesz-Markov-Kakutani representation theorem takes over)
Answer: I feel there are some assumptions missing here. For one thing, if you take say $$X = \mathbb{R}, f(x) = -x$$
and all $S_n$ to be subsets of even number, then
$$\alpha_{n_k} = \mu,$$
which converges to $\mu$, but $\mu$ is not necessarily $f$-invariant.
I will update this with a solution once a clarification is made.
Comment: I double checked my reference text, Foundations of Ergodic Theory by Viana, p. 48, ex. 2.2.1., and I am confident that I've included all explicit assumptions made by the authors. I can't say for sure whether the authors have missed something.
Comment: You missed the assumption that $S_n$ are intervals $\cdots$. With this assumption your argument simply works.
Comment: Apparently it's the small things that can suck up most of the time spent on a problem...