How to determine what group a Galois group is isomorphic to

Question: Consider $x^{4}-2=(x+\sqrt[4]{2})(x-\sqrt[4]{2})(x+i\sqrt[4]{2})(x-i\sqrt[4]{2}) \in \mathbb{Q}[x]$. Let $K=\mathbb{Q}(\sqrt[4]{2},i)$ be the splitting field of $x^{4}-2$. Since $K$ is a splitting field and we are in characteristic 0, it follows that $K/\mathbb{Q}$ is Galois. Finally, $[K\colon\mathbb{Q}]=8$.
I want to compute the Galois group $K/\mathbb{Q}$. Since the extension is Galois, there are 8 elements in this group. It turns out that this group is isomorphic to the dihedral group of order 8 (I've seen examples of this but don't have a reference).

What steps would I take to reach the conclusion that this group is the dihedral group?

Specifically I know that each automorphism of the Galois group permutes the roots, but I don't see how to make the connection that these elements are the same as the dihedral group of order 8. I would appreciate a detailed analysis because I think this would allow me to apply these techniques to many other problems in Galois theory. Thanks.
Comment: \root n\of a also produces $\root n\of a$.
Comment: @Mariano, I'm a PlainTeX kind of guy. Perhaps this comment thread isn't the place to discuss it, but I'd like to know why Plain constructs should be avoided here - they seem to be supported.
Comment: `\sqrt[n]{a}` produces $\sqrt[n]{a}$.
Comment: You can find in Lang's book on *Algebra* the study of extensions constructed by adjoining an $n$th root such as your $K/\mathbb Q$, and in particular the determination of their Galois groups, but if I recall correctly he only goes into detail for the case in which $n$ is odd, which is simpler.
Comment: @GerryMyerson, that's really a `plaintex`-ism, which should probably be avoided in LaTeX sources.
Comment: @Gerry: Some Plain TeX constructs interact badly with LaTeX constructs. In addition, LaTeX has many built-in improvements on plain TeX constructs, particularly in terms of spacing.
Comment: @Arturo, thanks.
Answer: Since $x^4-2$ is irreducible over $\mathbb{Q}$ (Eisensein's Criterion at $p-2$, for example), the Galois group is transitive on the four roots. There is an automorphism that maps $\sqrt[4]{2}$ to $i\sqrt[4]{2}$; call it $\rho$. This map either maps $i$ to $i$, or $i$ to $-i$.
If it maps $i$ to $i$, then consider $\sigma$, complex conjugation. We have that $\sigma\rho$ maps $i$ to $-i$ and $\sqrt[4]{2}$ to $-i\sqrt[4]{2}$, whereas $\rho\sigma$ maps $i$ to $-i$ but $\sqrt[4]{2}$ to $i\sqrt[4]{2}$. So $G$ is not abelian.
If $\rho$ maps $i$ to $-i$, then $\sigma\rho$ maps $\sqrt[4]{2}$ to $-i\sqrt[4]{2}$ and $i$ to $i$. Taking $(\sigma\rho)^3$ we obtain a map that sends $i$ to $i$ and $\sqrt[4]{2}$ to $i\sqrt[4]{2}$, so we are back in the previous case. So either way, $G$ is not abelian.
That means that it is either dihedral, or the quaternion group of order $8$ (the only nonabelian groups of order $8$). But in the quaternion group, the only element of order $2$ is central (it is $-1$), whereas complex conjugation, which is of order $2$ in the Galois group, is not central, as we just saw. That means that the Galois group must be the dihedral group of order $8$. Alternatively, in the quaternion group there is a single element of order $2$; but $G$ has at least two: complex conjugation and $\rho^2$. So $G$ must be dihedral, not quaternion.
Explicitly, our map $\rho$ that sends $\sqrt[4]{2}$ to $i\sqrt[4]{2}$ and $i$ to $i$ is of order $4$; complex conjugation $\sigma$ is of order $2$; now note that $\sigma\rho=\rho^3\sigma$ (both map $i$ to $-i$, and $\sqrt[4]{2}$ to $-i\sqrt[4]{2}$). This gives you explicitly the dihedral structure: $G$ contains $\langle \sigma,\rho\mid \sigma^2=\rho^4=1,\ \sigma\rho=\rho^3\sigma\rangle$, which is of order $8$, so $G$ is this group, which is the dihedral group of order $8$.
Answer: You don't say whether you know what the automorphisms are. If you do, you should be able to find automorphisms $f$ and $g$ with $f^4=1$, $g^2=1$, and $fg=gf^{-1}$, and that (together with knowing that $f$ and $g$ generate the group) is a presentation of the dihedral group.


How do you manage service account credentials (passwords)?

Question: In a Windows environment how do you address the following issues with service accounts?

Regular Password changes - with single service accounts used on multiple machines how do you regularly change passwords without significant outage periods?  Do you tend just to never change them?
Keeping track of passwords - by necessity multiple people need to know these, how do you record the passwords whilst keeping them reasonably secret?
To what point do you use the same account across multiple machines / services?  How do you track what account is being used where?  Any tools to help with this?
Has anyone found any good resources for appropriate minimum permission settings for common service account requirements for applications such as SQL Server, Sharepoint etc.
Comment: I guess point 4 is a little off topic.  My main concern is point 1.  I can't see how you can change the passwords without having an outage.
Comment: Even if point 4 is off topic, I'd still love to follow that thread. I found this question while looking for how to prevent interactive logins with a service account. I thought there was a GPO setting, but I haven't found it yet.
Answer: Switching to Server 2008 R2 all around ^^ (ok, maybe not - but thought I should mention the Managed Service Account and Virtual Account features of it that promises to resolve this mess)
Comment: Thanks for that, I hadn't noticed that in the features list of R2.  I'm a big Server 2008 (R1) fan.  I was a little disappointed with the stability and performance of 2008 R2 beta compared with Win7 RC - let's hope it's good when they release it
Answer: Many of our customers use Secret Server to manage their service accounts.
It can automatically discover where your service accounts are used (will scan your network for usages) and then these Windows Services can be added as a "dependency" for the credential.  An expiration schedule can be set (say every 30 days) and then it will automatically generate a new random password for the AD service account and change all the places it used (even stopping and restarting the Windows Services).  Secret Server also supports IIS Application Pool users and Windows Scheduled Tasks as "dependencies".
Get a free 30 day trial here: http://www.thycotic.com
Answer: Joel,
We use a third party application to manage the rotation of passwords for service accounts. The app tracks the passwords, creates new ones, and offers a vault so that you can access the passwords if and when necessary.
We try to reuse service accounts when possible and as part of the account creation process we have a form that people need to complete. when the form is submitted it is saved and the account that was created gets saved with the form. that way, if we need to know who uses the account, or why it was created, we can research. we also make certain the manager field in AD is filled in correctly and managers are assigned the task of know what service accounts they are responsible for.
MSDN would have a wealth of information regarding the minimum permissions required for common service account settings. As always, how you configure those settings depends upon the needs of your environment.
Comment: Any idea what third party tool you use for this?
Comment: sure, http://www.cyber-ark.com
Answer: i would recommend passgen.exe Download Info Here
Just go through its accompanying document. It gives precise scenario of changing password on multiple computers and how easy it is to keep them unique and complex.


JavaScript function works perfectly but giving error

Question: function scrollBottom()  {
    var myDiv = $("#configComponent");
    myDiv.animate({
        scrollTop: $(".drpMenuDiv").position().top
    }, 1000);
}

It gives following error:
TypeError: $(...).position(...) is undefined
scrollTop: $(".drpMenuDiv").position().top

Comment: The code itself looks fine, although you need to animate `scrollTop` on the `body` or `html`. Can you set up a http://jsfiddle.net which demonstrates the problem.
Comment: Or post your HTML, please
Comment: Can we see your HTML which contains that div?
Comment: @SubodhGhulaxe: It would fail on the previous line if he/she hadn't.
Answer: I suspect the error you're getting (from Firefox) is:
$(...).position(...) is null
(null, not undefined). (From Chrome it would be Cannot read property 'top' of null.)
That tells you that there are no matches for the selector .drpMenuDiv, so position() is returning null.
If that's possible, you want a guard in there:
function scrollBottom()  {
    var myDiv = $("#configComponent");
    var menuDivPos = $(".drpMenuDiv").position();
    if (menuDivPos) {
        myDiv.animate({
            scrollTop: menuDivPos.top
        }, 1000);
    }
}

Or alternately, animate to some default position if there's no menuDiv:
function scrollBottom()  {
    var myDiv = $("#configComponent");
    var menuDivPos = $(".drpMenuDiv").position();
    myDiv.animate({
        scrollTop: menuDivPos ? menuDivPos.top : 0
    }, 1000);
}

That example animates to 0 if there are no matches.
Comment: @user3690332: That tells you there's no match for the selector the first time, and that there *is* a match for the selector the second time (between the two, you've added at least one element with that class, or added that class to at least one existing element).
Comment: so what will be solution for that ?
Comment: @user3690332: Check whether there's a match. I've added a couple of examples.


Drupal 7 - access to page content in template.php

Question: In Drupal 7 I'm trying to access the body field of a page from template.php. I want to find a keyword in the text and then send subsequent text to a separate variable so that I can format it in page.tpl.php
I can access the node using
    $vars['node']
but can't find a way of accessing the content part of the node.
I can access the content in page.tpl.php using:
    $node->body[$node->language][0]['value']
but cant use the same or similar syntax in template.php
Answer: In page.tpl.php the content of the page is available in $page['content']. It seems that your are mixing two different concepts here: pages, any page on the site (including administration page, taxonomy terms page, and other not directly editable pages) and nodes, editable content. This can be rather confusing as a default Drupal installation provides a page content type. So you end up with page nodes, which are nodes of a the page content type.
The layout of the content of a page displaying a node, is handled in the node.tpl.php template. In this template, the body of the displayed node is available in $content['body'].
If you really need to access a field (handled using the Field API) of the node object ($node) from the page preprocess function in your template.php, you can use:
function THEME_preprocess_page(&$variables) {
    $node =& $variables['node'];
    $value = field_get_items('node', $node, 'FIELDNAME);
}


How can Machine Learning approaches be applied to Natural Language Processing?

Question: I am trying to do a paper about the Machine learning been applied in NLP. Can you guys please suggest me applications that have already used the Machine learning with the NLP?
Comment: This question is too broad IMHO. As you don't seem to know where to start, I am assuming your "paper" is simply about the state of the art (not about actual research on the topic). If this is homework for your University (I see you are an student), then it is probably for you to search and read different papers and come up, yourself, with an idea of the current state of the art. ;-)
Comment: I am trying to get ideas about how to start my project, anyway thank you for your comment @Peque
Answer: If you want something generic you can use this tutorial: http://www.cs.columbia.edu/~mcollins/papers/tutorial_colt.pdf
It is probably not the more recent information but you could find it useful if you start to learn ML methods for NLP.
As it is mentionned in this tutorial, ML methods are generally linked to the NLP task (Information Extraction, Machine Translation, etc.).
IBM Watson project is an example of platform that uses NLP and ML.
Comment: Thank you very much, it helps me a lot
Answer: The list is broad since machine learning is becoming more and more mainstream.
Regarding text, images and video, a good list of APIs would be:
AT&T Speech, IBM Watson, Google Prediction, Wit.ai, AlchemyAPI, Diffbot and I guess Project Oxford as well.
Hope it helps.


Building a query for a reservation database

Question: I have a database which holds car reservations. I'm trying to write a query that will give me enough information to fill a view with the following properties:

Prior months (up to 3) i.e. in January the rows would be Dec, Nov, Oct
The location with the most reservations that month.
The number of reservations at that location, that month.
The total number of hours reserved at the location that month.

The reservation tables is laid out as follows:
ResID, PickUpDateTime, ReturnDateTime, LocationName, VehicleSno

I've been trying for two hours now to work it out, but I'm stumped. I have the COUNT(*) statement to get the number of hours from each location, but it's a little off because it's not limited by the month it's supposed to pertain to. :/ I really hate dates.
SELECT
    MONTH(PickupDateTime) AS Month,
    LocationName as Location,
    COUNT(*) AS NoOfRes,
    TIMESTAMPDIFF(HOUR, PickUpDateTime, ReturnDatetime) AS Hours
FROM
    Reservation
GROUP BY
    Location
ORDER BY
    NoOfRes DESC

Comment: *sniff*.. *sniff* ... I smell homework ;)
Comment: Please include the code you've tried so far.
Comment: I smell work, work.
What I have, thought it is way off...
`CREATE VIEW Report2 AS SELECT LocationName as Location, COUNT(*) AS NoOfRes,     TIMESTAMPDIFF(HOUR, PickUpDateTime, ReturnDatetime) AS Hours FROM Reservation GROUP BY    Location ORDER BY NoOfRes DESC`
Comment: If you are facing difficulties with the month part: To get the month of a date, you can use the [MONTH()](https://dev.mysql.com/doc/refman/4.1/en/date-and-time-functions.html#function_month) function.
Comment: Please edit the question and add the code there, formatted nicely.
Comment: what did you expect to show if a car was booked out in Feb and returned in March ? should the hours be split between both months or all all into the first ?
Comment: There is a 48 hours limit, but that is a good question... hmm.. I suppose I would tick it to Feb, as that is when it was technically rented.
Answer: To get the month of a date, you can use the MONTH() function.
So, to get the The location with the most reservations for the month of Feb,
select LocationName, count(*) num_reservations
  from reservation
 where month(PickUpDateTime) = 2 --This can be parameterized if needed
 group by LocationName
 order by num_reservations desc

Comment: Thank you. A step in the right direction. I suppose I should just break the problem into multiple queries. Now, with this, I can make another query to calculate the total of hours registered that month.


Finding correlation between two groups in survey

Question: I have a friend who asked me for help in statistics.  I study mathematics, but have never dealt with statistics in all of my years of study, so I don't want to give them the wrong information.  Either way, here's what is needed.
They have a group of $n$ participants in a study.  Some participants have property $A$, some have property $B$, and some have both.  What they want to know is the best way to measure if there is a correlation between those with property $A$ and those with property $B$.  The hypothesis is that if something is to have property $A$, they are more likely to have property $B$.  What is the best way to test this?
Thank you in advance for your help.
Answer: You should use the Chi Squared test.
Create a $2$x$2$ table with colums (Not A, A) and rows (Not B, B)
You can see the rest at this link, the calculations should be fairly fast for a $2$ by $2$.
https://www.mathsisfun.com/data/chi-square-test.html
Comment: The gist of this test is that if there is no correlation, then the results should be perfectly spread out
Comment: Let's say that we have 50 adult women and 20 girls.
Comment: We suppose that they have the same interests (or not, we're here to find out)
Comment: We ask them if they like bicycling
Comment: 20 adults say yes and 30 say no
Comment: 8 kids say yes and 12 say no
Comment: in this case, it was the same proportion across women and children, so we can't infer any correlation between age and liking biking
Comment: our chi^2 statistic would be 0, and this would mean that there is no proven correlation
Comment: now, say 16 girls were to say and 4 say no. that is a hugely different proportion between women and girls, and the chi^2 statistic would be large this time
Comment: this would lead us to a low p value. the p value is the probability that there is no correlation. if there's a low chance that there's no correlation, there most likely is a correlation
Comment: usually, if this p value comes out to below 0.05, we cannot deny a possible correlation
Comment: Thank you so very much for your help!  This has made my friend's life easier.
Answer: You need to find the correlation coefficient of the properties A and B. First find the covariance: E(AB)-E(A)E(B). Then find the Std. Dev.  of each. Use the formula $\frac {Cov(A,B)}{\sigma_A \sigma_B}$. To get correlation coefficient. It lies between -1 and 1. Closer to 1 means better correlation. Closer to zero implies no correlation.
Note: E(A) is expected value of A
Comment: Thank you for your response.  What they want to know is if this corresponds to a well-known statistical test, or if there is a statistical test that best describes what you're recommending?


Errors in code. I do not know what category it falls under

Question: **In the new code I added. I don't think there is any problem but the program stopped after I entered the code of the item. What can I do to fix this???
void cart()
 {
int code, amount;
float weight, price, total_weight, total_price1;
char product[20];

switch(code)
{

case 1:
    product= "Cement";
    weight=20;
    price=18;
    break;

case 2:
    product="Concrete";
    weight=30;
    price=25;
    break;

case 3:
    product="Ceramic Tile Floor";
    weight=0.1;
    price=2.2;
    break;

case 4:
    product="Foam Insulation";
    weight=0.1;
    price=2.2;
    break;

case 5:
    product="Fibre-inforced Cement";
    weight=35;
    price=50;
    break;

case 6:
    product="Thick Glass Panel";
    weight=20;
    price=50;
    break;

case 7:
    product="Thin Glass Panel";
    weight=10.5;
    price=30;
    break;

case 8:
    product="Iron Beam";
    weight=5;
    price=10;
    break;

case 9:
    product={"Iron Rod";
    weight=1;
    price=5;
    break;

case 10:
    product="Plaster Boards";
    weight=10;
    price=15;
    break;

case 11:
    product="Quarry Tiles";
    weight=0.5;
    price=3;
    break;

case 12:
    product="Steel Beam";
    weight=5;
    price=10;
    break;

case 13:
    product="Wooden Boards";
    weight=3;
    price=5;
    break;
}

printf("\nPlease enter the amount desired:");
scanf("%d", &amount);
total_weight=weight*amount;
total_price1=price*amount;

printf("So far, the total weight and total price in the cart is %f kg & RM%0.1f", total_weight, total_price1);
}

The language I'm using is C.
Above is the code for my program (not the whole thing). The problem is:
.c|42|error: incompatible types when assigning to type 'char[20]' from type 'char *'|

this error goes for all the lines with product. Did I do the array thing wrong? I want to set variable product as strings and with each case the product is different. How should I declare the variable product in the function?
Also, how can I loop it so that if the user wants, he can add another "product" and its amount to the cart. Then, add the weight and price to total weight and price. And maybe use sentinel to stop entering products?
Lastly, is there a way to simplify what I've done?
Thanks in advance.
Here is the edited code:
    void cart()
{
int code, amount;
float weight, price, total_weight, total_price1;
char * product;

printf("\nEnter the code of the desired product:");
scanf("%d", &code);

switch(code)
{

case 1:
    strcpy(product, "Cement");
    weight=20;
    price=18;
    break;

case 2:
    strcpy(product, "Concrete");
    weight=30;
    price=25;
    break;

case 3:
    strcpy(product, "Ceramic Tile Floor");
    weight=0.1;
    price=2.2;
    break;

case 4:
    strcpy(product, "Foam Insulation");
    weight=0.1;
    price=2.2;
    break;

case 5:
    strcpy(product, "Fibre-Inforced Cement");
    weight=35;
    price=50;
    break;

case 6:
    strcpy(product, "Thick Glass Panel");
    weight=20;
    price=50;
    break;

case 7:
    strcpy(product, "Thin Glass Panel");
    weight=10.5;
    price=30;
    break;

case 8:
    strcpy(product, "Iron Beam");
    weight=5;
    price=10;
    break;

case 9:
    strcpy(product, "Iron Rod");
    weight=1;
    price=5;
    break;

case 10:
    strcpy(product, "Plaster Board");
    weight=10;
    price=15;
    break;

case 11:
    strcpy(product, "Quarry Tiles");
    weight=0.5;
    price=3;
    break;

case 12:
    strcpy(product, "Steel Beam");
    weight=5;
    price=10;
    break;

case 13:
    strcpy(product, "Wooden Board");
    weight=3;
    price=5;
    break;
}

printf("\nPlease enter the amount desired:");
scanf("%d", &amount);
total_weight=weight*amount;
total_price1=price*amount;

printf("So far, the total weight and total price in the cart is %0.2fkg & RM%0.2f", total_weight, total_price1);

}
But then the following message appears:
.c|45|warning: 'product' may be used uninitialized in this function [-Wuninitialized]|

and after entering any of the code numberss my program stopped working.
Also, can I know how to loop the program so the user can keep entering code of product and amount until he wants to stop?
Okay. So, I fixed it with the following code:
char * product="Unknown";

but my program still stopped working. It wont display the total  weight and price.
Comment: You might want to address this first: `code` is indeterminate in this function. It is never assigned a value, yet is evaluated in the switch check, and invokes undefined behavior as a result. Regarding your invalid assignment, how about just use `const char *product = "Unknown";` and leave the rest alone (apart from fixing the previously mentioned indeterminate code and fixing the typo Samoth is pointing out).
Comment: typo on case 9 ? `product={"Iron Rod";` remove `{`
Comment: use `strcpy(product, "string");` and case 5 too long.
Comment: @WhozCraig So, would the 'code' issue be fixed if I scan for the code first? Also, can you explain how 'const char *product = "Unknown";' works? Do I put it above with the declarations? What is "Unknown" referred to?
Comment: Its a pointer to constant char data. The "unknown" is the default value if it is never assigned in the switch below (which is never accounted for, but thats another issue, you have other variables that are in the same boat). Pointers can be on the left side of an assignment statement; arrays cannot, as the answers below are telling. Doing as i described you don't need the `product[]` *array* in the first place, but it sounds like you need to spend some time in a C-text learning about pointers first.
Answer: In C you can't assign a constant string to a char []. For example
product= "Cement";

is incorrect. You should use
strcpy(product, "Cement");

Answer: Change
char product[20];

to
const char * product;

Comment: Is this called a pointer? I'm not supposed to put in anything I didn't learn about yet, which is pathetic but rules are rules (maybe)
Answer: Do take care that you initialized product variable to be sufficiently large to be atleast equal to length of data + 1 (for null char) if you are to use string operations. I said so because you have declared product[20] but length of "Fibre-inforced Cement"; is > 20


In basketball, is one allowed to purposefully get the ball out-of-bounds off an opponent?

Question: Imagine the scenario of "accidentally" dribbling the ball into an opponent's foot, and the ball gets kicked out of bounds. Or, in an even more extreme case, "passing" (or throwing) the ball out of bounds while barely grazing an opponent. In the most extreme case, I toss the ball into an opponent's head, and it flies out of bounds.
These could result in an out-of-bounds by the opposing team, allowing one to reset the shot clock, for example. Is there any rule in basketball (or the NBA) that prevents these kinds of schemes? Or are there any other factors that stop these kinds of schemes (e.g. they're not consistent, or audiences/sponsors might get angry)?
Answer:
These could result in an out-of-bounds by the opposing team, allowing one to reset the shot clock, for example.

This is an incorrect assumption.  The defensive team would have to gain possession to reset the shot clock.  Deflecting the ball out-of-bounds would not do it.  So the tactic is only useful in a case where you might otherwise lose possession (such as about to fall out of bounds).  It is allowed, but you would lose time handling the ball and have to risk a throw-in.
Rule 7, Section IV, b

b. The shot clock is never reset on the following:

Defensive player is the last to touch the ball before going out-of-bounds....
Answer: Sure, there's no rule (see the rulebook) against throwing the ball at your opponent, and in falling-out-of-bounds situations it's not all that uncommon to see players try to toss the ball at their opponents' arms or legs if they don't have any other way of saving the ball.  It's possible that this could be penalized under "unsportsmanlike conduct" if it were done in a malicious or dangerous way (your example of throwing at the player's head).
However, most of the time, throwing the ball at your opponent is called a turnover.


Why does not Thread.sleep() work in Action Performed?

Question: public void actionPerformed(ActionEvent e) {
        String sp1="Player 1's turn. ";
        String sp2="Player 2's turn. ";
          System.out.println("Mouse entered for rating " + index);  //helps me track the cards
           ori=new ImageIcon(getClass().getResource(index+1+".png")); //set the image to the card

        ori.setDescription("ori");  //It's weird that I cannot directly flip the card, so I used this method to flip the cards.
        tail.setDescription("tail");//http://stackoverflow.com/questions/13557561/the-method-about-imageicons-does-not-work

        if (((ImageIcon) bt[index].getIcon()).getDescription()=="ori")
            bt[index].setIcon(tail);
         else
            bt[index].setIcon(ori);

        count++;

       System.out.printf("Action Performed %d times \n",count);
         if(count==1){  //if the card is clicked for once, the card should not flip and the index is stored in record.
           record=index;
           countS++;

       }
       String turnS=Integer.toString(countS);//parse the int and printout the turn
     //  text3.setText(sp1+"This is turn "+turnS);
       if(count==2){
           int match1=record/4;   //Since every four cards have the same rank, I used this to get the rank very easily
           int match2=index/4;
          if(match1==match2&&record!=index){  //compare the two cards clicked
              p1++;
              score1=Integer.toString(p1);
              text1.setText("Player 1: "+score1);  //display the score
              text3.setText(sp2+"This is turn "+turnS);
              bt[index].setEnabled(false);//remove the cards that match
              bt[record].setEnabled(false);
          }
          if(record==index){
              text3.setText(sp2+"This is turn "+turnS);//designed for the situation that the user clicks the same card
          }
          if(match1!=match2){//designed for the situation that the two cards do not match
           //time.schedule(taskFlip1,500);//delay the flip so that the user can see the cards
           //time.schedule(taskFlip2,500);

              try{   **//This part is problematic!**

                  Thread.currentThread().sleep(4000);
                  flip(index);
                  flip(record);

                }
                catch(Exception ie){

                }
              }
          text3.setText(sp2+"This is turn "+turnS);

       }

When I click on the button, the button is supposed to change the ImageIcon. It works fine without the sleep. But after I add sleep, when I click on the button, the program pauses without changing the ImageIcon! Can you tell me why? Thank you!
Answer: The action is executed by the very thread which also does handle the drawing. You block this thread. You see nothing. Game over.
This is the reason why YOU SHALL NOT BLOCK NOR DELAY THE EVENT-DISPATCHER THREAD.
Searching for the term "Event Dispatcher Thread" and "blocking" you find plenty of stuff explaining the gory details.
Answer: ActionPerformed is run in the event-dispatcher thread. Sleeping in there will stop the UI from updating.
You can use a Swing Timer instead to delay an action.
Answer: The actionPerformed() method runs in the event dispatching thread. So does the repaint system. If you sleep, you are deferring painting, and everything else. You should never sleep in this thread. If you want a deferred paint, use SwingWorker or javax.swing.Timer to start a deferred task.


Set notBefore/notAfter for Dogtag Certificate Profile / XML Request

Question: I cannot figure this one out:

Which ClassID do I have to use to add certificate validity inputs to the profile (is there an overview somewhere)?
Once this is done: How do I add this in a request?

Here's a snippet of the Certificate Profile:
<code><Input id="i1">
    <ClassID>certReqInputImpl</ClassID>
    <Name>Certificate Request Input</Name>
    <Attribute name="cert_request_type">
....
<Input id="i2">
    <ClassID>???????</ClassID>
    <Name>Validity Constraint</Name>
    <Attribute name="notBefore">
        <Descriptor>
            <Syntax>string</Syntax>
            <Description>Not Before</Description>
        </Descriptor>
    </Attribute>
    <Attribute name="notAfter">
        <Descriptor>
            <Syntax>string</Syntax>
            <Description>Not After</Description>
        </Descriptor>
    </Attribute>
</Input>
</code>
Thanks a lot in advance,
Chris
Answer: I'm closing this, as it seems that unfortunately there's no interest from the maintainers to continue supporting dogtag as a software itself - only as an underlying service for the IPA (freeipa.org).


Creating relational Tables in Ms Access

Question: I have to change my first question to the following:
I have 3 tables:
Clients,
Gender,
Race
Clients:
ClientID long integer
GenderID long integer
Gender   short text
RaceID   long integer
Race     short text

Gender:
GenderID long integer
Gender   short text

Race:
RaceID  long integer
Race    short text

What should I do in order to be able to modify data in the main table Clients -so they'd be changed according to content in Race / Gender tables
For example:
Gender table:
GenderID  Description
       1  Male
       2  Female

Clients table:
ClientID GenderID  Gender  DOB
      11       2   Female  1/1/1977
      12       2   Female  1/2/1970
      13       1   Male    1/4/1969

So, if I'd modify for example, ClientID "13" Gender to "Female" instead of the current one "Male", so that the GenderID would be automatically changed to "2"?
(And no other number would be allowed for that GenderID)
Or - if I'd modify ClientID from 1 to 2, I want the Gender to be changed to "Female"
Thank you, again
Comment: You don't have a natural key in the client table.
Answer: You should not use both a character-field, Race, and a foreign-key field, RaceID, in your schema design: you should only use the latter, RaceID.
You shouldn't, and-d-d-d, you don't need to.
Your reports and so forth would then be based upon a query which JOINs to all three tables – displaying the Race.Race value ("White") but never the (meaningless ...) RaceID integer.
Your input-fields would be combo-boxes which query (say) the Race table to find possible values, binding on the RaceID field.
The Clients table contains foreign-key numbers which the end-user never actually sees.  Queries (and combo-box parameters) are used to reference the corresponding strings.
You should also use Referential Integrity constraints to ensure that Clients.RaceID, if it is not NULL, must be a value in the Race table.
Comment: It's not clear to me...   Do you mean, in my main Clients table i should only use RaceID, ClientID  but not Race and Client fields?  And, when I'll join all 3 tables - I'll use the Race , Client from the Race and Client tables?
Comment: Also, if I'll build the query combining all 3 tables, and then - will create the form based on that query (creating a Form is my main goal) then - I won't be able to modify that form. But I need to be able to enter data and to modify my resulting form
Comment: You base your form on your Client table. You add list boxes to your form to select gender and race. I suggest reading up on MS Access a bit before you start, this is all basics you should understand before starting.
Comment: What question is this answer answering?
Comment: @Mike Robinson  Thank you! Your explanation (with some MsAccess relational databases video) helped. It works perfectly after I changed relations & more carefully designed my tables

Creating relational Tables in Ms Access


Is there an existing Java class to convert data stored little-endian to integers by offset and length?

Question: I have a data file that is made up of various fields in little-endian order. I know what the offset and length are for each of the various fields. Is there an existing Java class that will convert by offset and length to an integer? For example: 17 00 00 00 53 43 43 41 11 00 00 00 AA 35 00 00. Bytes 1 thru 4 (17 00 00 00) is 0x00000017.
Comment: It's a file of bytes. There aren't spaces between the bytes (that 17 00 00 00 is really 17000000). What I was hoping for is a method that would return an integer if I passed it the input, offset and length.
Answer: Guava provides the LittleEndianDataInputStream class which can be used to retrieve values in little endian order.
Answer: You can do that with a java.nio.IntBuffer or java.nio.ByteBuffer, in association with a java.nio.channels.FileChannel to read the data.
Answer: You should try to read it as it is. Get block of 4 bytes and treat them as integers. I'm sure JVM already treats numbers little endian (as far as I know, all Intel/amd are so).
Comment: The javadoc for `DataInput.readInt()` explicitly states that the data is read in big-endian order.
Answer: If your file is a file of raw bytes you can use ByteBuffer to read the file in little endian mode, and then use asIntBuffer() to read out the ints through an IntBuffer. If you need to navigate the file, you can use srcChan.position(targetPosition); to skip to your next "field".
try (RandomAccessFile srcFile = new RandomAccessFile("data/data.bin", "r");
     FileChannel srcChan = srcFile.getChannel();)
{
    //    Careful with these casts if you have large files - channel size is a long
    ByteBuffer ib = ByteBuffer.allocate((int)srcChan.size());
    ib.order(ByteOrder.LITTLE_ENDIAN);
    srcChan.read(ib);
    IntBuffer fb = ((ByteBuffer)ib.rewind()).asIntBuffer();
    while (fb.hasRemaining())
        System.out.println(fb.get());
}

Output:
23
1094927187
17
13738
If however you have a text file with a series of space delimited hex strings (the file format is unclear from your question) you'll have to add a bit of trickery to read that in, but once it is in you can use ByteBuffer in little-endian mode to read out the integers again.
The general process would be:

inputString.split(" ")
convert each element of that String array into a byte[]
use ByteBuffer.wrap to wrap the resulting byte[] and walk through the ints

It probably (not compile time tested) looks something like the below (which doesn't use an IntBuffer, just to show an alternative method):
String input = "17 00 00 00 53 43 43 41 11 00 00 00 AA 35 00 00";
String[] source = input.split(" ");
byte[] sourceBytes = new byte[source.length];
for (int i = 0; i < source.length; i++) {
    sourceBytes[i] = (byte)Integer.parseInt(source[i], 16);
}
ByteBuffer bb = ByteBuffer.wrap(sourceBytes);
bb.order(ByteOrder.LITTLE_ENDIAN);
while (bb.hasRemaining())
    System.out.println(bb.getInt());

The output is the same as for the first approach.
Comment: I don't mind the downvote, but would love some feedback
Comment: There is no evidence that the file consists of ASCII hex strings.
Comment: @EJP. Fair enough. There's no evidence that it's made of bytes, either, but you assume it is in your answer.
Comment: Yes there is. Otherwise 'bytes 1 through 4' wouldn't make sense.
Comment: @EJP. The OP has 1 experience point. A novice programmer may well refer to bytes in a string. Hence I have now asked the question to the OP directly so as to clarify the question.
Comment: 'Bytes 1 through 4' of this data as a space-delimited hex string would be '17 0'. And where on earth would he get such a file in the first place? You're inventing difficulties where they don't exist.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/69933/discussion-between-andy-brown-and-ejp).
Comment: The input isn't really space-delimited, sorry for the confusion. ByteBuffer and srcChan.position(i) look like they'll do what I need done. Thanks much.


Estimating the size of the kernel of the squaring function in the symmetric group $S_n$

Question: I'm considering the symmetric group $S_n$ on $n$ letters, and a function $f: S_n \rightarrow S_n$ defined as $f(x)=x^2$. I'm interested in the kernel of this function, $G = \ker f$, which is the set of all permutations in $S_n$ for which $x^2$ is the identity permutation.
I would like to know the order of magnitude of the size of $G$. I don't need the exact size, but rather a rough estimate would be sufficient. Specifically, I'm considering the case where $n=256$. Would it be feasible to enumerate all elements of $G$ in this case?
Comment: If x^2 is identity then x is a product of disjoint transpositions. A count of those would not be difficult to find.
Comment: @coffeemath, yes, but I have difficulty to estimate it.
Comment: vfenux--- citadel links the exact count in comment.
Answer: This is the number of involutions, counted by the telephone numbers / involution numbers $I_n$, A000085 on OEIS. General results imply that it has exponential generating function
$$\sum_{n \ge 0} \frac{I_n}{n!} t^n = e^{t + \frac{t^2}{2}}$$
which gives a closed-ish form
$$I_n = \sum_{k=0}^{\lfloor \frac{n}{2} \rfloor} \frac{n!}{(n-2k)! 2^k k!}$$
(this can also be proven more directly) as well as an asymptotic
$$I_n \sim \frac{1}{\sqrt{2} e^{\frac{1}{4}}} \left( \frac{n}{e} \right)^{\frac{n}{2}} \exp(\sqrt{n})$$
cited on the OEIS entry which I assume can be proven using the saddle point method. Wikipedia says it can also be proven using Stirling's approximation on the binomial summation.


Are there circular limaçons?

Question: Trying to get a general definition for auxiliary circles in the context of conic sections (Wikipedia redirects me to just 'Ellipse'), I came to this table at the wiki for pedal curves. It states that for central conics, the auxiliary circle is the pedal of the conic with respect to the focus, and that similarly the tangent at the vertex is the pedal for parabolas (so correct me if I'm wrong, but there aren't auxiliary circles for parabolas).
Since the circle is a case of an ellipse, I supposed that its pedal was the circle itself -as stated here- and that the circle could be considered its own auxiliary circle. It makes sense; the points on a circle are the points you get for a pedal when you use the centre as the pedal point.
But then the table says that the pedal of a circle from any point is the limaçon. And even if I again use the 'focus' of the circle (the centre) as the pedal point, I just seem to get the squished shape of a limaçon, and not the expected circle.
I can't find any examples online of special-case limaçons that are circles, either. So is the pedal point I chose wrong, or is it that the auxiliary circle of a circle simply isn't defined as its pedal curve?
Comment: *"correct me if I'm wrong, but there aren't auxiliary circles for parabolas"* For a parabola, the tangent line at the vertex "is" the auxiliary circle, albeit one with infinite radius and zero curvature. Thinking of lines as special members of the circle family comes in handy for unifying various results of geometry, so start getting used to it. :) For instance, see [Descartes' "Kissing Circles" theorem](https://en.wikipedia.org/wiki/Descartes%27_theorem), which holds even when the kissers don't look all that *circular*.
Comment: *"I can't find any examples online of special-case limaçons that are circles, either."* Have you looked at the MathWorld [Limaçon entry](https://mathworld.wolfram.com/Limacon.html)? The general limaçon with polar equation $r=b+a\cos\theta$ becomes a circle when $b=0$.
Comment: @Blue: On the limaçon formula; oh, right, sorry. I wasn't familiar with polar coordinates other than using them for complex numbers. Great example for the parabola, too. So the basic idea that a conic's auxiliary circle is its pedal curve from its focus *is* correct, right?
Comment: @Blue, I've posted an answer. Are the points about hyperbola auxiliary circles and the definition of auxiliary circle being a pedal for all conics correct?
Answer: As in Blue's first comment, the limaçon of a circle with $b=0$ is indeed the circle itself. (That the pedal curve of a circle is the circle itself can be seen by using the basic foot-of-the-perpendicular equations with no hassle, too.)
The parabola's auxiliary circle, as in the second comment, can be visualised as an auxiliary circle itself; as the eccentricity of an ellipse graphed with a focus close to the origin grows closer to one, and one end shoots off into infinity, the part of the  auxiliary circle touching the visible end becomes more vertical, until when $e=1$, it becomes the tangent at the vertex. This line then flips(as $e$ grows past 1) to become the auxiliary circle for the hyperbola.
Thus, the auxiliary circle can be understood as the pedal of the conic from its focus.
Comment: +1. This is correct. ... It's a good exercise to show that the Cartesian equation for the pedal curve (aka, auxiliary circle) for a conic with respect to the focus is $$(1 - e^2) (x^2 + y^2)=p (p - 2 e x)$$
where the eccentricity and latus rectum are $e$ and $p$, and where the focus is located at the origin and corresponding vertex is on the positive $x$-axis, at $(\frac{p}{1+e},0)$. (FYI, the polar equation for such a conic is $r = \dfrac{p}{1+e\cos\theta}$.) From the equation, we see that the pedal curve/circle degenerates to a line when $e=1$ (ie, when the conic is a parabola).

Are there circular limaçons?


How does the proof of Rejection Sampling make sense?

Question: I am taking a course on Monte Carlo methods and we learned the Rejection Sampling (or Accept-Reject Sampling) method in the last lecture. There are a lot of resources on the web which shows the proof of this method but somehow I am not convinced with them.
So, in the Rejection Sampling, we have a distribution $f(x)$ which is hard to sample from. We choose a easy-to-sample distribution $g(x)$ and find a coefficient $c$ such that $f(x) \leq cg(x)$. Then we sample from $g(x)$ and for each draw, $x_i$, we also sample a $u$ from a standard uniform distribution $U(u|0,1)$.
The sample $x_i$ is accepted if it is $cg(x_i)u \leq f(x_i)$ and rejected otherwise.
The proofs which I came across usually just show that $p(x|Accept) = f(x)$ and stop there.
What I think about this process is that we have a sequence of variables $x_1,Accept_1,x_2,Accept_2,...,x_n,Accept_n$ and a $x_i,Accept_i$ pair corresponds to our i.th sample ($x_i$) and whether it is accepted ($Accept_i$). We know that each $x_i,Accept_i$ pair is independent of each other, such that:
$P(x_1,Accept_1,x_2,Accept_2,...,x_n,Accept_n) = \prod\limits_{i=1}^n P(x_i,Accept_i)$
For a $(x_i,Accept_i)$ pair we know that $P(x_i) = g(x_i)$ and $P(Accept_i|x_i) = \frac{f(x_i)}{cg(x_i)}$. We can readily calculate $p(x_i|Accept_i)$ but I don't understand how it suffices as a proof. We need to show that the algorithm works, so I think a proof should show that the empricial distribution of the accepted samples converge to $f(x)$ as $n\rightarrow\infty$. I mean, with $n$ being the number of all accepted and rejected samples:
$\frac{Number \hspace{1mm} of \hspace{1mm} samples \hspace{1mm} with \hspace{1mm} (A \leq x_i \leq B)}{Number \hspace{1mm} of \hspace{1mm} accepted \hspace{1mm} samples} \rightarrow \int_A^B f(x)dx$    as    $n\rightarrow\infty$.
Am I wrong with this thought pattern? Or is there a connection between the common proof of the algorithm and this?
Thanks in advance
Answer: You should think of the algorithm as producing draws from a random variable, to show that the algorithm works, it suffices to show that the algorithm draws from the random variable you want it to.
Let $X$ and $Y$ be scalar random variables with pdfs $f_X$ and $f_Y$ respectively, where $Y$ is something we already know how to sample from. We can also know that we can bound $f_X$ by $Mf_Y$ where $M\ge1$.
We now form a new random variable $A$ where $A | y \sim \text{Bernoulli } \left (\frac{f_X(y)}{Mf_Y(y)}\right )$, this takes the value $1$ with probability $\frac{f_X(y)}{Mf_Y(y)} $ and $0$ otherwise. This represents the algorithm 'accepting' a draw from $Y$.
Now we run the algorithm and collect all the draws from $Y$ that are accepted, lets call this random variable $Z = Y|A=1$.
To show that $Z \equiv X$, for any event $E$, we must show that $P(Z \in E) =P(X \in E)$.
So let's try that, first use Bayes' rule:
$P(Z \in E) = P(Y \in E | A =1) = \frac{P(Y \in E \& A=1)}{P(A=1)}$,
and the top part we write as
\begin{align*}P(Y \in E \& A=1) &= \int_E f_{Y, A}(y,1) \, dy \\ &= \int_E f_{A|Y}(1,y)f_Y(y) \, dy =\int_E f_Y(y) \frac{f_X(y)}{Mf_Y(y)} \, dy  =\frac{P(X \in E)}{M}.\end{align*}
And then the bottom part is simply
$P(A=1) = \int_{-\infty}^{\infty}f_{Y,A}(y,1) \, dy = \frac{1}{M}$,
by the same reasoning as above, setting $E=(-\infty, +\infty)$.
And these combine to give $P(X \in E)$, which is what we wanted, $Z \equiv X$.
That is how the algorithm works, but at the end of your question you seem to be concerned about a more general idea, that is when does an empirical distribution converge to the distribution sampled from? This is a general phenomenon concerning any sampling whatsoever if I understand you correctly.
In this case, let $X_1, \dots, X_n$ be iid random variables all with distribution $\equiv X$. Then for any event $E$, $\frac{\sum_{i=1}^n1_{X_i \in E}}{n}$ has expectation $P(X \in E)$ by the linearity of expectation.
Furthermore, given suitable assumptions you could use the strong law of large numbers to show that the empirical probability converges almost surely to the true probability.
Comment: Glivenko-Cantelli: http://www2.imperial.ac.uk/~das01/MyWeb/M3S3/Handouts/GlivenkoCantelli.pdf
Comment: Thanks for the answer. Can you clarify how can I show that the emprical distribution converges to the target distribution by using the Law of Large Numbers? It is exactly what I try to show in this case.
Comment: @Harri What disturbs me is the fact that we learn the random variable indicating acceptance of the draw ($A=1$) after we have learned the value of the actual variable. We observe the variables according to the sequence $Y_1,A_1,Y_2,A_2,...,Y_n,A_n$, so if we are about to observe the variable $Y_2$, what we know about the system is $Y_1$ and $A_1$ and since $Y_2$ is  independent of them, what we process is first $P(Y_2)$, then $P(A_2|Y_2)$ not the other way around.
Comment: Could you say some more on why the order of knowing $P(Y_2)$ and then $P(A_2|Y_2)$ disturbs you?
Answer: First, keep in mind that a complete procedure of the rejection sampling method only produces a single random variable. When some $x_i$ is accepted, the procedure stops, and there is no $x_{i+1}$ anymore. If you want multiple random variables, just repeat the procedure multiple times.
In some textbook, they denote the event of acceptance by $A$ and calculate the probability
$$
\begin{aligned}
P(A) =& \int_{-\infty}^{\infty}dx\int_0^{\frac{f(x)}{cg(x)}}g(x)du \\
=& \int_{-\infty}^{\infty}\frac{1}{c}f(x)dx \\
=& \frac{1}{c}.
\end{aligned}
$$
And
$$
\begin{aligned}
f_X(x|A) =& \frac{f_X(x) \cdot P(A|x)}{P(A)}\\
=& \frac{g(x) \cdot \frac{f(x)}{cg(x)}}{\frac{1}{c}} \\
=& f(x).
\end{aligned}
$$
The confusing thing is that the acceptance $A$ here appears to be acceptance of a single sample of $x_i$, but the whole procedure may reject multiple $x_i$'s.
Yes, a more rigorous proof should consider the probability of acceptance at different steps. Let $X_i$ denote the $i$th sample, $f_{X_i}$ denote the probability density function of $X_i$, $A_i$ denote the $i$th acceptance, and $X_\infty$ denote the final accepted value. Then the probability density function of $X_\infty$ is
$$
f_{X_\infty}(x) = P(A_1) f_{X_1}(x|A_1) + P(A_2) f_{X_2}(x|A_2) + \dots.
$$
$P(A_1)$ is $\frac{1}{c}$ and $f_{X_1}(x|A_1)$ is $f(x)$ as calculated before. Note $P(A_2)$ is $\left(1-\frac{1}{c}\right)\frac{1}{c}$ where $1-\frac{1}{c}$ is the probability of the rejection of $X_1$ since only when $X_1$ is rejected have we a chance to choose an $X_2$.
And $f_{X_2}(x|A_2)$ is $f(x)$ too because the second step is not affected by previous steps, its probability should be the same as the first step. If this explanation doesn't convince you, we can also work it out rigorously. Be careful $X_2$ is not defined when $X_1$ is accepted (or you can define it to be an arbitrary number when $X_1$ is accepted if undefined value makes you uncomfortable), so for probabilities concerning $X_2$, only conditional probabilities given $A_1^c$ or subsets of $A_1^c$ make sense. Now
$$
\begin{aligned}
f_{X_2}(x|A_2) =& \frac{P(A_1^c)f_{X_2}(x|A_1^c)P(A_2|X_2=x)}{P(A_2)} \\
=& \frac{P(A_1^c)f_{X_2}(x|A_1^c)P(A_2|X_2=x)}{P(A_1^c)P(A_2|A_1^c)} \\
=& \frac{f_{X_2}(x|A_1^c)P(A_2|X_2=x)}{P(A_2|A_1^c)} \\
=& \frac{g(x) \cdot \frac{f(x)}{cg(x)}}{\frac{1}{c}} \\
=& f(x).
\end{aligned}
$$
So
$$
\begin{aligned}
f_{X_\infty}(x) =& P(A_1) f(x) + P(A_2) f(x) + \dots \\
=& (P(A_1) + P(A_2) + \dots) f(x) \\
=& \left(\frac{1}{c} + \left(1-\frac{1}{c}\right)\frac{1}{c} + \left(1-\frac{1}{c}\right)^2\frac{1}{c} + \dots\right) f(x) \\
=& f(x).
\end{aligned}
$$
That is the desired result. Note $P(A_1) + P(A_2) + \dots$ = 1 has an intuitive meaning, that is eventually one sample will be accepted at some step $i$.


WPF ListView.CurrentChanged too fast for binding

Question: My case:

MVVM
ListView+Details(custom UserControl)
List bound to MV.Items (IsSynchronizedWithCurrent=true)
Details bound to MV.Items.Current
MV.Items.Count == 100
about 0.2sec to read details (lazy mode)

When I hold the down arrow on the list, very strange things happen:

list items order change
current changes in the random order
CPU usage drastically increments
and eventually all hangs.

I've read some post that one should start the timer or run handler in the background, but I am not able to do that, since all the binding WPF does for me.
Is there some way to instruct the binding in my DetailsControl, to wait a while before accepting CurrentItem?
Or should I just resign from the clean solution and write custom code in my MV to handle that?
Answer: See my codeplex project:
http://wpfcollections.codeplex.com/
There is LazyCurrentCollection that should help.


Exibir um botão baseando na ação de outro

Question: Sou iniciante no asp.net MVC
Tenho um projeto.
E dentro de uma determinada view eu tenho dois botões.
Porem, um deles só pode aparecer, se o outro for executado.
1 Botão> Salvar (salva carro)
2 Botão> Associar uma concessionária (só pode estar ativado, quando eu salvar o carro)
Associar uma concessionária é uma PopUp que exibe um grid com checkbox e permite que o usuário selecione uma concessionaria para associar. Isso já funciona perfeitamente.
Podem me ajudar?
Se precisarem de mais informações, é só falar.
Eu acredito precisar de um cód javascript na view, mas não tenho noção de como montar ele. Não tenho conhecimentos suficientes em js.
Ambos estão na mesma view.
View
@model Carro
@{
    var idConcessionaria = "id" + Guid.NewGuid().ToString().Substring(0, 5);

}

    @using (Ajax.BeginForm(
        "Incluir",
        "Carro",
        new DefaultAjaxOptions()
    ))
    {
        @Html.Partial("Validation")

       @Html.HiddenFor(i => i.Id)
       @Html.EditorFor(i => i.Modelo)
       @Html.EditorFor(i => i.Codigo)
        [...]

            <input type="submit" class="button blue" value="@Geral.Salvar" />

         @AdicionarConcessionaria

    }

Controller Carro
public ViewResultBase Salvar()
    {
        Carro model = new Carro();
        return base.SwitchView(model);
    }
[HttpPost]
[OutputCache(Duration = 0)]
public ViewResultBase Salvar([ModelBinder(typeof(CollectionModelBinder))]Carro model)
{
    if (this.ModelState.IsValid)
    {
        try
        {
            this.Service.AddItem(model);

            return this.PopUpSuccessView();
        }
        catch (ValidationException exception)
        {
            base.AddValidationErrors(exception);
            return base.PartialView(model);
        }
    }
    else
    {
        return base.PartialView(model);
    }
}

Services
public void AddItem(Carro item)
        {
            base.context.Carros.Add(item);
            base.Save();
        }

Answer: Acredito que o melhor caminho seria você alterar o fluxo do seu sistema de maneira que o botão Associar só fosse mostrado quando o usuário estivesse Editando um carro.
Por exemplo, crie uma Action chamada Adicionar, nesta action você retorna uma View chamada AdicionarOuEditar.cshtml (reutilizar a mesma View).
public ActionResult Adicionar()
{
    return View("AdicionarOuEditar");
}

[HttpPost]
public ActionResult Adicionar(SuaModelAqui model)
{
    //seu código para salvar aqui
    return RedirectToAction("Editar", new { id = seuNovoIdAqui });
}

Crie a respectiva Action para o seu HttpPost.
Na sua View, crie uma condição para mostrar ou não o botão, algo parecido como:
@if(Model != null && Model.Id != 0)
{
   significa que sua view está em modo de edição
   mostra o botão
}

Depois você cria uma outra action chamada Editar e segue os mesmos passos anterior, porém com códigos específicos para edição.
public ActionResult Editar(int id)
{
    var model = carregarSuaModelAqui(id);
    return View("AdicionarOuEditar", model);
}

[HttpPost]
public ActionResult Editar(SuaModelAqui model)
{
    //seu código para salvar aqui
    return Redirect(Request.RawUrl);
}


Alternative to ping

Question: I want to see if an Amazon EC2 instance is open, but by default Amazon EC2 blocks ping requests. There is a way to do this by changing the security policy of the instance. Excluding that, what would be the closest alternative to "see if a server is responsive" and is light-weight?
Is curl a good option?
Comment: If you arrive here from google try using a bash socket to open a port https://stackoverflow.com/a/4743398/619760
Answer: I think curl is exactly what you want. Like all well-behaved unix programs, it returns an error code if anything goes wrong:
[cnicutar@ariel ~]$ curl www.no-such-website.com
[cnicutar@ariel ~]$ echo $?
6

Also you may want to use --connect-timeout to make sure it doesn't wait forever.
Comment: Thank you, I will use that. Out of curiosity, what does `6` mean as an error code?
Comment: @David542 It's `curl`-specific. Every program chooses what to return and there's little standardization. If you're really interested you can look for a header called `sysexits.h`. The manual page does however explain exit codes.
Comment: from `curl` manpage: `6 Couldn't resolve host. The given remote host was not resolved.`
Comment: @dschulz So that's that. Everything not 0 is an error, which is what the OP is probably after.
Comment: You're right @cnicutar. I was just too curious about the 6 too and went to try `man curl` then `/EXIT CODES`  :-)
Comment: @dschulz I too looked earlier but didn't find it straight away and weaseled out: "I'm sure it's there".
Answer: If you can ssh to it then it's up. A simple way of checking this with nc is:
nc -zv 111.222.333.444 22
(Replace 111.222.333.444 with the ip address of your instance)
Comment: Thanks, what is the difference between netcat and ping? Also, the above command does not work in its current format.
Comment: The command works fine, I tested it before I posted. What error do you get?
Comment: @LarsHansson from docker container, I have to do nc mysql in my local, do i need to replace port in your example to 3306?
Answer: CURL won't work as a quick check if the server is up and the web server daemon is down. One alternative is to send a TCP ACK with tools like hping3. If you get a RST, the server is UP.
hping3 -c 1 -V -p 80 -s 5050 -A example.fqdn

What you could do is try the CURL test first and on failure try the second method to confirm that the server is down and not just the web server daemon.
The problem with this method is that a stray TCP packet like this could be filtered by an intermediate proxy.
Comment: Sure it will work. If the web server daemon is down the box will reply with a TCP RST or with nothing at all (which will be caught by the timeout). At any rate, if there's no response in the specified time `curl` will know.
Comment: Okay, thats true. Its so much faster to get a RST with hping3 than to wait for the exponential SYN retransmit back-off to timeout. Compare curl with the hping test for various tests (non-existent host, down host, down port, etc.). Its generally quicker.

Alternative to ping


checkout page is being redirected to 404 error instead of thank you page

Question: I have a WordPress website with woo commerce functionality. I have used cartflows for customizing the checkout page and thank you page. now the problems are:

after payment is successful, it redirects customers to 404 page rather than thank you page.
order status doesn't update as completed even after payment is successful.
emails for cash on delivery and bank transfers are being received two times.

can someone please assist me how can I resolve these errors???
Answer: Mb you've not selected which page is the Success page in WooCommerce settings?
Or this page is not created in Page.
Check these points first.
Comment: All pages are created, and they are perfectly working with direct bank transfer and cash on delivery, But they give 404 redirection when user purchase with debit/credit card. after payment gets successful it redirects them on 404 page.


Warning: format '%f' expectts a matching 'double' argument (pt-br)(en)

Question: Meu primeiro post aqui e gostaria de saber, porque quando vou compilar meu código ele dá um erro dizendo que o formato %f espera um double, sendo que o f é usado para float e a variável que eu estou colocando é float.
Segue o código:
#include <stdio.h>

float proceNotas(float nota1, float nota2, float nota3, char letter);

int main(){
    float n1, n2, n3;
    char letra;
    printf("Digite a primeira nota: ");
    scanf("%f", &n1);
    printf("Digite a segunda nota: ");
    scanf("%f", &n2);
    printf("Digite a terceira nota: ");
    scanf("%f", &n3);
    getchar();
    printf("Digite a operacao desejada: A) media aritmetica\nP) Media ponderada\nH) Media harmonica\n");
    letra = getchar();
    printf("\nA media do aluno é: %f"), proceNotas(n1, n2, n3, letra);
    return 0;
}

float proceNotas(float nota1, float nota2, float nota3, char letter){
    float arit, pond, harm;

    switch(letter){
        case 'A':
        arit = nota1+nota2+nota3/3;
        return arit;
        break;
        case 'P':
        pond = (nota1*5)+(nota2*3)+(nota3*2)/5+3+2;
        return pond;
        break;
        case 'H':
        harm = 3/(1/nota1)+(1/nota2)+(1/nota3);
        return harm;
        break;
        default:
        return printf("Operacao invalida!");
    }
}

Answer: Vários erros.
Aqui:
printf("\nA media do aluno é: %f"), proceNotas(n1, n2, n3, letra);

deveria ser:
printf("\nA media do aluno é: %f", proceNotas(n1, n2, n3, letra));

Seus cálculos estão errados. Estude a precedência dos operadores.
Aqui:
arit = nota1+nota2+nota3/3;

creio que não quer dividir apenas a nota3 por 3 mas sim toda a soma:
arit = (nota1+nota2+nota3)/3;

Aqui:
pond = (nota1*5)+(nota2*3)+(nota3*2)/5+3+2;

deve ser:
pond = ((nota1*5)+(nota2*3)+(nota3*2)) / (5+3+2);

e aqui:
harm = 3/(1/nota1)+(1/nota2)+(1/nota3);

deve ser:
harm = 3 / ((1/nota1)+(1/nota2)+(1/nota3));

Comment: Me sinto até envergonhado, muito obrigado, olhando assim, sao varios erros bobos
Comment: @AxelFelix, aceite a resposta do anonimo :). Ele respondeu mas você não marcou a resposta dele como útil e nem aceitou a resposta
Comment: pode responder a minha pergunta? https://pt.stackoverflow.com/questions/469237/identificar-registros-sequenciais-de-cada-usuário
Answer: A função printf() é uma função com número de argumentos variável (com ... no protótipo). Assim sendo, os argumentos que caem sob o domínio dos ... sofrem as promoções predefinidas para argumentos (link em inglês)

... The default argument promotions are performed on trailing arguments.

Estas promoções predefinidas incluem a conversão de valores tipo float para valores tipo double.
Ou seja, não é possível enviar um valor de tipo float para dentro do printf(). Não faz sentido haver uma conversão para esse tipo, por isso a conversão "%f" é para tipo double.
    float xf; double xd; long double xl;
    xf = xd = xl = 3.14159265L;
    printf("%f %lf\n", xf, xf);       // %f ou %lf para float/double
    printf("%f %lf\n", xd, xd);
    printf("%Lf\n", xl);              // %Lf para long double

https://ideone.com/nr6nqy


ConfigurationElementCollection with a number of ConfigurationElements of different type

Question: Is it possible to have a CollectionElementCollection with a number of different by type  CollectionElements, e.g.:
<collection>
    <add type="MyType1, MyLib" Type1SpecificProp="1" />
    <add type="MyType2, MyLib" Type2SpecificProp="2" />
</collection

I have all classes required for such solution:
class MyCollection : ConfigurationElementCollection { }
class MyElement : ConfigurationElement { }
class MyType1 : MyElement { }
class MyType2 : MyElement { }
...
etc

but when I start my application I'm getting next predictable error:

Unrecognized attribute 'Type1SpecificProp'.

because Type1SpecificProp is defined in MyType1 not MyElement, especially if MyCollection has next method:
protected override ConfigurationElement CreateNewElement()
{
    return new MyElement(); // but I want instantiate not the base class but by a type given
}

i.e. returns base class thus OnDeserializeUnrecognizedAttribute() in child classed are never been called.
So the question is: how to let child classes to resolve unknown elements by their self?
Answer: I looked into this as well. PolymorphicConfigurationElementCollection<T> seems deprecated.
Edit: it's not, see the comment of 'abatishchev' below, i was just linking an old version.
The solution of Rest Wing was promising but unfortunately required invoking internal methods residing in another namespace. While this is possible via reflection it isn't going to receive prices for coding beauty in this case.
I digged into the source with Reflection too and came up with the following solution:
[ConfigurationCollection(typeof(ElementBaseConfig), CollectionType=ConfigurationElementCollectionType.BasicMap)]
public class MyTypesConfigCollection : ConfigurationElementCollection
{
    protected override ConfigurationElement CreateNewElement()
    {
        // Not used but function must be defined
        return null;
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
        return element;
    }

    protected override ConfigurationElement CreateNewElement(string elementName)
    {
        switch (elementName)
        {
            case "mytype1":
                return new MyType1Config();

            case "mytype2":
                return new MyType2Config();

            default:
                throw new ConfigurationErrorsException(
                    string.Format("Unrecognized element '{0}'.", elementName));
        }
    }

    protected override bool IsElementName(string elementName)
    {
        // Required to be true
        return true;
    }

    public override ConfigurationElementCollectionType CollectionType
    {
        get { return ConfigurationElementCollectionType.BasicMap; }
    }
}

The override of the CollectionType is REQUIRED, even if this has been specified via the attribute in the top. When not overridden the base class' CollectionType still refers to 'AddRemoveClearMap' which isn't going to trigger the required 'CreateNewElement(string elementName)' function but it's parameterless variant 'CreateNemElement()'. For the same reason the overwritten IsElementName function should return true.
Note that I created a ElementBaseConfig which is the base class of both MyType1Config and MyType2Config in which you could define some shared attributes.
Comment: You've linked ver. 3.1, [here's the recent](http://msdn.microsoft.com/en-us/library/bb750549%28PandP.50%29.aspx) and not obsolete
Comment: You are right, changed my answer to reflect this. Thanks for noticing.
Answer: Microsoft.Practices.EnterpriseLibrary.Common.Configuration.PolymorphicConfigurationElementCollection<T> from EntLib5 do this job as a charm.
Comment: I know this answer was posted a while ago, but could you go into a little more detail if you're marking this as the accepted answer?
Comment: @goric: You need to inherit it and override `RetrieveConfigurationElementType` to substitute type in runtime. Also see [NameTypeConfigurationElementCollection](http://msdn.microsoft.com/en-us/library/ee939739%28PandP.50%29.aspx)
Answer: An instance of specific type (MyType1 and MyType2) needs to be created in order for child classes to resolve unknown elements or attributes by themselves.
Since the CreateNewElement method does not give any information on an element's attributes, that is not place where specific type instantiation can occur.
After some digging via Reflector, one comes to following partial call stack:
VariantCollection.MyCollection.CreateNewElement()
System.Configuration.ConfigurationElementCollection.CallCreateNewElement()
System.Configuration.ConfigurationElementCollection.OnDeserializeUnrecognizedElement(string elementName, XmlReader reader)

The OnDeserializeUnrecognizedElement method can be overriden in MyCollection class in order to create specific type instance. Instead of using the parameterless CallCreateNewElement method, use new one that receives XmlReader:

Read attribute type (ensure its existence and validity).
Create new element of specified type.
Call internal virtual void AssociateContext( BaseConfigurationRecord configRecord ) method of System.Configuration.ConfigurationElement on the element.
Call internal void CallInit() method of System.Configuration.ConfigurationElement on the element.
Return the prepared element.

BTW, if there will not be too many different collection elements, consider using something like:
<myType1Collection>
    <add Type1SpecificProp="1" />
</myType1Collection>
<myType2Collection>
    <add Type2SpecificProp="2" />
</myType2Collection>

That way you can avoid casting the items from MyCollection to specific type.


Computing orthogonal basis for the Krylov space

Question: I am reading about Lemma 5.2.1 form here. Bellow the lemma is attached from the link.
According to this lemma, i.e., $(5.2.2)$, $q_{k+1}$ must lie in the span of $q_i$ and $Hq_k$, Next, in order to compute $q_{k+1}$, it suffices to find a vector
$$y_{k+1} = \sum_{i=0}^{k} \theta_{ki} q_i + Hq_k\tag{1}$$
that is orthogonal to $q_i$ for $0 \leq j \leq k$ and then normalize $y_{k+1}$ to get $q_{k+1} = y_{k+1}/\gamma_{k+1}$, where $\gamma_{k+1} = ||y_{k+1}||_2$. Then, using the orthogonality of the $y_{k+1}$ with the $q_i$, $i=0,\dots,k$ we derive
$$0 = \langle q_j, y_{k+1} \rangle = \sum_{i=0}^k \theta_{ki} \langle q_j, q_i\rangle + \langle q_j, Hq_k \rangle = \theta_{kj} + \langle q_j, Hq_k \rangle.$$
As $q_i$ are orthonormal, from $(5.2.2)$, it is implied that
$$Hq_j \in span \{ q_0, q_1, \dots, q_j, q_{j+1}\},\quad j=0,\dots,k\tag{2}$$
and hence $$\langle q_i, Hq_k\rangle=0\tag{3}$$ for $j \leq k-2$. This way, $y_{k+1}$ can be writen as alinear combination of $Hq_k$ and the previous two orthonormal vectors, i.e.,
$$y_{k+1} = Hq_k - \langle q_k, Hq_k \rangle q_k - \langle q_{k-1}, Hq_k \rangle q_{k-1}$$
My questions are:

Why in $(1)$ we do not use a $\theta$ coefficien for the $Hq_k$ term as we did for $q_i$?
Why in $(3)$ the terms are zero for $j \leq k-2$? For this question, if we use $(2)$, i.e., for some $\lambda_i \in \mathbb{R}$ we may write
$$Hq_k = \sum_{i=0}^k \lambda_i q_{i+1}$$ and
$$\langle q_j, Hq_k\rangle = \sum_{i=0}^k \lambda_i \langle q_j ,q_{i+1}\rangle$$ but I could not reach the result in $(3)$ for $j \leq k-2$.

Could you please provide some explanations?
Answer: Why does $Hq_k$ not have a coefficient in $(1)$?
What we're doing in (1) is providing a general form for $y_{k+1}$ in which we'll later be able to solve for the coefficients $\theta_{k0}, \dots, \theta_{kk}$ to get the properties we want: that $y_{k+1} \in \operatorname{span}\{q_0, q_1, \dots, q_k, H q_k\}$ and that $\langle q_j, y_{k+1}\rangle = 0$ for $j=0, 1, \dots, k$.
The set of all such $y_{k+1}$ is a $1$-dimensional vector space, and it doesn't matter which element of that space we pick, because we're going to normalize and set $q_{k+1} = \frac{y_{k+1}}{\|y_{k+1}\|}$ anyway. So we're going to pick a specific $y_{k+1}$ to find: the one with a coefficient of $1$ on $Hq_k$. This makes our algebra easier.
If we put an unknown coefficient on $Hq_k$, we'd be able to solve for $\theta_{k0}, \dots, \theta_{kk}$ in terms of that coefficient, getting a family of solutions proportional to the $y_{k+1}$ we actually do find. Since we normalize anyway, that doesn't gain us anything.
How do we know that $\langle q_j, H q_k \rangle = 0$ for $j \le k-2$?
Because $H$ is symmetric, we have $\langle q_j, Hq_k \rangle = \langle Hq_j, q_k\rangle$, so it's enough to check that $Hq_j$ is orthogonal to $q_k$ for $j \le k-2$.
By the lemma, $$Hq_j \in  \operatorname{span}\{q_0, q_1, \dots, q_{j+1}\},$$
so when $j \le k-2$, we have
$$Hq_j \in \operatorname{span}\{q_0, q_1, \dots, q_{j+1}\} \subseteq \operatorname{span}\{q_0, q_1, \dots, q_{k-1}\}.$$
All of $q_0, q_1, \dots, q_{k-1}$ are orthogonal to $q_k$; therefore $Hq_j$ is also orthogonal to $q_k$.
Comment: Thanks for the answer. I still not understand the intuition in the second part. Can you provide a counter example on why we can not use $j \leq k-1$? Anny additional info is highly appreciated. Thanks again.
Comment: What intuition do you not understand? (Also, to give you a counterexample, I would have to know what $H$ is or what a Krylov space is, which I don't. But the argument that I gave does not apply to $j=k-1$, which is why we only conclude that $\langle q_j, H q_k \rangle = 0$ for $j \le k-2$.)
Comment: Why the argument does not apply for $j> k-2$? This is what I am trying to understand.
Comment: I've elaborated on this part. We need $j+1 \le k-1$ for the containment in my next-to-last line to work.


Sum with squared trigamma function: $\sum_{n=1}^{\infty}\left(n\psi_{1}^{2}(n)-\frac{1}{n}\right)$

Question: Here is a question I found on web
$$S=\sum_{n=1}^{\infty}\left(n\psi_{1}^{2}(n)-\frac{1}{n}\right)$$
The closed form is: $\frac{3}{2}\zeta(3)+\frac{3}{2}-\frac{\pi^2}{12}$. I know how to handle $\psi_{1}^{2}(n)$ by using double integrals and integral representation of the trigamma function. But with the term $\frac{1}{n}$ I don't know how to get rid of it.
Clearly, the sum of $n\psi_1^2(n)$ is divergent, so I doubt there is a way to eleminate the term $\frac{1}{n}$ but I can't find it yet.
Any help is welcome, and I am grateful for that, thank you so much.
Answer: Perhaps this has something to do with the theory of multiple zeta values. Here is a self-contained solution using basic properties of $\psi_1(n)=\sum_{m\geqslant n}1/m^2$, namely $0<\psi_1(n)-1/n<1/n^2$: $$\small\psi_1(n)-\frac1n=\sum_{m\geqslant n}\left(\frac1{m^2}-\frac1{m(m+1)}\right)=\sum_{m\geqslant n}\frac1{m^2(m+1)}<\sum_{m\geqslant n}\frac1{nm(m+1)}=\frac1{n^2}$$ (which implies $\lim\limits_{n\to\infty}n\psi_1(n)=1$ and the convergence of $S$) and $\sum_{n\geqslant 1}\psi_1(n)/n=2\zeta(3)$, equivalent to the simplest Euler sum a.k.a. $\zeta(2,1)$; an easy proof is as follows:
$$\small\Xi=\sum_{n\geqslant 1}\frac1n\sum_{m\geqslant n}\frac1{m^2}=\sum_{m\geqslant 1}\frac1{m^2}\sum_{1\leqslant n\leqslant m}\frac1n=\sum_{m\geqslant 1}\frac1{m^2}\sum_{n\geqslant 1}\left(\frac1n-\frac1{n+m}\right)=\sum_{n,m\geqslant 1}\frac1{nm(n+m)}\\\small=\sum_{n,m\geqslant 1}\left(\frac1n+\frac1m\right)\frac1{(n+m)^2}=2\sum_{n,m\geqslant 1}\frac1{n(n+m)^2}=2\sum_{n\geqslant 1}\frac1n\sum_{m>n}\frac1{m^2}=2\big(\Xi-\zeta(3)\big).$$

We compute (in two ways) the limit $\lim\limits_{N\to\infty}(S_N-H_N)$, where $$\color{gray}{H_N=\sum_{n=1}^N\frac1n,}\qquad S_N=\sum_{n=1}^N n\left(\sum_{m=n}^N\frac1{m^2}\right)^2.$$
First, writing $S_{N-1}=\sum_{n=1}^{N-1}n\big(\psi_1(n)-\psi_1(N)\big)^2$ and expanding the square, we get $$S_{N-1}-H_{N-1}=\sum_{n=1}^{N-1}\left(n\psi_1^2(n)-\frac1n\right)-2\psi_1(N)\sum_{n=1}^{N-1}n\psi_1(n)+\psi_1^2(N)\frac{N(N-1)}{2}.$$
Now $\lim\limits_{n\to\infty}n\psi_1(n)=1$ implies $\lim\limits_{N\to\infty}(1/N)\sum_{n=1}^{N-1}n\psi_1(n)=1$ by Stolz–Cesàro, hence $$\lim_{N\to\infty}(S_N-H_N)=\color{blue}{S-\frac32}.$$
Second, fix $N$ and put $A_n=n(n+1)/2$ and $B_n=\sum_{m=n}^N 1/m^2$ (with $B_{N+1}=0$), then $$S_N=\sum_{n=1}^N(A_n-A_{n-1})B_n^2=\sum_{n=1}^N A_n(B_n^2-B_{n+1}^2)\\\small=\sum_{n=1}^N A_n(B_n-B_{n+1})(B_n+B_{n+1})=\sum_{n=1}^N\frac{n+1}{2n}\left(2B_n-\frac1{n^2}\right)$$ and, since $\sum_{n=1}^N B_n=H_N$, and $B_n\to\psi_1(n)$ monotonically (as $N\to\infty$), we get $$\lim_{N\to\infty}(S_N-H_N)=\sum_{n=1}^\infty\left(\frac{\psi_1(n)}{n}-\frac{n+1}{2n^3}\right)=\color{blue}{\frac32\zeta(3)-\frac12\zeta(2)}.$$


multisite multilingual over different directory

Question: I have multi-site over directories.
xx and yy are made symbolic links are linked to same Drupal directory
domain.tld/xx
domain.tld/yy
And on .htaccess it requires to have different Rewritebase
RewriteBase /xx
or
RewriteBase /yy
which is not possible.
Any other way to solve using someother  RewriteRule?
Note: It is also multilingual website
Update: It is Drupal 7.26
Answer: I was solved this problem . May be use to you for only Multisite
Solution:
<code>Give Symbolic link form mulitsite to site1
Executed that command line
ln -s /var/www/multisite /var/www/site1

Rename example.sites.php to sites.php
// 192.168.1.99 local IP address
$sites['192.168.1.99.site1'] = 'site1';

put this line in sites.php
</code>
No need to use RewriteBase /xx
If you have any problem in symbolic link use this link https://superuser.com/questions/68685/chown-is-not-changing-symbolic-link
and also How do I setup multiple sites with one database in Drupal 7 (or) Multisite Apache configuration with Drupal


Strategy for gaining ssh access without setting up a router

Question: I'm going to need to administrate someone's macbook pro remotely over ssh. Problem is, they'll be moving between networks so I can't just set up port forwarding on their router. What strategy could I use to gain access, regardless of the network they're on?
I'm thinking one possibility might be to get them to run a bash script (hopefully by double clicking on an icon on their desktop) which somehow made it possible for me to ssh in.
Perhaps something along the lines of https://github.com/progrium/localtunnel could do the job?
Thanks!
Answer: You're going to need the machine you'll be administering to make outbound connections in order to reach it behind whatever firewalls / routers it ends up behind. You might consider saving yourself the headache of implementing that yourself and use something like Hamachi.
Answer: Can you set up OpenVPN between the Macbook and your site?  The Macbook can be an OpenVPN client using TunnelBlick.  You can set up an OpenVPN server on your site using whatever is appropriate.  In this case, the Macbook will initiate a VPN connection to your site, and your OpenVPN server will assign it a static IP address inside the VPN.  You can then just ssh to that VPN IP address.
Yes, that localtunnel thing will probably work.  On the other hand, OpenVPN is much more standardized and well understood than localtunnel.  And you can do much more with it if you need additional access.
Answer: If you specifically need SSH, then some sort of VPN client on the Mac that links it to your network would allow this.  When you need to get access, they fire up the VPN, which assigns them a static address on your network, then you SSH on.
Answer: As far as I'm concerned you can do that provided that:
1) you have public IP and sshd server running OR
2) if you are in intranet and you can set up port forwarding on your router so as port 22 will be redirected to your machine
if 1) or 2) are the case for you and macos machine has sshd server running. Do the following on macos whenever you want to have access to it (make script from it and give it to macos owners):
macos$ ssh -R 65022:localhost:22 root@<yourmachine_ip_address>

What it does is forwarding macos's sshd server on your port 65022.
Now you can simply ssh to port 65022:
yourlocalmachine$ ssh -p 65022 email@example.com

and you should be on macos now.
By the way: yourmachine_ip_address can be a third machine with sshd access, which you own and with public IP address. Than in last step you would connect with it this way:
yourlocalmachine$ ssh -p 65022 root@<yourmachine_ip_address>

WARNING: I'm not 100% sure it will work (I haven't tested it yet), but it's interesting - I will try it as soon as I get back home :)
UPDATE: I've tested it - it works like a charm.
UPDATE 2: In second case (when we use third machine), GatewayPorts yes has to be set in /etc/sshd/sshd_config file on this machine.


Can Dell power vault nx 300 work without active directory?

Question: I am struggling to find this solution...
Dell customer support is not helping with this issue. They are asking money for the support. I cant get any info from google regarding the configuration.
Comment: don't really know much about the device but since it arrives without knowledge of a domain existence then I'm sure it can work without AD. let me do some reading on the nx300
Comment: looks like there are two additions workgroup or not, which version do you have?
Answer: It is just windows 2008 underneath.  Without AD it'll work but you'll have to sync local passwords up manually and some features eg. domain based DFS will be unavailable.
Answer: The Dell NX300 uses Windows Storage Server 2008.  Storage Server doesn't need to be joined to a domain to work, so there's no reason it can't run without active directory.
As JamesRyan mentioned, you'll be using local authentication on the NX300 then (likely a pain) or have to use some other method for authentication.
Features like SMB/CIFS file sharing and FCI will work, but you will lose domain-dependent technologies like DFS.


Como usar transicoes de "tempo" em uma animacao Canvas

Question: Dando sequencia ao post "Como gerar uma curva Seno", onde fiz alguns ajustes:
Ainda estou trabalhando neste simulador de ECG (eletrocardiograma), e agora preciso "manipular" os tempos dentro do simulador,
Por exemplo: Demora muito entre aplicar o medicamento e ficar esperando que ele passe por todo o processo, para conferir os resultados.
Então, criei este botão que "faz o tempo passar" com o dobro da velocidade.

Embora inicialmente esteja FUNCIONADO (E o gráfico fica semelhante), QUANDO troco a velocidade e SOMENTE depois aplico o medicamento.
Mas, se eu troco essa velocidade "DURANTE" a transição, acontecem coisas loucas nos resultados.
por favor confira neste exemplo  do CodePen   onde eu usei um exemplo do Jquery-flot

Ou seja, não importa a velocidade do tempo, o gráfico sempre deveria ser idêntico.
para isso simplesmente dividi os tempos das variáveis..

Eis a parte do codigo que cria a onda Seno

if(isRunning==true){
                    if( medicineTime1 >= 1 ){
                        medicineTime1--;
                        if( medicineTime1 < 1 ){ medicineTime1 = .1; }
                        //
                        // o  "high2Temp e linear", transformando em "seno"...
                        //
                        // criar o  "envelope" apra ancorar o coeficiente.
                        high2Target  = high2TargetPhase1;
                        high2Final   = high2Target + high2Temp;
                        high2FinalSum= high2Final / medicineTime1 ;
                        high2Temp    = high2Temp - high2FinalSum;
                        // criar o coeficiente.
                        coefficient =  ( high2FinalSum / high2TempTimeG );
                        //  para dividir em 2  (metades), durante o tempo de "de subida".
                        if( !isMedicineTime1Temp ){
                            medicineTime1Temp = medicineTime1;
                            // assumindo que sempre partiremos de  "Normal ECG"
                            // high2Inicial = 70;
                            high2Inicial = high2;
                            isMedicineTime1Temp = true;
                        }
                        //  primeira metade
                        if( medicineTime1 > medicineTime1Temp / 2 ){
                            apple = apple + coefficient;
                            high2 = high2 - apple;
                        }
                        //  segunda metade
                        if( medicineTime1 < medicineTime1Temp / 2 ){
                            apple = apple - coefficient;
                            high2 = high2 - apple;
                        }
                        //
                        // a frequencia sempre sera  linear...
                        //
                        frequency2Target  = frequency2TargetPhase1/frequency2Factor;
                        frequency2Final   = frequency2Target-frequency2;
                        frequency2FinalSum= frequency2Final/medicineTime1 ;
                        frequency2        = frequency2 + frequency2FinalSum;
                        if(medicineTime1<1){
                            //high2 = high2TargetPhase1 * -1;
                            frequency2         = frequency2TargetPhase1/frequency2Factor;
                            medicinePhase1     = false;
                            medicinePhase2     = true;
                            isMedicineTime1Temp= false;
                        }
                    }
}

E aqui como divido as variáveis:

document.getElementById('buttonTime1').onclick = function(){
    updateInterval = updateInterval*2;
    medicineTime1 = medicineTime1*2;
    high2TempTimeG = 50;
    document.getElementById("log").innerHTML = "tempo = 1 ";
};
document.getElementById('buttonTime2').onclick = function(){
    updateInterval = updateInterval/2;
    medicineTime1 = medicineTime1/2;
    high2TempTimeG = 25;
    document.getElementById("log").innerHTML = " tempo = 5 ";
};

Logo eis a minha duvida, por que o código funciona em uma situação, e não na segunda? ja que todas as variáveis sao as mesmas?
o que não estou vendo? onde tenho que prestar atenção?
Answer: Percebi onde estava meu erro,
A var "medicineTime1Temp" que e o tempo em que "deve durar" a transição, estava sendo ajustada apenas "antes" da animação iniciar....
Se a velocidade for trocada "durante a aminação", ela também devera ser ajustada,  mas eu havia esquecido.


How to adapt a C++-style random number engine for GSL (GNU Scientific Library)?

Question: I have a PRNG that satisfies the requirements of a C++ random number engine, as described here. (It's from the PCG family). That is, an instance of the engine can be used by C++ standard library distribution classes to generate random numbers:
pcg_extras::seed_seq_from<std::random_device> seed_source;
pcg32 rng(seed_source);
std::uniform_real_distribution<double> uniformDist(0., 1.);
double randomNumber = uniformDist(rng);

I need to generate samples from a distribution not included in <random>, so I need to use a function from GSL. How do I use my C++ engine for this purpose? The GSL rng functions all require a const gsl_rng * as the first argument.
The default creation and usage of gsl_rng is as follows:
const gsl_rng_type * T;
gsl_rng * r;
gsl_rng_env_setup();
T = gsl_rng_default;
r = gsl_rng_alloc (T);
double u = gsl_rng_uniform (r);

To use my own engine, I believe that I will need to define a gsl_rng_type, as defined in "gsl/gsl_rng.h":
typedef struct
  {
    const char *name;
    unsigned long int max;
    unsigned long int min;
    size_t size;
    void (*set) (void *state, unsigned long int seed);
    unsigned long int (*get) (void *state);
    double (*get_double) (void *state);
  }
gsl_rng_type;

Am I correct in what I surmise is needed? Are there examples out there of how I might define a custom gsl_rng_type, especially the three necessary member functions? What might be my void *state?
Answer: I ended up doing the following to get things working. Note that my random number engine is a global variable in my program: g_rng.
It's necessary to construct a struct to hold whatever state is relevant for the RNG. In my case, I simply hold a pointer to pcg32:
// In some header file, e.g. rng.h
typedef struct
{
    pcg32 *rng;
} gsl_pcg_state;

Three functions, "set", "get", and "get_double" must be defined:
// In some header file, e.g. rng.h
static void gsl_pcg_set(void *state, unsigned long int seed)
{
    ((gsl_pcg_state *)state)->rng = &g_rng;
    (void)seed;                 // unused
}

static unsigned long int gsl_pcg_get(void *state)
{
    return (*((gsl_pcg_state *)state)->rng)();
}

static double gsl_pcg_get_double(void *state)
{
    // Range [0, 1)
    return (*((gsl_pcg_state *)state)->rng)() / 4294967296.;
}

So then a gsl_rng_type can be instantiated:
static const gsl_rng_type gsl_rng_pcg = {
    "pcg",
    0xffffffffUL,
    0,
    sizeof(gsl_pcg_state),
    &gsl_pcg_set,
    &gsl_pcg_get,
    &gsl_pcg_get_double
};

Within the main program, you would have...
gsl_rng *r;
r = gsl_rng_alloc(&gsl_rng_pcg);
// one can now call various gsl_ran_[...] functions

gsl_rng_free(r);

Looking at gsl_rng_alloc as defined in rng.c from GSL confirms this is the right setup.
Answer: That is correct. The entire public interface is outlined in https://github.com/LuaDist/gsl/blob/master/rng/gsl_rng.h


Replace Contents of NSTextFieldCell *During* Editing?

Question: I'm trying to boldface the contents of an NSTextFieldCell if certain text is entered by the user while the NSTextFieldCell is being edited.
So far I've got this:
In awakeFromNib:
<code>[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldCellDidChange:)  name:NSControlTextDidChangeNotification object:theNSTableView];
</code>
The method:
<code>- (void) textFieldCellDidChange: (id) sender
{
    //successfully captures contents of the NSTextFieldCell prior to the
    //start of editing
    NSString * textOfMyNSTextFieldCell = [myNSTextFieldCell stringValue];

    //attempts to capture the current edited contents of the NSTextFieldCell while
    //editing is still in progress:
    //but DOES NOT YET WORK:
    NSText *fieldEditor = [myTableView currentEditor];
    textOfMyNSTextFieldCell = [fieldEditor string];
}
</code>
Is it possible to capture the edited contents of an NSTextFieldCell while editing is still in progress?
Answer: To get the NSTextFieldCell's stringValue after a change is made, subclass NSTextFieldCell and implement this:
<code>- (void) textDidChange:(NSNotification*)notification {
    NSLog(@"NSTextFieldCell noticed that text did change to: %@", self.stringValue) ;
    NSLog(@"Was notified by: \n%@", notification.object) ;
    NSLog(@"which is its controlView's currentEditor: \n%@", ((NSTextField*)self.controlView).currentEditor) ;
}
</code>
Comment: Thanks for this info, John. Will this method be called on every keypress during editing, or, is it only called after editing is complete?
Comment: In my testing, it was called after every keystroke.


$x \mapsto \sup_{f \in K}{f(x)}$ is continuous

Question: Let $K \subset C[0, 1]$ be a compact subspace, then consider the following map $\varphi: x \mapsto \sup_{f \in K}{f(x)}$ How to prove that $\varphi$ is continuous?
Since, $K$ is compact, then, by Arzela-Ascoli theorem, $K$ is pointwise bounded, i.e. $|f_{n}(x)| \leq M$, $\forall f_{n} \in K$ and equicontinuity also holds, i.e. $\forall \epsilon > 0, \exists \delta >0: |x-y| < \delta => |f(x)-f(y)| < \epsilon$ for each $f \in K$. Then, the second condition seems to be extremely useful, since i need to prove that if $x_{n} \rightarrow x$, then $\sup_{f \in K}{f(x_{n})} \rightarrow \sup_{f \in K}{f(x)}$ by i can't make a good use of it. Are there any hints that might help?
Answer: Let us show that $\varphi$ is continuous in $x$. Hence, we pick an arbitrary $\varepsilon > 0$ and choose the corresponding $\delta > 0$.
Now, let $y$ be given with $| x - y | \le \delta$. For any $f \in K$ we have
$$f(x) - \varepsilon \le f(y)\le f(x) + \varepsilon.$$
You should try to finish the proof.
Answer: Suppose $x_n \to x$, then $f(x_n) \to f(x)$ for all $f \in K$ and
since $\phi(x_n) \ge f(x_n)$ for all $f \in K$ we see that
$\liminf_n \phi(x_n) \ge \liminf_n f(x_n) = f(x)$ and so
$\liminf_n \phi(x_n) \ge \phi(x)$. This is true regardless of the nature of $K$.
Now choose $f_n \in K$ such that $f_n(x_n) = \phi(x_n)$. Choose a subsequence
$x_{n_k}$ such that $\limsup_n \phi(x_n) = \lim_k \phi(x_{n_k})$. Then $f_{n_k}$ has a further subsequence such that $f_{n_{k_j}} \to f \in K$,
and hence we have $f_{n_{k_j}}(x_{n_{k_j}}) \to f(x)$ and so
\begin{eqnarray*}
\limsup_n \phi(x_n) &=& \lim_k \phi(x_{n_k})
= \lim_j \phi(x_{n_{k_j}}) \\
&=& \lim_j f_{n_{k_j}}(x_{n_{k_j}})
= f(x) \le \phi(x)
\end{eqnarray*}
Hence $\phi$ is continuous.
Answer: It's possible to complete a proof in the following way:
Since $K \subset C([0, 1], \mathbb{R})$ is compact, then by Arzela-Ascoli theorem $\forall \epsilon > 0, \exists \delta>0$, so that $|x-y| < \delta$ implies $|f(x)-f(y)|<\epsilon, \forall f \in K$.
Let $|x_{n} - x| \to 0$, then we need to check that $|\sup_{f \in K}{f(x_{n})}-\sup_{f \in K}{f(x)}| \to 0$. But $|\sup_{f \in K}{f(x_{n})}-\sup_{f \in K}{f(x)}| \leq \sup_{f \in K}{|f(x_{n})-f(x)|} < \epsilon, \forall \epsilon > 0$ (by equicontinuity).


How to run mixed effects models with lots of 0's

Question: I have ecological data (transects as the unit) from inside marine reserves and matched control transects that I would like to test the difference across 18 separate response variables. These are 3 overall response variables: biomass, density, and richness, and 3 response variables (biomass, density and total Length) for each of 5 of individual fish families. However the data points are also grouped within sites (4 transects per site) and marine reserve (8 separate reserves). I want to test the overall difference for these 18 response variables, as well as the difference for each individual marine reserve. To do this I think I need to run mixed effects models with site nested in reserve as random effects for the overall outcomes, and mixed effects models with site only for each individual reserve outcome.
I have tried a number of things listed below but am running into several problems.

For the overall outcomes I tried running these in nlme. The data is quite skewed for some of the 18 outcomes, with many 0's, so for these I have tried log transforming. However I get error # 1 when trying to log transform (see below)
From there I tried running the models without log transforming them. Many of the residual plots were trumpet shaped as a result but I wanted to see if I could move forwards. The models ran but when I tried to put the main output data into a table format I get error # 2 (see below) for specific outcomes.
If I rerun the models with 1|site instead of 1|name/site I can compile the data to a table, but the p-values of most of the outcome variables with both 1|name/site and 1|site are 1.

My first guess was that many of the outcome variables have a high number of 0's, which is causing problems.
Would it be possible to provide feedback on:
A) The best models to run for this data
B) How to compile this data from all 18 outcome variables into a single table
C) An explanation of why the p - value is 1, and why this is leading to errors when trying to create the output table.
I am guessing this has to do with some groups of the random effects having no data, but I am unsure.
Thank you
<code>```# Input data
matched.cases3 = read.csv('matched.cases2FHR.csv')
matched.cases3=matched.cases3%>% mutate(TorC=as.factor(TorC))
head(matched.cases3)

# Run all for one example from 18, Scarbm. TorC is Treatment or Control (0 or 1)

#try to log transform. See error #1
Scarbm.lme1 = lme(log(Scarbm)~TorC,
random=~1|name/site,data=matched.cases3, method='REML')
#Log transform error: Error in MEEM(object, conLin, control$niterEM) :
NA/NaN/Inf in foreign function call (arg 1)

#Run without log transforming
Scarbm.lme1 = lme(Scarbm~TorC, random=~1|name/site,data=matched.cases3,
method='REML')
Scarbm.lme2 = lme(Scarbm~TorC, random=~TorC|name/site,data=matched.cases3,
method='REML')

#check AIC fixed intercept is better
AIC(Scarbm.lme1,Scarbm.lme2)

#check residual plot, trumpet shaped
plot(Scarbm.lme1)

#Summary
summary(Scarbm.lme1)
Linear mixed-effects model fit by maximum likelihood
Data: matched.cases3

Random effects:
Formula: ~1 | name
        (Intercept)
StdDev:  0.05367244

  Formula: ~1 | site %in% name
         (Intercept) Residual
StdDev:    288.8733 334.5428

Fixed effects: Scarbm ~ TorC
 Correlation:
      (Intr)
TorC1 -0.357

Standardized Within-Group Residuals:
   Min         Q1        Med         Q3        Max
-2.2320898 -0.3453362 -0.1419344  0.2529601  5.9144762

Number of Observations: 250
Number of Groups:
          name site %in% name
             8             32

AIC  BIC  logLik
3686.832    3704.439    -1838.416

 Value Std.Error DF t-value p-value
(Intercept) 358.2354    59.57017    217 6.013671    0
TorC1           0.0000          42.48697    217 0.000000    1

#Compile to table (for all 18 outcome variables). See error #2 for when
run as 1|name/site
lme=Scarbm.lme1
p=data.frame(summary(lme)$tTable[,"p-value"])
t=data.frame(summary(lme)$tTable[,"t-value"])
df=data.frame(summary(lme)$tTable[,"DF"])
ste=data.frame(summary(lme)$tTable[,"Std.Error"])
p=p[2,]
t=t[2,]
df=df[2,]
ste=ste[2,]
mean=emmeans(lme, ~TorC) %>% as.data.frame
mean=mean[c("emmean", "lower.CL","upper.CL")]
meanT=mean[2,]
meanC=mean[1,]
r2=data.frame(r.squaredGLMM(lme))
int=intervals(lme)
int=data.frame(int$fixed)
int=int[2,]
response=c("Scarbm")
response=data.frame(response)
management=c("FHR")
management=data.frame(management)
ScarbmTC=cbind(management,response,int,meanT,meanC,ste,df,t,p,r2)
#Error in intervals.lme(lme) : cannot get confidence intervals on var-cov
components: Non-positive definite approximate variance-covariance Consider
'which = "fixed"'

#rerun with random effect as 1|site only, it works.
Overall=rbind(bmTC,densTC,richTC,AcanthbmTC,AcanthdensTC,AcanthLETC,ScarbmTC,ScardensTC,ScarLETC,LethbmTC,LethdensTC,LethLETC,LutbmTC,LutdensTC,LutLETC,SerrbmTC,SerrdensTC,SerrLETC)
Overall
#Example for just Scarbm row of Overall
management response lower est. upper emmean lower.CL ste df t p
FHR       Scarbm    -83.5972502 -9.077611e-14   83.5972502
358.182621  235.455253 480.909989   42.4145630  217 -2.140211e-15
1.000000e+00
</code>

Log transform error: Error in MEEM(object, conLin, control$niterEM) : NA/NaN/Inf in foreign function call (arg 1)
intervals.lme(lme) : cannot get confidence intervals on var-cov components: Non-positive definite approximate variance-covariance Consider 'which = "fixed"'
Comment: Do you expect your data to result from two processes (first process: presence/absence, second process: amount)? If yes, you need an approach for zero-inflated data (which basically means two coupled models for the two processes). There is also a high chance that some of your dependent variables require use of a GLMM. And finally, this looks like a data exploration exercise. Your approach has unfortunate implications for resulting p-values.
Comment: A lot of people use log(y+1) which doesn't result in all those missing values. It isn't necessarily theoretically justified, but on the other hand, if it results in more symmetrically distributed residuals, it would be a more desirable model than the one without a transformation. All models are wrong, but some are more useful than others.
Answer: You could use a two-part mixed effects model for semi-continuous data. This combines a logistic regression for the dichotomous indicator that the outcome is zero or not with a log-normal model for the continuous part.
Two-part mixed effects models are available in the GLMMadaptive package I've written - you can find a sample analysis here.


Why do I need to enable the Drupal Bootstrap theme when using a Bootstrap subtheme?

Question: I'm trying to learn how to use the Drupal Bootstrap theme to create my own subtheme.  I've added the Bootstrap theme to my drupal/themes directory, and chosen SASS as my sub-theme starterkit (i.e. I've copied drupal/themes/bootstrap/starterkits/sass to drupal/themes/mynewtheme).
I understand the concept of how sub-themes work: the sub-theme inherits the parent theme's resources.  But I don't understand how it works in the case of the Drupal Bootstrap theme.  Once I install the bootstrap framework into my sub-theme (per the instructions on the Drupal Bootstrap sub-theming instructions page), what resources is the sub-theme inheriting from the main theme?
Answer:
Why do I need to enable the Drupal Bootstrap theme when using a Bootstrap subtheme?

You don't. You simply have to define in your subtheme that you're making Drupal Bootstrap your parent theme.

what resources is the sub-theme inheriting from the main theme?

The templates and anything tethered to it.
Templates that you don't override on your subtheme gets delegated to the parent theme, in this case, the Bootstrap theme. Anything that the Bootstrap theme doesn't override gets delegated to the core themes. If I remember correctly, the Bootstrap theme overrides a lot of the templates. If you turn on template debugging, you'll see the hierarchy of the template suggestions.
Since the templates also define additional things like favicons, extra CSS, HTML boilerplates, and that stuff (html and page templates especially), if you don't override them on your subtheme, you get Bootstrap's which loads whatever is in there.