Fazer um loop com php em uma class HTML

Question: Vamos supor que eu tenha uma div dentro de um foreach e dentro dessa div eu tenha uma outra div com uma classe x, porém gostaria que essa classe x fosse numerada a cada repetição, existe essa possibilidade?
Exemplo do código:
<?php
                    foreach ($list_menu as $key => $menu):
                    ?>
                            <?php
                            if(count($menu->subMenu)):
                            ?>

                                    <a href="<?= base_url('categoria/' . $menu->txtUrlMenuSite); ?>"><?= strtolower($menu->txtMenu); ?>

                                                <?php
                                                foreach ($menu->subMenu as $key => $sub):
                                                ?>

<a href="<?= base_url('categoria/' . $sub->txtUrlMenuSite); ?>"><?= $sub->txtMenu; ?>

                                                <?php
                                                endforeach;
                                                ?>

                            <?php
                            else:
                            ?>

<a href="<?= base_url('categoria/' . $menu->txtUrlMenuSite); ?>"><?= strtolower($menu->txtMenu); ?>

                            <?php
                            endif;
                            ?>

                    <?php
                    endforeach;
                    ?>

Comment: coloca um count $count = 0;  foreach(sue foreachaqui) {  echo ""; $count++;}
Comment: Marcos Brinner, muito obrigado, irei tentar agora!
Comment: Você pode colocar uma parte do código para ficar mais clara a pergunta, amigo?
Comment: Woton Sampaio, desculpa amigo acabei de editar o post, muito obrigado!
Answer: Gustavo,
você pode fazer:
$a = "";
foreach ($arr as $key => $value)
   $a .= "

";

 echo $a;

ou tbm colocar um contador:
$count = 0;
$a = "";
foreach ($arr as $value)
    $a .= "

";

echo $a;

Comment: Muito Obrigado Gabriel Carvalho, com a sua resposta e a dos outros amigos consegui resolver o problema!!
Comment: @GustavoSiqueira, evite agradecer nos comentários. O agradecimento já é um UpVote, e confirmação da resposta. :]

Fazer um loop com php em uma class HTML


Using flex as display, and having a video as child does not respect my fill setting

Question: I'd like to have on an HTML page:

header div - some height, based on its contents
content div (below header) - take the rest of the height below header
table (in content div) - take 100% for both dimensions of its parent (content div)
video item (in table) - take and reserve 100% for both dimensions of its parent (td)

Here is what I have:

body { margin: 0; }

#main {
  position: absolute;
  left:0px;
  top:0px;

  display: flex;
  flex-direction: column;
  height: 100vh;
  width: 100vw;
  background:red;
}

#header {
  background:yellow;
}

#content {
  background:gray;
  flex:1;
}

table {
  width: 100%;
  height: 100%;
  background: blue;
  color: white;
}

video {
  width: 100%;
  height: 100%;
}

Header

    <video controls>
      <source src="https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/1080/Big_Buck_Bunny_1080_10s_1MB.mp4" type="video/mp4">
    </video>

Now, the problem is with the video tag (if you run this snippet there will be scrollbars -  I don't want them).
If I remove the video tag, everything works as intended.
However, if there is the video tag, it ruins the 'flex' option: it enlarges the td, hence the table becomes also larger and then the content also - so scrollbar(s) are enabled and the page won't fit into the screen.
Maybe the video is resized when the media is loaded, and at that time all css operations are finished.
But what is the way to make the video to be the exact same size as 100% width and height of its parent (the td) even during playback?
Comment: why you need the table?
Comment: sometimes table is this simple (1row, 1col), but sometimes it is larger (3row, 3col) and it's generated dynamically - probably not a must but I don't want to mix things in one question.
Answer: You can make the video position:absolute

body {
  margin: 0;
}

#main {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  background: red;
}

#header {
  background: yellow;
}

#content {
  background: gray;
  flex: 1;
  min-height: 0;
}

table {
  width: 100%;
  height: 100%;
  background: blue;
  color: white;
}

td {
  position: relative;
}

video {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

      Header

            <video controls>
      <source src="https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/1080/Big_Buck_Bunny_1080_10s_1MB.mp4" type="video/mp4">
    </video>

Comment: @Daniel in this particular situation it's not needed but it's good to have it because it will prevent your element to overflow in case there is more content. Related: https://stackoverflow.com/q/36247140/8620333
Comment: This is exactly what I needed. Only one thing is not clear for me: what is the reason of `min-height: 0;` in `#content`?
Comment: Thanks. Any idea on why this is not working in IE11? (tried to check it in JSFiddle, but their page is not working under IE at all. Then tried it with my server, FF, Opera, Edge, Chrome all works fine, but IE no)
Comment: @Daniel well, IE is known to have a lot of issues with flexbox. Unfortunately I cannot test it
Answer: Do you want this...

body {
  margin: 0;
}

#main {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  background: red;
}

#header {
  background: yellow;
}

#content {
  background: gray;
  flex: 1;
  height: 100%;

}

table {
  width: 100%;
  height: 100%;
  background: blue;
  color: white;
}

td {
  position: relative;
}

video {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

Header

    <video controls>
      <source src="https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/1080/Big_Buck_Bunny_1080_10s_1MB.mp4" type="video/mp4">
    </video>

Comment: No, vertical scrollbar is still there. I want that the video takes the max space that the column  > table > td offers. (tried to click on 'Run code snippet')


Displaying the same contents onto a different Greenfoot world

Question: For a Greenfoot final class project, I decided to make a game called "Doggie the Super Catcher". What this game basically does is that the actor, Doggie, will try his best to catch the clovers and special treats that seems to be falling from the trees by running back and forth across the screen (through the user's left and right arrow keyboard input, of course). However, the thing is that I want to create multiple levels, and that I kind of want what I have for the first world (named GameWorld) to appear in level 1, which is in a different world. How am I supposed to do that? In other words, I can't seem to transfer the same things from GameWorld to Level1, which includes the clovers, candies, and score board, when a certain condition is met (i.e., a specific number of points is reached)? FYI: I've used a separate actor for the score board (hope this helps...). Does any of you know of a way? Thanks.
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

public class Doggie extends Actor
{

// Declare arrays of Greenfoot images for animation
private GreenfootImage[] runningLeft;
private GreenfootImage[] runningRight;

// Declare Greenfoot images for standing still facing left and right
private GreenfootImage standingStill;
private GreenfootImage standingLeft;
private GreenfootImage standingRight;

//
boolean facingLeft;

// Integers that help control the speed of movement and animation
private int animationCounter;
private int animationDelay;
private int animationDelayCounter;
private int animationSpeed;

Clover c;
SpecialTreat1 c1;
SpecialTreat2 c2;

public Doggie()
{
    String fileName;
    String fileNamePrefix = "left0";
    String fileNameSuffix = ".png";

    runningLeft = new GreenfootImage[3];
    runningRight = new GreenfootImage[3];

    for (int imageCounter = 0; imageCounter < runningLeft.length; imageCounter++)
    {
        fileName = fileNamePrefix + (imageCounter + 1) + fileNameSuffix;
        runningLeft[imageCounter] = new GreenfootImage(fileName);
        runningRight[imageCounter] = new GreenfootImage (runningLeft[imageCounter]);
        runningRight[imageCounter].mirrorHorizontally();
    }

    standingStill = new GreenfootImage ("still01.png");
    standingLeft = new GreenfootImage ("left01.png");
    standingRight = new GreenfootImage (standingLeft);
    standingRight.mirrorHorizontally();

    facingLeft = true;

    animationSpeed = 5;

    animationDelay = 6;

    animationDelayCounter = 0;

    animationCounter = 0;
}

/**
 * Act - do whatever the Doggie wants to do. This method is called whenever
 * the 'Act' or 'Run' button gets pressed in the environment.
 */
public void act()
{
    animationDelayCounter++;
    if (animationDelayCounter == animationDelay)
    {
        animationCounter++;
        animationDelayCounter = 0;
    }

    if (animationCounter > runningRight.length - 1)
        animationCounter = 0;

    c = (Clover)getOneIntersectingObject(Clover.class);
    c1 = (SpecialTreat1)getOneIntersectingObject(SpecialTreat1.class);
    c2 = (SpecialTreat2)getOneIntersectingObject(SpecialTreat2.class);

    if (c != null)
    {
        c.collect();
        GameWorld gW = (GameWorld)getWorld();
        gW.showPoints();
    }

    if (c1 != null)
    {
        c1.collect();
        GameWorld gW = (GameWorld)getWorld();
        gW.showPoints();
    }

    if (c2 != null)
    {
        c2.collect();
        GameWorld gW = (GameWorld)getWorld();
        gW.showPoints();
    }
}

public void runLeft()
{
    if (!(facingLeft))
        animationCounter = 0;

    facingLeft = true;

    setImage (runningLeft[animationCounter]);
    setLocation (getX() - animationSpeed, getY());
}

public void runRight()
{
    if (facingLeft)
        animationCounter = 0;

    facingLeft = false;

    setImage (runningRight[animationCounter]);
    setLocation (getX() + animationSpeed, getY());
}

public void standStill()
{
    if (facingLeft)
    {
        setImage(standingLeft);
    }
    else
        setImage(standingRight);
    animationCounter = 0;
    animationDelayCounter = 0;
}

}

Comment: And sorry I haven't commented on this code yet. :(
Answer: In Greenfoot, levels are usually implemented by having different worlds.  So you might have:
class Level1 extends World
{
    ...
}

And
class Level2 extends World
{
     ...
}

They will both appear directly beneath World in the class diagram.  If you want to share code between your levels (e.g. they both spawn clovers) then you probably want a shared parent class.  So you might have:
class DoggieWorld extends World
{
    public void spawnClovers(int speed)
    {
        if (Greenfoot.getRandomNumber(1000) < speed)
            addObject(new Clover(), Greenfoot.getRandomNumber(getWidth()), 0);
    }
}

Then you have two level classes, each of which extends DoggieWorld (not just plain World), allowing you to call the spawnClovers method from each:
class Level1 extends DoggieWorld
{
    public void act()
    {
        spawnClovers(20);
    }
}

class Level2 extends DoggieWorld
{
    public void act()
    {
        spawnClovers(50);
    }
}

I don't want to make this answer too long, but hopefully that gives the general idea: have a shared parent world class which both level classes inherit from (using extends), and then both level classes can call methods from the shared parent.
Edit: sorry, I think I just understood more clearly that you also want to transfer the actors between the worlds when switching level.  You can do this by going through all the actors of the type you are interested in, and removing them from the existing world and adding them to the new world.  E.g. include this sort of method in Level1:
public void changeLevel()
{
    World nextLevel = new Level2();
    for (Clover c : getObjects(Clover.class))
    {
        // Must ask for position before removing from world:
        int x = c.getX();
        int y = c.getY();
        removeObject(c);
        nextLevel.addObject(c, x, y);
    }
    Greenfoot.setWorld(nextLevel);
}

Hope that helps
Comment: OK. Thanks for the quick reply, but I've got one more question. Does it mean that all private variables declared in DoggieWorld as well as its constructor will be inherited directly by its subclasses, Level1 and Level2? If so, it means that I don't need to put any constructors or variables into Level1 and Level2, right, assuming that I transfer all the actors exactly the way they were to the new world(s)?
Comment: Oh, wait. I kind of fixed that myself, but for some reason, I don't know why my public variable "score" (declared in DoggieWorld) is ignored by the program when I tried to use it in a condition in Level1.... :(
Comment: Oh, never mind. Worked around your idea for a few hours, and now, I finally got it! Many thanks!!! :P


Intuition behind projection matrix

Question: I'm new to machine learning and came across projection matrix . In a random thread it was interpreted as

The matrix $X(X^\text{T} X)^{-1} X^\text{T}$ is a projection matrix, as it does precisely that: it is the linear transformation that orthogonally projects a vector onto the span of the vectors comprising $X$.

I'm having hard time to understand the underlying concept behind this and how is this related to linear regression .Some intuition and use cases in machine learning and deep learning would help.
And Ik taking inverse is undoing the process but what does this means here?
Comment: Could you clarify *which* underlying concept you are trying to understand?  The quotation refers to no fewer than six concepts: matrix, projection, linear transformation, orthogonality, vector, and span!  The topic you refer to can be researched by searching our site for [regression projection matrix](https://stats.stackexchange.com/search?tab=votes&q=regression%20projection%20matrix).
Comment: A lot of similar posts, see [this list](https://www.google.com/search?q=site%3Ahttps%3A%2F%2Fstats.stackexchange.com+least+squares+as+projection&oq=site%3Ahttps%3A%2F%2Fstats.stackexchange.com++least+squares+as+projection&aqs=chrome..69i57j69i58.11993j0j4&client=ubuntu&sourceid=chrome&ie=UTF-8)
Comment: I understand basic terminologies , but I wanted to understand maths as well as intuition behind orthogonality, projections and how is that leads to linear regression.
Answer: Suppose we have an n-vector $y$ and an $n$ by $p$ matrix $X$.  The subspace $S$ spanned by the $p$ columns of $X$ is the set of vectors formed by taking all possible linear combinations of the columns of $X$ (an infinite number).  For example, if $X$ consists of two nonzero columns that do not lie on top of each other then $S$ will be a plane through the origin.
The projection of $y$ on $S$ is the point $\hat{y}$ in $S$ that is closest to $y$.  See the diagram in Why is $\mathbf{y}-\mathbf{\hat{y}}$ perpendicular to the subspace spanned by $\mathbf{x}$ in linear regression? where our $S$ is the yellow area in that diagram.
The projection has the property that $\hat{y}$ and $y-\hat{y}$ are orthogonal.  This must be so because if we take any other point $p$ in $S$ then the triangle formed by the tips of $y$, $\hat{y}$ and $p$ is a right angle triangle in which the segment from $y$ to $p$ is the hypotenuse and since the hypotenuse is the longest side $p$ cannot be closer to $y$ than $\hat{y}$.
Another property to note is that projection of $\hat{y}$ on $S$ is just $\hat{y}$ again since $\hat{y}$ already lies in $S$.
The regression of $y$ on $X$ is just the projection of $y$ on $S$ and the regression coefficients, the vector $\hat{b}$, is the vector that $X$ maps to $\hat{y}$, i.e. $\hat{y} = X\hat{b}$.  (It will be unique if $X$ is of full rank, i.e. if there is no nonzero $b$ such that $Xb = 0$.) $\hat{y}$ is referred to as the fitted values and $e=y-\hat{y}$ is referred to as the residuals.  From the above $y = \hat{y} + e$ and the terms on the right hand side, i.e. the fitted values $\hat{y}$ and the residuals $e$, are orthogonal to each other. (It is also true from the Pythagorean theorem that $||y||^2 = ||\hat{y}||^2 + ||e||^2$ because the points $0$, $y$ and $\hat{y}$ form a right angle triangle where the side from $0$ to the tip of $y$ is the hypotenuse.)
We can demonstrate the orthogonality modulo computer floating point precision of $e$ to $X$ and to $\hat{y}$ in R using the built in BOD data frame like this:
<code>fm <- lm(demand ~ Time, BOD)
X <- model.matrix(fm)
yhat <- fitted(fm)
e <- resid(fm)

crossprod(X, e)
##                      [,1]
## (Intercept) -8.881784e-16
## Time         0.000000e+00

crossprod(yhat, e)
##               [,1]
## [1,] -1.776357e-15
</code>
To construct the projection matrix from above we multiply the first equation below by $X'$ giving the second but $X'e$ is zero since $e$ is orthogonal to $S$ and hence to the columns of $X$ giving the third equation.
$y = X\hat{b} + e$
$X'y = X'X\hat{b} + X'e$
$X'y = X'X\hat{b}$
Now in the usual case where the columns of $X$ are linearly independent $X'X$ is invertible so multiply through by $(X'X)^{-1}$ giving $\hat{b} = (X'X)^{-1} X'y$ and since $\hat{y} = X\hat{b}$ we have  $\hat{y} = X(X'X)^{-1} X'y$ so as the projection is a matrix, it represents a linear transformation.
Comment: Would you elaborate why taking projection on subspace is linear?
Comment: I think its easiest to just construct it and since it is a matrix it represents a linear transformation. Added that at the end.
Comment: Thanks, that was a neat explanation!

Intuition behind projection matrix


ActionScript 3 / Flex 4 : Add Text/Label to an Image loading in AS

Question: I load an image from a url and add it to the stage.
I need a way to add some text to the image before loading it to the stage !
NOTE: add text over the image after it has been loaded
thanks in advance.
NOTE:
Image type  mx : Image
Answer: You could just use a composite component then.
Any with absolute positioning should do.
Just make sure to add the label as the last subcomponent.
For example:
<code><mx:Canvas width="100" height="100">
    <mx:Image source="http://www.gravatar.com/avatar/" width="100%" height="100%"/>
    <s:Label text="This is your text"/>
</mx:Canvas>
</code>
Comment: *Technically*, this doesn't add the text to the `Image` itself but just displays the text over the `Image`. This may or may not be what the OP is looking for.
Comment: This is indeed a quick fix for the problem described.
If it is really necessary to incorporate a watermark in the image, then some server side technology would be the best way to achieve this.
Comment: Because I don't want to use another side service to do something , this is the best way to go ahead and do this.

thanks Jason and Dennis for your time


When KL Divergence and KS test will show inconsistent results?

Question: I know that Kullback–Leibler divergence and Kolmogorov–Smirnov test are different and should be used in different scenarios. But they are similar in many ways and given two distributions, we could calculate their KL divergence in terms of bits and p-value under KS test (and there are also other metrics like Jensen–Shannon divergence and many other hypothesis testing methods. But Let's just talk about KL divergence and KS test here.)
My question is: Under what circumstances, that KS test will provide a very small p-value but KL divergence will give us a very small distance? What is the intuition behind it? It would be better if there could be any concrete examples.
Comment: For a comparison of Kolmogorov distance and KL divergence note that Kolmogorov distance compares values of cumulative distribution functions while KL divergence compares (log) ratio of densities.
Answer: Set aside Kullback-Leibler divergence for a moment and consider the following: it's perfectly possible for the Kolmogorov-Smirnov p-value to be small and for the corresponding Kolomogorov-Smirnov distance to be small.
Specifically, that can easily happen with large sample sizes, where even small differences are still larger than we'd expect to see from random variation.
The same will naturally tend to happen when considering some other suitable measure of divergence and comparing it to the Kolmogorov-Smirnov p-value - it will quite naturally occur at large sample sizes.
[If you don't wish to confound the distinction between Kolmogorov-Smirnov distance and p-value with the difference in what the two things are looking at, it might be better to explore the differences in the two measures ($D_{KS}$ and $D_{KL}$) directly, but that's not what is being asked here.]


Has there ever been a piano accordion with piano keys on both hands?

Question: It's possible to find a piano accordion with piano keys on the right hand and the triangular arrangement of buttons on the left-hand. It's also possible to find a button accordion with the triangular arrangement on both hands and a free-bass system instead of the Stradella system. The bayan is a 20th century solution to the centuries-old quest to find a portable, sustained-note keyboard instrument.
The obvious other way to go is to have piano keys on both hands. In some ways this is a more obvious instrument to me than a bayan, given that the piano keyboard is already a thing. There are obvious problems around playing piano keys freely with the hand that's controlling the bellows, but perhaps not insurmountable. Has anyone ever made such a thing: a piano accordion with piano keys on both hands? If they did, what was wrong with it: why didn't it catch on?
Answer: If you google "double keyboard piano accordion" you can see at least a couple of different designs have been manufactured, one being the Soprani Luttbeg. They're very rare though, so if you want to try the idea out for yourself you could get hold of two identical piano accordions and swap the piano section of one for the button section of the other (this may not work on all accordions, you might need to resort to gaffer tape like these guys).
I imagine you'd quickly discover that playing chords would be a lot more challenging than using buttons. The usual Stradella button layout on the accordion makes for a very economical way of moving through related chords with minimal movement of the fingers.
A true double keyboard would also make the whole instrument significantly wider and more unwieldy - you'll see those that have been made don't really have full second keyboards. It would also make bellows control harder as it would be difficult to strap a hand in.
The one advantage would be the ability to play mutli-voice keyboard music as written, but this is possible (and arguably easier) on either a free bass piano accordion or a chromatic button accordion. Chromatic button accordions have the added advantage of a greater range as the buttons are smaller so you can fit more of them in.


Using Unicode characters with Imagemagick and PHP

Question: I'm trying to provide text for imagemagick and it threw me a curve ball:
Bần chỉ là một anh nghèo

Per http://www.imagemagick.org/Usage/text/#unicode, all I need to do is wrap the extended characters in  \x{}.  Using json_encode, I can easily get close:
print json_encode("Bần chỉ là một anh nghèo");  // Output is "B\u1ea7n ch\u1ec9 l\u00e0 m\u1ed9t anh ngh\u00e8o"

Now, all I need to do is to get it from "B\u1ea7n ch\u1ec9 l\u00e0 m\u1ed9t anh ngh\u00e8o" to "B\x{1ea7}n ch\x{1ec9} l\x{00e0} m\x{1ed9}t anh ngh\x{00e8o}"
Any suggestions on a regex in PHP?
EDIT: Per icktoofay's feedback, I don't think RegEx is the right solution.  I think I need to somehow execute my command differently.  My code is basically doing:
$cmd = "convert -fill black -font Oswald -pointsize 72 label:'" . addslashes($text) . "' logo.png"
exec($cmd);

Also open to any possible security holes here.  I think addslashes will do it, but...
Comment: It's trivial. What have you tried? Do you have problems with escaping the backslash in the search pattern, or with constructing the replacement pattern?
Answer: I think you're misinterpreting that example. ImageMagick takes UTF-8 input. The \x{236A} was part of an embedded Perl script that output to ImageMagick. Really, what you'll want to do is just hand ImageMagick some UTF-8 text.

Looking into it more, I'm guessing that your problem is PHP not dealing with UTF-8 command-line arguments in a sane way. I checked to see if another way (say, execv) was available, and unfortunately, there isn't. A workaround may be to write to a temporary file and use ImageMagick's @ syntax:
$temp_file_name = tempnam(sys_get_temp_dir(), "txt");
file_put_contents($temp_file_name, $text);
$cmd = "convert ... label:@" . escapeshellarg($temp_file_name) . "...";
exec($cmd);
unlink($temp_file_name);

Comment: I actually tried that, handing the string as-is via "$cmd = "convert -fill black -font Oswald -pointsize 72 label:'" . addslashes($text) . "' logo.png";"   The code does work, but it chews up extended characters.  My next step was to try and convert $text as shown in the ImageMagick example..
Comment: BTW, I think you're right.  I tried it command-line and it output "B\x{1ea7}n ch\x{1ec9} l\x{00e0} m\x{1ed9}t anh ngh\x{00e8o}" almost literally.  So I think I'm on the wrong path...
Comment: @Anthony: You could try having ImageMagick read the text from a file rather than from the command line. I updated my answer to show this possibility.
Comment: Brilliant!  I'll give that a try and report back.  I didn't think about that approach..
Comment: I changed the code to write to disk, but I'm still getting the same results.  When I vim the file, however, I see "Bần chá» là má»t anh nghèo".  Perhaps I need to do something about the PHP string encoding?  If I just do a "print $text;" it shows up in the browser correctly, but apparently there is something I'm missing about encoding...
Comment: @Anthony: You'll need to figure out what encoding it is, then. In many browsers, you can tell the browser to interpret the page as a specific encoding. (In Firefox, for example, that's in View → Character Encoding.) Go through the list until it's correctly interpreted. Then you know that that's the right encoding. Then use [`iconv`](http://www.php.net/iconv) to convert to UTF-8.
Comment: Thanks for the tip - I tried this and verified that the encoding is UTF-8.  I think I've actually tracked down the problem: I'm ripping down the font from Google Fonts and using a python script to convert the WOFF download to a TTF file, which I then pass to ImageMagick.  I verified that "Bần chỉ là một anh nghèo" renders properly at http://www.google.com/webfonts for "Open Sans", but when  I rip it down and download the converted TTF file, it lacks some of the extended latin characters.  So I think something about my conversion process needs to change.  Thanks for your help!
Comment: @Anthony: No need to convert — Google Web Fonts supports TTF natively! The CSS file you'd link in — `http://fonts.googleapis.com/css?family=Open+Sans` — varies its content depending on the `User-Agent` fetching it. Fetch it with cURL and you'll get a version with a link to a TrueType font. When I do that, I get [this font](http://themes.googleusercontent.com/static/fonts/opensans/v6/cJZKeOuBrn4kERxqtaUH3aCWcynf_cDxXwCLxiixG1c.ttf).
Comment: I actually struggled with this.  I saw that based on how I grabbed the font, I'd get a TTF vs WOFF.  I grabbed your link, installed it, and it seems less robust than the Google Font.  Try this: Check the font you linked to me in Character Map vs visiting http://www.google.com/webfonts/specimen/Open+Sans.  You'll notice there are way more glyphs on the web font.  Is TTF more limited?  (Note: The characters from my sample are at http://www.unicodemap.org/search.asp?search=B%E1%BA%A7n%20ch%E1%BB%89%20l%C3%A0%20m%E1%BB%99t%20anh%20ngh%C3%A8o, itemized individualy)
Comment: @Anthony: I just checked and the TTF does have all of those characters.
Comment: Well, I posted the phrase into MS Word and changed the font to Open Sans - it appears normally.  But if I launch Character Map and try to find some of the extended latin characters, like http://www.unicodemap.org/details/0x1EA7/index.html, I can't find them.  Also, I copied the TTF to the server and tried to use it with ImageMagick.  The same extended characters won't show up..
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/24296/discussion-between-anthony-and-icktoofay)


Installing Drupal patches in Ubuntu terminal

Question: I'm new to Ubuntu and I never ran Drupal patches before and now is my first to do so: I've searched here in the Drupal answers with the phrase: "Patches, Ubuntu" But I didn't find instruction on how to run patches for a module in a local site via the Ubuntu terminal. I've also searched some in Google in Youtube but I found ways for many other CLIs, but not for the Ubuntu terminal.
Is it possible to run the patches there as I would run Drush commands?
Comment: Update: Stage two of my process in solving this problem can be viewed here:

http://drupal.stackexchange.com/questions/186028/failed-patching-both-manually-and-with-git-in-ubuntu-terminal
Answer: As far as I know there is nothing in specific about applying patches for drupal in ubuntu.
If you are already using git for managing your project code then you can apply a patch to a project's repository by using following code:
git apply -v path/file.patch

If you are not using git, or if the repo isn't a local checkout of the project you wish to patch:
patch -p1 < path/file.patch

For more information, check https://www.drupal.org/patch/apply
Live example for patching in Drupal 8:

Download the .patch file (in this case: Add_rtl_support.patch)
Copy it into the particular module's directory (since the patch is relative to the module directory).
Change the destination directory in the Ubuntu terminal to the module's folder - In this case it should be cd modules/admin_toolbar.
Apply the patch using 2nd method patch -p1 < Add_rtl_support.patch
Comment: @benos yes, you need to install git, `sudo apt-get install git`
Comment: Hello Benos. it all depends on the patch that you are applying. Check the path given in the patch, depending on that you should either apply the patch from site root or the module root directory. Regarding #1, if you are already using git as version control management then you can #1 else use #2.
Yes, you can install git using sudo apt-get install git
Comment: Download the patch and have the name as "Add_rtl_support.patch". Change the directory to the module folder, since its for Drupal 8 it must be something like cd modules/contrib/admin_toolbar. Then try to apply patch using #2,
patch -p1 < Add_rtl_support.patch
Ensure you have the patch file in the same module directory. Hope am clear!
Comment: Update: Stage two of my process in solving this problem can be viewed here:

http://drupal.stackexchange.com/questions/186028/failed-patching-both-manually-and-with-git-in-ubuntu-terminal


How to lift a finger from a touch screen without generating touch events?

Question: I'm writing an application where the user moves shapes on a screen by dragging them, using a UIPanGestureRecognizer.
Here is the problem: the finger is not a point, and the location of the UITouch is more or less the centroid of the contact surface of the finger on the screen. When the user begins to lift his finger, the shape of the contact surface changes and it generates additional touch events before the finger actually leaves the screen.
How to deal with this?  I could try to detect a pause in the movement of the finger, but I don't know if this feels intuitive. Are there any other solutions ?
Answer: Just an idea:  I suppose you could add a 0.2 second delay between touch detection and actually moving the shape.  That way, you can discard the bogus touch events after the user lifts his finger (which is far shorter than 0.2 seconds).


TabLayoutPanel with scroll

Question: I'm using a TabLayoutPanel in a GWT application, attached to the RootLayoutPanel of the page.
Inside each tab I have a ScrollPanel, which is used to display a FlexTable.
Is it possible to make the TabLayoutPanel grow vertically, so the user can scroll the entire page using the browser scroll bar, instead of using the internal ScrollPanel ?
Answer: The short answer is: It's not possible with LayoutPanel's. The reason: LayoutPanel's are specific for applications that need to fill the browser client area, or in other words the part that is visible by the user. One of the problems with browsers is to have a widget that has exactly the height of the visible area and also automatically resizes when the browser window is resized. This is one of the problems the LayoutPanels solve.
If you want to use the browser scrollbar and be able to create pages longer than the visible area use the 'normal' Panels.
BTW just FYI you are aware the FlexTable is slow in rendering and if possible better use Grid.
Answer: Just add a new style to the TabLayoutPanel:
this.addStyleName("tab-style-content");

And define in your CSS as:
.tab-style-content .gwt-TabLayoutPanelContent
{
overflow: auto;
}

Thus, the property overflow will be overwritten in the gwt-TabLayoutPanelContent and the scrollbar will be shown automatically.
Answer: If you make the TabLayoutPanel bigger than the root panel, you will get a browser scroll bar.
Comment: I removed the ScrollPanel, adding the FlexTable directly to the TabLayoutPanel. However, as the FlexTable grows with the new items added to it, the TabLayoutPanel height doesn't change.

Do I have to call a specific method to layout the panel again ?
Answer: If I want to achieve something like this, I always put the TabLayoutPanel in a SimplePanel and add the SimplePanel to the RootPanel. I guess this is not the best way, but it works.
public void onModuleLoad() {
   //Create TabPanel
   TabPanel tp = new TabPanel();
   tp.add(new HTML("Foo"), "foo");
   tp.add(new HTML("Bar"), "bar");
   tp.add(new HTML("Baz"), "baz");
   tp.selectTab(1);
   // Create SimplePanel and add TabPanel
   SimplePanel sp =new SimplePanel();
   sp.add(tp);
   // Add SimplePanel to the root panel.
   RootPanel.get().add(sp);
}

Comment: It didn't work, probably because I'm using TabLayoutPanel, introduced in GWT 2.0, not TabPanel. Here's a thread discussing the same problem:
http://www.coderanch.com/t/493012/Google-Web-Toolkit/Application-Frameworks/TabLayoutPanel-auto-height-grow-gwt
Comment: Why not use the TabPanel instead? Isn't the only benefit of the *LayoutPanels that they are automatically attached to the RootPanel?
Comment: `TabPanel` won't work in `Standards` mode, only in `Quirks` mode. So you can't mix `TabPanel` with `FlowPanel` you have to use `TabLayoutPanel` which is apparently crippled in respect to the way it handles auto sizing at the browse level.

TabLayoutPanel with scroll


During form validation, can you "stash" a form for an end user while they fill out a different form?

Question: Core of the question
I have a form that might throw a validation error based on the values in other entities on the site.  If a user fills out an entity form and hits submit, they will see validation errors that tell them another entity is in conflict.
I would like to provide the user with an option to update the other entity on the site to clear up the validation issue.  The problem with that, however, is that the user would have to navigate away from the form throwing the validation errors, and they'd then lose their input.
I would like to fix this up without using Ajax, because I think that Ajax will complicate the UI and I'd like to keep javascript out of the equation for now.
Is there a standard non-hackish way to use $form and $form_state in a way that will allow me to just grab the user input and stash it into the SESSION or something so once the user fills out a secondary form, they go back to the original form and their originally input values are still there?
The desired user experience

{Entity A} exists with field data on the site that will cause a
validation error on {New Entity B} add form.
User enters field input into {New Entity B} add form, and hits submit.
My custom {New Entity B} form validation callback checks {Entity A} and
discovers a problem that requires {Entity A} to be edited before
{New Entity B} can be saved.
User does ??? and {New Entity B} $form and {New Entity B} $form_state are "saved
for later" while user goes to {Entity A} edit form.
User updates and saves {Entity A} and is redirected back to {New Entity B} add form.
{New Entity B} add form has the same input values the user already entered, because they were retrieved from a "stashed" {New Entity B} $form and {New Entity B} $form_state.

Is this possible?  How?
Edit
Caveat about uncertainty of form fields
The exact fields on the entity form are unknown.  I want to apply this logic to numerous entity forms, which means I don't know which fields are there in my validation callbacks.  This is why I'm looking to stash $form and $form_state in their entirety.  I don't want to get involved with individual field values.
Comment: It sounds more like the problem you need to solve is the functional dependency, not the work-around. Without all the developer-speak, can you give us a real life example of this?
Comment: I'm building a scheduling module that allows various entities to be placed onto a schedule.  I don't want 2 different users putting the same entity on their schedule at the same time.  If that happens, I want to provide steps to resolve the scheduling conflict.
Comment: It sounds like these 'entities' are 'Tasks'. If each task is discrete, and can only be claimed once, then providing the user with a list of unclaimed tasks would prevent the problem.
Comment: The problem is that I want to provide an option to override another referrer's claim (or request override, request sharing, all which require filling out another form).  Also, i don't want to build a new UI to choose from a list of unclaimed time ranges.  the time ranges are not really even list-able, as they are not limited in definition (could be 3pm to 4pm or could be mon-thurs, etc)
Comment: And by "entities" I do mean Drupal Entity's -- I'm using EntityAPI and Entity Reference fields.  It could be an "instructor" or a "location" or any reference-able Drupal Entity type that has a date field.
Comment: this is what I'm working on: http://drupal.org/sandbox/tmsimont/1931666 in conjunction with this: http://drupal.org/sandbox/tmsimont/1917664
Answer: I just looked at your Entity Availability project page, and it looks interesting. You are facing the classic Temporal dependency problem of all scheduling systems (eg Departure time depends on Arrival time). This is the one data dependency which cannot be resolved statically.
The Webforms module uses $_SESSION to store information for multi-page forms for the anonymous user. In the case of the Webform module, the submission ID ($sid) is saved the $_SESSION, and the $form_state is saved in and retrieved from the database, however I see no problem with using $_SESSION to maintain a working copy of the $form_state object ($_SESSION['form_id'] = $form_state;). However, I would suggest you look at a cache_entity_availability table keyed on, perhaps, form_id and uid, just in case the session expires (servers down, network problem etc).
Thanks for the additional info, and good luck with the project.


Using transitive to prove symmetric

Question: Consider a relation R on a set A. Prove R is symmetric if R is transitive and there exists a c in A such that for every x in A, xRc and cRx. Help!!
Comment: Take $x$ and $y$ in $A$. Then if $x$~$y$ then $y$~$c$ and $c$~$x$ then by transitivity; $y$~$x$
Comment: Here is a [mathjax tutorial](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference). Be sure to show your work.
Answer: Assume $x,y\in A$ and $xRy$. We must show that $yRx$. We know that $xRc$ and $cRy$, by assumption. Since R is transitive we have $xRc \land cRy \rightarrow yRx$, proving that R is symmetric.
Comment: @Arthur I had. It is corrected now.

Using transitive to prove symmetric


PermissionError: [Errno 13] Permission denied on mac

Question: When I try to run the code below, the mac refuse the connection.
from http.server import BaseHTTPRequestHandler, HTTPServer
class RequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        message = "Welcome to COE 550!"
        self.protocol_version = "HTTP/1.1"
        self.send_response(200)
        self.send_header("Content-Length",len(message))
        self.end_headers()
        self.wfile.write(bytes(message, "utf8"))
        return

server = ('localhost', 80)
httpd = HTTPServer(server, RequestHandler)
httpd.serve_forever()

The output message is

PermissionError: [Errno 13] Permission denied
Comment: The PermissionError: [errno 13] permission denied error occurs when you try to access a file from Python without having the necessary permissions. See this question: https://stackoverflow.com/questions/36434764/permissionerror-errno-13-permission-denied
Answer: The port 80 is considered as privileged port(TCP/IP port numbers below 1024) so the process using them must be owned by root.  When you run a server as a test from a non-priviliged account, you have to   test it on other ports, such as 2784, 5000, 8001 or 8080.
You could either run the python process as root or you have to use any non privileged port to fix this issue.

server = ('localhost', 8001)
httpd = HTTPServer(server, RequestHandler)
httpd.serve_forever()


Check function exists in PowerShell module

Question: I've the following PowerShell script which searches in a directory for PowerShell module). All found modules will be imported and stored in a list (using the -PassThru) option.
The scrip iterates over the imported modules and invokes a function defined in the module:
# Discover and import all modules
$modules = New-Object System.Collections.Generic.List[System.Management.Automation.PSModuleInfo]
$moduleFiles = Get-ChildItem -Recurse -Path "$PSScriptRoot\MyModules\" -Filter "Module.psm1"
foreach( $x in $moduleFiles ) {
    $modules.Add( (Import-Module -Name $x.FullName -PassThru) )
}

# All configuration values
$config = @{
    KeyA = "ValueA"
    KeyB = "ValueB"
    KeyC = "ValueC"
}

# Invoke 'FunctionDefinedInModule' of each module
foreach( $module in $modules ) {
    # TODO: Check function 'FunctionDefinedInModule' exists in module '$module '
    & $module FunctionDefinedInModule $config
}

Now I would like to first check if a function is defined in a module before it gets invoked.
How can such a check be implemented?
The reason for adding the check if to avoid the exception thrown when calling a function which doesn't exists:
& : The term 'FunctionDefinedInModule' is not recognized as the name of a cmdlet, function, script file, or operable program

Answer: Get-Command can tell you this. You can even use module scope to be sure it comes from a specific module
get-command activedirectory\get-aduser -erroraction silentlycontinue

For example. Evaluate that in an if statement and you should be good to go.
Comment: Based on your answer I was able to figure out the correct syntax:
`foreach( $module in $modules ) { if ( Get-Command ($module.Name + '\NotExisting') -ErrorAction SilentlyContinue ) { Write-Host "Exists in module $($module.Name)"  } }`
Comment: The number of modules is dynamic and the script doesn't know the names of the modules. How can I set the "current" module as scope?
Answer: Use Get-Command to check if a function currently exists
if (Get-Command 'FunctionDefinedInModule' -errorAction SilentlyContinue) {
    "FunctionDefinedInModule exists"
}

Comment: Most of the modules will contain a function with the name 'FunctionDefinedInModule'. I need a way to check if the function exists in the "current" module.
Answer: If many functions need to be checked
try{
    get-command -Name Get-MyFunction -ErrorAction Stop
    get-command -Name Get-MyFunction2 -ErrorAction Stop
}
catch{
    Write-host "Load Functions first prior to laod the current script"
}

Answer: Test-Path -Path Function:\<function name>

Answer: Maybe try adding this function to your module?
function DoesFunctionExists {
    param(
        [string]$Function
    )

    $FunList = gci function:$Function -ErrorAction 'SilentlyContinue'
    foreach ($FunItem in $FunList) {
        if ($FunItem.Name -eq $Function) {
            return $true
        }
    }
    return $false
}

Answer: I needed it so often that I wrote module for this.


How to set "search" icon in the navigation tab bar in Ionic?

Question: I'm working on an Ionic project and I want to set the "search" icon in the tab bar of my navigation. Here's what I've tried so far:
<ion-tabs>
   <ion-tab [root]="tab1Root" tabTitle="Home" tabIcon="home" [rootParams]="apiuser"></ion-tab>
  <ion-tab [root]="tab3Root" tabTitle="Search" tabIcon="ion-md-search" [rootParams]="apiuser"></ion-tab>
  <ion-tab [root]="tab5Root" tabTitle="Search" tabIcon="md-search" [rootParams]="apiuser"></ion-tab>
  <ion-tab [root]="tab6Root" tabTitle="Search" tabIcon="search" [rootParams]="apiuser"></ion-tab>
</ion-tabs>

The result:

I don't know why the icon is not displayed.
I've attempted to use various icon names such as "ion-md-search", "md-search", and "search" for the tabIcon property, but none of them seem to work as expected. Can someone please provide guidance on how to correctly set the "search" icon in the tab bar of my Ionic application? My Ionic CLI version is 5.4.16, and I'm using Ionic Framework 3.9.4. I know that is very old version but i don't want to update it

The versions that I use:
Ionic:

   Ionic CLI          : 5.4.16
   Ionic Framework    : ionic-angular 3.9.4-201903121725
   @ionic/app-scripts : 3.2.4

Cordova:

   Cordova CLI       : not installed
   Cordova Platforms : android 8.1.0
   Cordova Plugins   : cordova-plugin-ionic-keyboard 2.1.3, cordova-plugin-ionic-webview 4.0.1, (and 23 other plugins)

Utility:

   cordova-res : not installed
   native-run  : 0.3.0

System:

   NodeJS : v14.18.1 (C:\Program Files\nodejs\node.exe)
   npm    : 6.14.15
   OS     : Windows 10

Answer:
npm install ionicons

import { Ionicons } from 'ionicons/icons';

 <ion-tabs>
  <ion-tab [root]="tab3Root" tabTitle="Search">
    <ion-icon name="search"></ion-icon>
  </ion-tab>

</ion-tabs>

Comment: I update my question.The first tab is okay, but the others idk why there's nothin
Comment: I tried as you said with `` but its not loading the image
Answer: Use ion-tab-bar and ion-tab-button. something like this:
<ion-tabs>
  <ion-tab-bar>
    <ion-tab-button tab="search">
      <ion-icon name="search"></ion-icon>
      <ion-label> Search </ion-label>
    </ion-tab-button>
     ....
  </ion-tab-bar>
</ion-tabs>

Comment: Ther's no  for ionic v3


Matrices with eigenvalues in geometric progression

Question: Given $a\in\Bbb F$ are there any natural $k\times k$ matrices in $\Bbb F^{k\times k}$ with $a^{0},a^1,a^2,\dots, a^{k-1}$ as eigenvalues where $\Bbb F$ is any char $0$ field?
The characteristic equation should have roots in G.P. as well. How should the char equation look like?
Can we conclude that all such matrices should be structurally similar and just look at circulants with these prescribed eigenvalues since other matrices are just conjugate by unitaries of diagonal matrices with specified numbers as roots? (Note circulants are rotations by FFT)
What is the matrix structure in general?
Comment: What kinds of matrices do you allow, $\text{Mat}_k\mathbb{C}$ or $\text{Mat}_k\mathbb{R}$? (After all, real matrices can have complex eigenvalues.)
Comment: Well, you know that the eigenspaces are 1-dimensional, and you must have 1 vector in each of them, so that's a complete classification (at least in $\mathbb{C}$).
Comment: In $\mathbb{C}$, how about the matrices that look like $diag (a^0, a^1, \ldots a^{k-1})$? Are those 'natural'?
Comment: changed question
Comment: @CalvinLin that is exactly the question. What are all the matrices? Are they just rotations of diagonlas?
Answer: If you have $k$-by-$k$ real matrices then the characteristic polynomial must be real. Assume that the eigenvalues are real and all have a common ratio. If they are all real then:

$\chi(s) \propto (s-v)^k$
$\chi(s) \propto (s-v)(s-rv)(s-r^2v)\ldots (s-r^kv)$

In the first case, the matrix is a multiple of the identity. In the second it is diagonalisable.
If there is a complex eigenvalue then its conjugate must also be an eigenvalue. If the common ratio is $r$ then there exists a positive integer $k$ for which
$$z=r^kz^* \implies |z|=|r^kz^*| \implies |z|=|r|^k|z^*| \implies |r|^k=1 \implies |r|=1$$
It follows that the eigenvalues must all have the same modulus: $|r^kz|=|r|^k|z|=|z|$. Moreover, since they appear in pairs, there must be an even number of them. Hence, the characteristic polynomial must be of the form
$$\chi(s) \propto (s-z_1)(s-z_1^*)\ldots(s-z_m)(s-z^*_m)$$
$$\chi(s) \propto (s^2-2\Re(z_1)s+\ell^2)\ldots(s^2-2\Re(z_m)s+\ell^2)$$
where $\ell$ is the common modulus of the roots which have a common ratio.
Comment: @JAS You asked "*How should the char equation look like?*" and that is what I tried to answer.
Comment: @JAS No, the common ratio has modulus one, but the roots need not have modulus one.
Comment: You got the char equations. How about the matrices?
Comment: @JAS But they are not proportional. Some have one root, some have $k$ roots, some have $\tfrac{1}{2}k$ pairs of complex conjugate roots if $k$ is even.
Comment: Your first case is $r=1$ (just a repeat of second case). You also missed a case with $r=-1$. and if the root $a$ is generic, we will have all char equations propoertional to the second one.
Comment: changed my comment.


How to know which file(file name) is transfered through FTP/SFTP

Question: Think of a situation I transferred a file through FTP, in which log I can find the name of the file transferred. Kindly mention the location of the log file.
Thanks In Advance.
Comment: Please edit with info on what ftp client you are using.
Comment: We cannot tell you what you did without sufficient detailed information about the tools you used. In general : servers only log detailed information if they are configured to do so (and you can't travel into the past to change the log level to start collecting details you need because you now need them) and the same for clients,  usually they don't maintain transfer logs although they can be configured to do (but not AFTER the fact)
Comment: No. No. No, whatever transfer protocol is used, I just told FTP as an example. i want to know if the file transferred through ftp. is it possible to check that particular file name in any of the log files in the server? Not in the client software used.
Answer: That depends if you used a commandline client or a gui client.
The commandline client is easy, the standard way is to provide a -v|--verbose flag to enable showing filenames when copied, or read the man page for said cli client. You can save this output to stdout by piping the command ftp -v folder remote.com:21 > log.txt notice the > log.txt at the end.
If it's a gui it's up to you to find the checkbox to enable logging, or read the manual where/if it describes logging.
Btw, you never mentioned what client, this is essential to give you the answer.
Comment: No. No. No, whatever transfer protocol is used, I just told FTP as an example. i want to know if the file transferred through ftp. is it possible to check that particular file name in any of the log files in the server? Not in the client software used.


Trying to solve "The method sort(List, Comparator) in the type Collections is not applicable for the arguments"

Question: I have an assignment where I have to sort patients based on emergency and if they have the same emergency level, then it's based on the order of arrival, but when I'm sorting, I'm getting an error saying "The method sort(List, Comparator) in the type Collections is not applicable for the arguments (List, Comparator)" Can anyone help? Below is all of my code:
import java.util.Comparator;
public class Patient implements Comparable<Patient> {
// attributes
private String name;
private int order; // order of arrival
private int emergency; // 1 is normal, 5 is life-and-death situation

// constructor
public Patient(int order, String name, int priority) {
    this.order = order;
    this.name = name;
    this.emergency = priority;
}

// getters and setters
public int getOrder() {
    return order;
}

public void setOrder(int order) {
    this.order = order;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public int getEmergency() {
    return emergency;
}

public void setEmergency(int emergency) {
    this.emergency = emergency;
}

public String toString() {
    return name;
}

@Override
public int compareTo(Patient patient) {
    // TODO Auto-generated method stub
    int total = 0;
    if (emergency < patient.emergency) {// compares patient emergency
        total = 1;
    } else if (emergency == patient.emergency) {
        if (order < patient.order) {// compares order of arrival in case emergencies are the same
            total = -1;
        } else if (order > patient.order) {
            total = 1;
        }
    } else if (emergency > patient.emergency) {
        total = -1;
    }
    return total;
}

public static class Comparators {
    public static final Comparator<Patient> EMERGENCY = (Patient p1, Patient p2) -> Integer.compare(p1.getEmergency(), p2.getEmergency());
    public static final Comparator<Patient> ORDER = (Patient p1, Patient p2) -> Integer.compare(p1.getOrder(), p2.getOrder());

}}

import java.util.*;
public class PatientManager{
private PriorityQueue<Patient> waitingList;

public PatientManager() {
    waitingList = new PriorityQueue<Patient>();
}

// Starter method
public void start() {
    String choice;
    Scanner in = new Scanner(System.in);
    String name;
    int emergency = 0;
    int order = 0;
    List<Object> list = null;
    Patient patient;
    System.out.println("-------------------------------");
    System.out.println("(1) New Patient.");
    System.out.println("(2) Next Patient.");
    System.out.println("(3) Waiting List.");
    System.out.println("(4) Exit.");
    System.out.println("-------------------------------");

    while (true) {
        //clear screen
        System.out.print("* Choose an item from the menu: ");
        choice = in.next();
        switch (choice) {
        case "1":
            System.out.print("Enter patient's name: ");
            name = in.next();
            System.out.print("Enter emergency [1 (low) to 5 (life-and-death)]: ");

            while (emergency < 1 || emergency > 5) {//testing for emergency and if any wrong values are given clears the scanner and tries again
                try {
                    emergency = in.nextInt();
                    if (emergency < 1 || emergency > 5)
                        System.out.print("(x) Wrong value. Try again: ");
                }
                catch (Exception e) {
                    System.out.print("(x) Wrong value. Try again: ");
                    in.next();
                }
            }
            order++;//Sets the number of the arrival.
            patient = new Patient(order, name, emergency);
            waitingList.add(patient);
            System.out.println("Patient added to the waiting list.");
            emergency = 0;//resetting value of emergency otherwise all patients will have the same one and loop will not run a second time
            Arrays.sort(waitingList.toArray());
            break;
        case "2":
            if (waitingList.isEmpty()) {
                System.out.println("No more patients.");
            } else {
                patient = waitingList.remove();
                System.out.println(patient.getName() + " is treated.");
            }
            break;
        case "3":
            if (waitingList.size() == 0) {
                System.out.println("No patients in the list.");
            } else {
                System.out.println("Waiting list includes:");
                list = new ArrayList<Object>(waitingList);
                Collections.sort(list, Patient.Comparators.EMERGENCY);
                for (int i=0;i<waitingList.size();i++) {
                    System.out.println("- " + list.get(i));
                }
            }
            break;
        case "4":
            System.out.println("Program terminated. Good bye!!");
            in.close();
            System.exit(0);
            break;
        // print list name and emergency
        default:
            System.out.println("(x) Wrong choice.");
            break;
        }
    }
}}

Answer: The problem is that the list you're sorting has been declared as a list that can contain arbitrary objects. You can't apply a comparator of Patients to objects that might not be Patients.
To solve it, declare your list as a list of Patients:
List<Patient> list = new ArrayList<>(waitingList)


How do I deploy my GAE project for only a specific folder?

Question: I wonder how do I deploy my Google App Engine project only for a specific folder?
e.g. If my project source folder is "src", and inside this src folder have many sub folders. Say, I have css, app, images, and js folders, but I want to deploy only css, app and images folders to the GAE, I want GAE to ignore js folder during the deployment, is there any way to do so with some setting in app.yaml file?
Thanks!
Joel
Answer: Have a look at skip_files
Skipping Files

Files in your application directory whose paths match a static_dir path or a static_files upload path are considered to be static files. All other files in the application directory are considered to be application program and data files.
The skip_files element specifies which files in the application
  directory are not to be uploaded to App Engine. The value is either a
  regular expression, or a list of regular expressions. Any filename
  that matches any of the regular expression is omitted from the list of
  files to upload when the application is uploaded.
Comment: @JoelT. be aware that by using `skip_files` it does replace the whole app you deployed previously. so if you uploaded javascript files in your js folder to the app and then you use skip_files you won't have them online any more.
Comment: @aschmid00. Thanks! In fact I use skip_file mainly for my backup folders, such as js_bac, not exactly the working folder js. Anyway thanks for the advice! :)
Comment: great. Feel free to accept the answer if it was what you were looking for :) it also helps others who can then see this as answered.
Comment: It's not a great solution though; how can we target just one directory for example?
Comment: if it's a regex (and it's been a while!) then you can use that to filter in/out things as well by including the path in the regex?
Answer: You can now add a .gcloudignore file to the root of your project (https://cloud.google.com/sdk/gcloud/reference/topic/gcloudignore). The syntax is the same as .gitignore files.
For the OPs case, placing the following in the root folder (next to app.yaml) should do the trick:
# .gcloudignore

src/js/


ubuntu 18.04 driver setup for nvidia tesla k40m gpu for use with matlab

Question: I have an ubuntu 18.04 (System76 desktop) that has built in Intel graphics. I tried plugging in an nVidia K40m gpu card for matlab computations, but I am running into numerous problems.  The card has a gpu but it is just for computing, not for driving a monitor.  I have the matlab parallel toolbox that is designed to work with this type of gpu.
1) When I install the nVidia driver, the machine seems to try to use the K40m card as a display and stops using the Intel graphics.  I can't figure out how to stop this without removing the nVidia driver driver.
2) I can't seem to get the right CUDA driver to work with Matlab either.
Any sugestions for how to fix these?
Comment: I can't test this as I have no external GPU and am still on Ubuntu 16.04. I would however let go of trying to use one GPU for this and one for that, I'd start by trying to use NVIDIA driver for both screen and computation.Simpler debugging. Note that it may be required to turn off secure boot from BIOS before installing the driver. After installing NVIDIA driver try running nvidia-smi on bash terminal to see that all is well. You can post output here if issues come up. Then try running a = gpuArray; on matlab and see if you get errors.
Comment: Thanks, but this machine has Intel graphics and the K40m card is compute only.  So, I have to use the Intel graphics for display and MATLAB only works with nVidia GPUs.
Answer: I did some search and the latest driver version for your gpu is 410.
Suppose you want to use CUDA 10, then there's no need to install nvidia driver at first since the 410 driver is already included in CUDA 10.
Read the cuda10 Installation Guide for linux creafully.
https://developer.nvidia.com/cuda-downloads?target_os=Linux&target_arch=x86_64&target_distro=Ubuntu&target_version=1804&target_type=runfilelocal
Download the runfile version cuda, and be very careful to every step of its command line prompts.
These steps works for me, with a Intel graphics and Nvidia graphics together in my laptop.(and I use Inter one to show). I can't make sure it also works for you since the gpu is not same.
Please follow the cuda installation guide for linux at first or something not clear here.

remember the location of cuda10 run file.
make sure disable Nouveau,
enter or touch this file: /etc/modprobe.d/blacklist-nouveau.conf

input two lines:
blacklist nouveau
options nouveau modeset=0

save and then command line:
sudo update-initramfs -u

systemctl set-default runlevel3.target to make your computer only command line version after reboot,then reboot, use command line
lsmod | grep nouveau,to check whether you disable nouveau, if there's no output, it's right.
sudo sh cuda_10.0.130_410.48_linux.run

(1)EULA Acceptance-------y
(2)CUDA Driver installation------y
(3)openGL-------n
(4)x-server-------n
(5)CUDA Toolkit installation location --------------Enter
(6)CUDA Samples installation and location ---------------Enter
If everything is fine, command line:
systemctl set-default runlevel5.target

Then reboot.

set environment path in ~/.bashrc
PATH=/usr/local/cuda-10.0/bin
LD_LIBRARY_PATH=/usr/local/cuda-10.0/lib64
then source ~/.bashrc
make sure all things are right.
cat /proc/driver/nvidia/version
nvcc -V
nvidia-smi
test cuda
 cd your-own-sample-path to/1_Utilities/deviceQuery
sudo make
./deviceQuery
Comment: would the installation be the same for a k80 with a GTX 780 for graphics?


Formatar data no carregamento da página

Question: Olá queria formatar a data do meu formulário no carregamento da página, porque a data está vindo do banco de dados no formato internacional (yyyy-mm-dd).
Fiz essa função para formatar minha data, porém eu tenho 2 formulários na mesma página e ambos tem inputs do mesmo nome. Meu input  está no formato de texto.

function formataData(ele){
    var value = $(ele).val();
    var d = undefined;
    if(value.search('-') > -1){
        d = $(ele).val().split('-');
        console.log(d);
    } else if($(ele).val().search('/') > -1) {
        d = $(ele).val().split('/');
        console.log(d);
    }

    if(d !== undefined){
        if(d[0].length > 3){
            $(ele).val(d[2]+'/'+d[1]+'/'+d[0]);
        }else {
            $(ele).val(d[2]+'-'+d[1]+'-'+d[0]);
        }
    }
}

Resumindo o que eu queria
-A página carrega assim:

<input type="text" name="vencimento" value="yyyy-mm-dd" class="form-control">

-Queria chamar minha função javascript/JQuery no carregamento da página para ficar assim:

<input type="text" name="vencimento" value="dd-mm-yyyy" class="form-control">

Usei $(document).ready(function(){}); mas ficou cambiarra demais :/ queria reaproveitar essa função em outros códigos! Obrigado pela atenção.
Obs: tinha esquecido, quero chamar esta função para todos os campos de data no carregamento da página também
Comment: porque não faz no php?
Comment: Porque não mudas a query na base de dados para te dar o que queres de inicio?
Comment: Seria melhor mesmo. Mas como eu chamaria uma função JS no load da página? Sem ter que fazer gambiarra. @Sergio
Comment: e como você traz a data do banco?
Comment: Qual linguagem da sua página?
Comment: @LeoCaracciolo Estou usando PHP, Js/JQuery, Mysql
Answer: Se você não puder mudar como os dados vêm da base, use o seguinte:
$(document).ready(function() {

   ajeita();

});

Vai ajeitar o formato em todos os campos com a classe form-control

Teste no snippet abaixo:

function ajeita() {
    $('input.form-control').each(function () {
        var data = $(this).val().split('-').reverse();
        $(this).val(data.join('-'))
    });
};

//opção sem jQuery
const ajeita2 = () => {
  document
  .querySelectorAll('.form-control')
  .forEach(el => el.value = el.value.split('-').reverse().join('-'))
}

<input type="text" value="1990-10-25" class="form-control" />

<input type="text" value="1991-11-16" class="form-control" />

<input type="text" value="1980-08-25" class="form-control" />

<input type="text" value="2010-05-04" class="form-control" />

<input type="button" value="testar" onclick="ajeita();" />
<input type="button" value="testar (sem jQuery)" onclick="ajeita2();" />
Comment: Editei porque eu tinha usado "yyyy/mm/dd" em vez de "yyyy-mm-dd"
Comment: Tranquilo, obrigado, essa função each é bem útil, sabia que existia mas não o que fazia. @LeonKlaj
Answer:
$dataBanco1="2016-01-21"; // pra servir de exemplo
$dataBanco2="2016-01-23"; // pra servir de exemplo
$data1 = date('d/m/Y', strtotime($dataBanco1));
$data2 = date('d/m/Y', strtotime($dataBanco2));
<input type="text" name="vencimento" value="<?php echo $data1 ?> " class="form-control">
<input type="text" name="vencimento" value="<?php echo $data2 ?> " class="form-control">
Comment: Sim, sim, eu tinha entendido @LeoCaracciolo porém nem todos campos vem do Banco de dados, queria fazer isso também, para quando o usuário fosse criar um dado, entende? Mas mesmo assim obrigado!
Answer: Já venho tarde talvez com a minha resposta..., mas:
Se queres fazer isso no browser e todas as datas estão em formato yyyy-mm-dd podes fazer assim:
$('input.form-control').each(function(){
    this.value = this.value.split('-').reverse().join('-');
});

Se podes mudar isso no servidor, no SQL, podes fazer:
DATE_FORMAT(coluna_data, "%d-%m-%Y") AS coluna_data

Se podes mudar isso no servidor, no PHP, podes fazer:
$data = date("d-m-Y", strtotime($dataOriginal));
echo '<input type="text" name="vencimento" value="'.$data.'" class="form-control">';

Comment: Bacana, mas como seria minha query no SQL? select DATE_FORMAT(coluna_data, "%d-%m-%Y") from relatorios. ?
Comment: @MarceloRafael poderia ser `SELECT DATE_FORMAT(coluna_data, "%d-%m-%Y") AS coluna_data FROM relatorios;`.
Comment: posso trocar "$d-%m-%Y" por: "$d/%m/%Y" ? Por barras " / ".
Comment: @MarceloRafael sim podes.

Formatar data no carregamento da página


Bases and superbases

Question: So, in the book "The Sensual (Quadratic) Form" By Conway and Fung, together with the notion of the base for the lattice, there is also a notion of superbase:
"In the same spirit, a strict base is an ordered pair $(e_1, e_2)$ whose
integral linear combinations are exactly all the lattice vectors. A lax
base is a set $\{\pm e_1, \pm e_2\}$ obtained from a strict base.
Finally, a strict superbase is an ordered triple $(e_1, e_2, e_3)$, for
which $e_1+e_2+e_3 = 0$ and $(e_1, e_2)$ is a strict base(i.e., with strict vectors), and a lax superbase is a set $\{\pm e_1, \pm e_2, \pm e_3\}$ where $(e_1, e_2, e_3)$ is a strict superbase".
And then there is the following statement:
"On the other hand, each base $\{\pm e_1, \pm e_2\}$ is in just two superbases:
$$
\{\pm e_1, \pm e_2, \pm (e_1+e_2)\},\ \ \{\pm e_1, \pm e_2, \pm (e_1-e_2)\}.
$$
Note that each of these really is a superbase".
Can you please explain, why each of these form a (lax) superbase? For I understand that if $(e_1,e_2,e_1+e_2)$, then $2e_1 + 2e_2 = 0$, which cannot be the case.
Answer: If $(e_1,e_2)$ is a strict base, then so are $(-e_1,e_2)$, $(e_1,-e_2)$ and $(-e_1,-e_2)$. These all induce the same lax base $\{\pm e_1,\pm e_2\}$.
Next, given a strict base $(e_1,e_2)$, there is a unique superbase obtained from it: $(e_1,e_2,-e_1-e_2)$. The superbases related to the other strict bases above are $(-e_1,e_2,e_1-e_2)$, $(e_1,-e_2,-e_1+e_2)$, and $(-e_1,-e_2,e_1+e_2)$.
The superbases $(e_1,e_2,-e_1-e_2)$ and $(-e_1,-e_2,e_1+e_2)$ induce the same lax superbase:
$$\{\pm e_1,\pm e_2, \pm(e_1+e_2)\},$$
and $(-e_1,e_2,e_1-e_2)$ and $(e_1,-e_2,-e_1+e_2)$ induce the same lax superbase:
$$\{\pm e_1,\pm e_2,\pm(e_1-e_2)\}.$$

Bases and superbases


Convergence in probability of a random variable

Question: I need to prove that $(X_n^2 -X)^2\to 0$ in probability $\Rightarrow X_n^2\to X$ in probability.
I tried solving it with the triangle inequality, but it didn't get me anywhere. Is there another approach to solve it?
Answer: Hint: For any $\varepsilon>0$
$$
[|X_n^2-X|>\varepsilon]=[(X_n^2-X)^2>\varepsilon^2].
$$

You need to show that
$$
P(|X_n^2-X|>\varepsilon)\xrightarrow[n\to\infty]{}0
$$
for all $\varepsilon>0$. So, let such an $\varepsilon>0$ be given. Then
$$
P(|X_n^2-X|>\varepsilon)=P((X_n^2-X)^2>\varepsilon^2).
$$
Now argue that the right-hand side goes to zero as $n\to\infty$.
Comment: It has nothing to do with convergence in mean square. You need to use your assumption. What does it state?
Comment: That's not given. That is what you want to show. Please, take a step back and write down what the assumption is and what it means.
Comment: I'm sorry, but I can't see how to get it from that :/
Comment: @Buzi: I have added some additional hints.
Comment: All I can think of that it has something to do with convergence in mean square.. But I am not sure that I can assume that it exist.
Comment: Oh, Now I think I got it.. well $|X_n^2-X|^2>\varepsilon$ is given. So it is actually straight forward?
Comment: What do you mean by "is given"?
Comment: I mean that $ P\{|X_n^2 - X|>\varepsilon\}\to 0$, so it is also the same for the square of both sides?
Comment: Sorry, I meant $\mathrm{P}\{ ( X_n^2 - X)^2>\varepsilon\}\to 0$ is given,  so it still exist for $\varepsilon ^2$


TornadoFX: Compare 2 form values in ValidationContext

Question: In tornadofx, I am trying to validate if two values of inputs in a form equal. I followed this guide and everything works as expected. But I encountered that I have no way how to check if the two values in inputs equal.
For example, let's say I want to create the simple registration form where I have to check if the 2 passwords equal. What I tried was:
val validator = ValidationContext()

validator.addValidator(this, this.textProperty()) {
    if(!password!!.isEqualTo(it).get()) //password1 != password2 -> does not work
        error("Passwords do not equal")
}

I looked into the login example hoping I would find help in the example code but without success.
Is there a way to compare the inputs in the validation context? If so how?
EDIT: This does work but I don't think it is the desired way to check the inputs in the validation context. Is there a better way?
if (password.get() != password2.get())
    error("Passwords do not equal") //Returns the error message

Answer: You can create validators for each field so that they compare against the other field. Then you need to make sure to re-evaluate the validator for the other field when a field is changed. Make sure to include focusFirstError = false to avoid the focus to shift when you make a change in the input fields.
class DualValidationForm : View() {
    private val vm = object : ViewModel() {
        val text1Property = bind { SimpleStringProperty() }
        val text2Property = bind { SimpleStringProperty() }
    }

    override val root = form {
        fieldset("Make sure both fields have the same value") {
            field("Text 1") {
                textfield(vm.text1Property) {
                    validator {
                        if (it == vm.text2Property.value) null else ValidationMessage("Not the same!", ValidationSeverity.Error)
                    }
                    vm.text1Property.onChange {
                        vm.validate(focusFirstError = false, fields = vm.text2Property)
                    }
                }
            }
            field("Text 2") {
                textfield(vm.text2Property) {
                    validator {
                        if (it == vm.text1Property.value) null else ValidationMessage("Not the same!", ValidationSeverity.Error)
                    }
                    vm.text2Property.onChange {
                        vm.validate(focusFirstError = false, fields = vm.text1Property)
                    }
                }
            }
            button("You can click me when both fields have the same value") {
                enableWhen(vm.valid)
                action {
                    information("Yay!", "You made it!").show()
                }
            }
        }
    }
}

Comment: Yes thats, +/- what I expected (more in my edited question), there isn't a really neater way of doing such things is there?
Comment: Not that I can think of :)


Using multiple submit buttons in one form with a tag?

Question: I am using submit button with a tag. However, one more button needs to be used.
Can I use two submit buttons with a tag in one form?

    ...
    <form id="action-1" action='my action1 html' method="post">
        <input class="mini-action" type="text" name="mini" value="1">
    </form>

    // A tag submit button currently in use
    action-1

    // ToDo: Here I want to send to action2 url when submit button is clicked.
    action-2

Comment: The tags you are showing are not submit buttons.
But yes you can it will work.
Answer: The tags you used are not submit buttons but links hijacked to act as buttons, additionally it is considered to be best practice to place the submit buttons inside the form they submit.
You can override the submit button's action with the attribute formaction
<form action="action-1">

  <button type="submit">this will trigger action-1</button>
  <button type="submit" formaction="action-2">this will trigger action-2</button>
</form>


Extract image meta data and set field values on Media upload

Question: I'm extracting IPTC and EXIF data when the user uploads an image using the Media Library UI.
Using hook_form_alter I can get the URI of the uploaded file in the media_library_add_form_upload form, and extract the data from it. So far, so good.
However, the form does not (yet?) contain the other fields attached to the media type (e.g. title, description, copyright) so I can't set the values.
How can I set the values in the form that is shown after I've selected and upload an image?
Answer: The form fields are nested under $form['media'][0]. Having extracted data from the uploaded file, we can set the data as default values on the fields.
/**
 * Implements hook_media_form_alter().
 */
function ds_media_exif_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id !== 'media_library_add_form_upload') {
    return;
  }

  if (!array_key_exists('upload', $values)) {
    return;
  }

  $upload_id = $values['upload'][0];
  $file = File::load($upload_id);
  $uri = $file->getFileUri();

  // Extract exif, iptc data here.
  $data = extractFileData($uri);

  // Title defaults to the file name.
  if (isset($data['title'])) {
    $form['media'][0]['fields']['name']['widget'][0]['value']['#default_value'] = $data['title'];
    // Set alt field to title.
    $form['media'][0]['fields']['field_media_image']['widget'][0]['#default_value']['alt'] = $data['title'];
  }

  // Some more fields: field_description and field_copyright.
  $form['media'][0]['fields']['field_description']['widget'][0]['#default_value'] = $data['description'] ?: '';
  $form['media'][0]['fields']['field_copyright']['widget'][0]['value']['#default_value'] = $data['copyright'] ?: '';
}


Different seating arrangements on a 6 seater

Question: Six actors sit in a row to have their photographs taken. Romeo and Juliet insist on sitting next to each other. Caesar refuses to sit next to Brutus. Falsta and Puck don't mind where they sit. How many completely different ways altogether, can they be seated?
Answer: Another way:
Romeo and Juliet can be glued together as $RJ$ or $JR:\;\; 2$ ways
Leave out Brutus and Caesar for the moment, then there are $3$ entities, permutable in 3! ways
$\Large\uparrow\bullet\Large\uparrow\bullet\Large\uparrow\bullet\Large\uparrow$
with $4$ gaps where Brutus and Caesar can be inserted in $4\times$3 ways.
Putting everything together yields $2\times3!\times4\times3 = 144$
Answer: Romeo and Juliet have internally two ways to sit. If we take that into account we can for all practical purposes glue them together treat them as one. We are then down to 5 "people". So now we consider Caesar, Brutus, Falsta, Puck and Julieo. Caesar and Brutus sitting together is internally two ways and externally (just four people-hybrids now) $2 \cdot 4!$. We need to remove that from the $5!$ if all 4 and R-J hybrid were allowed to sit in any order. So all in all:
$$2\cdot(5! - 2\cdot4!) = 144$$
Note this includes counting if Romeo is on the left and Julia on the right or vice versa.
Comment: That should be $2\cdot5!-4\cdot4!=144$ or $2\cdot(5!-2\cdot4!)=144$
Comment: Yes must have slipped a button, there goes better I hope.
Answer: This is kind of a brute force approach, but it works pretty well since there aren't too many options.
Romeo and Juliet are represented by Q, Brutus and Caesar are represented by X, and Falsta and Puck are represented by ?.  We will now list all the possible seating arrangements.  Note that each of the pairs are interchangeable, so we will multiply our final result by 8.
QQX?X?  |  QQX??X  |  QQ?X?X
XQQX??  |  XQQ?X?  |  XQQ??X  |  ?QQX?X
X?QQX?  |  X?QQ?X  |  ?XQQX?  |  ?XQQ?X
I have listed 11 arrangements here.  The first 7 arrangements have their mirror counterparts where the QQ are on the right side of the 6 seats, so there are really 11+7=18 arrangements I should have listed.  Multiplying this by 8 gives a total of 144 possibilities.
It's entirely possible I have neglected something, so someone should check my work.
EDIT: I think a good check is that I ended up with 18 arrangements, which only has one factor of 2.  (i.e., I can only divide 18 by 2 wholly once.)  This means that I have accounted for all of the symmetries -- with the one I included in the 18 being the reflective symmetry of the seating arrangements.  (i.e., if one seating arrangement works, then the complete reverse order works too).


Configuring AWS ElasticCache redis Cluster-3.2.4 with Laravel-5.4.32 using Predis

Question: I am trying to use ElasticCache Redis Cluster(Cluster mode enabled not sentinel) on Laravel-5.4.32 but getting below error:
1/1) ServerException
MOVED 13491 10.0.1.199:6379
My database.php looks like below:

<code>'redis' => [

    'client' => 'predis',
    'cluster' => true,

    'default' => [
        'host' => env('REDIS_HOST', '127.0.0.1'),
        'password' => env('REDIS_PASSWORD', null),
        'port' => env('REDIS_PORT', 6379),
        'database' => 0,
    ],

],
</code>

REDIS_HOST value is been provided using .env file.
My application works fine with single redis instance.
Comment: I have already tried the configuration mentioned here: https://stackoverflow.com/questions/41091103/laravel-predis-redis-cluster-moved-no-connection-to-127-0-0-16379

It does not work for me. same error.
Comment: Please see this post: PHP [demo code](https://stackoverflow.com/questions/45684076/cannot-connect-redis-cluster-in-elasticache-to-php-using-phpredis-library/51186536#51186536) using AWS ElastiCache Redis.
Answer: Below configuration worked for me:
<code>'redis' => [
    'client' => 'predis',
    'options' => [
        'cluster' => 'redis',
    ],
    'clusters' => [
        'default' => [
            [
                'host' => env('REDIS_HOST', 'localhost'),
                'password' => env('REDIS_PASSWORD', null),
                'port' => env('REDIS_PORT', 6379),
                'database' => 0,
            ],
        ],
    ],
],
</code>
Actually, this is clearly mentioned in laravel documentation: https://laravel.com/docs/5.4/redis#configuration


Remove jQuery, and jQuery UI and add migrate plugin with Updated jQuery and UI

Question: I am trying to use drupal_add_html_head to add script elements to the head tag, however, this is important that these script tags are not self-closing because that is not the correct way to add them.
How do I do this:
$html5jquerymigrate = array(
    '#tag' => 'script',
    '#attributes' => array(
        'src' => libraries_get_path('jquery.migrate', true) . '/jquery-migrate-1.2.1.min.js',
    ),
    '#prefix' => '',
    '#suffix' => '',
);

drupal_add_html_head($html5jquerymigrate, 'html5jquerymigrate');

But instead of getting it printed out like this:
Answer: Ok, there was no 1 step solution to this problem.  So here's what I did in case anyone else wants to know.
This is a 3 STEP solution to adding jQuery 1.9 and jQuery UI 1.10 functionality to Drupal 7.  Not sure about other versions of Drupal.
1 - Needed to remove Drupals old jQuery library of version 1.4 and replace with version 1.9, so in my theme, I added the following function:
In template.php
function MYTHEME_js_alter(&$js) {

    $js['misc/jquery.js']['data'] = 'http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js';

    // Adding this ensures that the UI functionality gets added at all times!  Even when logged out of the site, since we have functionality on the site that requires this when logged out!
    if (!isset($js['misc/ui/jquery.ui.core.min.js']))
    {
        drupal_add_js('http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js');
    }
    else
        $js['misc/ui/jquery.ui.core.min.js']['data'] = 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js';
}

2 - Now that this is done, before we can really take advantage of Drupal with any other jquery library that is greater than 1.8 (which sucks), we need to add in the migrate plugin found here:  http://blog.jquery.com/2013/05/08/jquery-migrate-1-2-1-released/
I have the Libraries Module installed, so I just put the JS in my Libraries folder called: jquery.migrate
3 - Than I added this to template.php file for my theme:
function MYTHEME_page_alter($page) {
    drupal_add_js(libraries_get_path('jquery.migrate') . '/jquery-migrate-1.2.1.min.js');
}

Now I can use all of the greatest and newest technologies in jQuery 1.9 and beyond while still being able to have Drupal 7 not crash on me!  AMEN!  HALLELUJAH!!!!
Answer: You can use drupal_add_js function instead. Read the API Documentation here: drupal_add_js
A Simple Example:
// This may do the work for you.
drupal_add_js('/sites/all/libraries/jquery.migrate/jquery-migrate-1.2.1.min.js');
// Using a CDN
drupal_add_js('http://code.jquery.com/jquery-latest.min.js', 'external');

Comment: it is a good practice and the important thing is you are telling drupal that it is a external JS file so drupal will not add any tokens or version ID, helpful for avoiding errors.
Comment: To use CDN simply add a `external` parameter, see my edited answer.
Comment: So, and if you want to add a js library from a CDN??
Comment: Ok, this is almost what I want... BUT I need it to be inserted at the VERY TOP of the page... before any other `script` files.  How to do this?  I removed Drupals default jquery...  But need to add my own so that it comes up before any other jquery files, how?
Comment: why do you add `'external'` in the 2nd parameter?  It doesn't seem to make a difference without that parameter altogether.


Custom JQuery code does not load

Question: Iam trying to call custom JQuery code but its just not working
new HtmlCommand() and InvokeCommand(method:css) is just working fine, just my custom script is not executed:
Controller:
    <?php
    /** * @file * Contains Drupal\ajax_example\AjaxExampleForm */

    namespace Drupal\ajax_example\Form;

    use Drupal\ajax_example\Ajax\AjaxExampleCommand; use Drupal\Core\Ajax\AjaxResponse;
    use Drupal\Core\Ajax\CommandInterface;
    use Drupal\Core\Ajax\ChangedCommand;
    use Drupal\Core\Ajax\CssCommand;
    use Drupal\Core\Ajax\HtmlCommand;
    use Drupal\Core\Ajax\InvokeCommand;
    use Drupal\Core\Form\FormBase;
    use Drupal\Core\Form\FormStateInterface;

    class AjaxExampleForm extends FormBase{

    /**
     * @param array $form
     * @param FormStateInterface $form_state
     *
     * @return array
     */
    public function buildForm(array $form, FormStateInterface $form_state) {

        $form['submit'] = array(
            '#type' => 'button',
            '#value' => 'Login',
            '#attached' => array(
              'library' => array(
                'ajax_example/ajaxCustom','core/jquery')),
            '#ajax' => array(
                'callback' => 'Drupal\ajax_example\Form\AjaxExampleForm::ajaxCallOwn',
                'event' => 'click',
                'progress' => array(
                    'type' => 'throbber',
                    'message' => 'ajaxOwn',
                ),
        ));
    }

public function ajaxCallOwn(array &$form, FormStateInterface $form_state)
  {
    $ajax_response = new AjaxResponse();

    //$ajax_response->addCommand(new HtmlCommand('#edit-user-name2--description', "changedDessrition!!!!"));

    $ajax_response->addCommand(new InvokeCommand(NULL,'changeDescription'));
    return $ajax_response;
  }

Command:
<?php

/**
 * @file
 * Contains Drupal\ajax_example\Ajax\AjaxExampleCommand
 */

namespace Drupal\ajax_example\Ajax;

use Drupal\Core\Ajax\CommandInterface;

class AjaxExampleCommand implements CommandInterface{

  /**
   * @var string
   */
  protected $blub;
  // Constructs a SystemBlubCommand object.

  /**
   * Constructs an SlideDownCommand object.
   * @param string $blub
   */

  public function __construct() {
    $this->blub = "changed!!!!";
  }

  public function render() {
    return array(
      'command' => 'changeDescription',
      'method' => NULL,
      'blub' => $this->blub,
    );
  }
}

ajaxCustom.js
(function ($, Drupal) {

    /**
     * Command to Slide Down page elements before removing them.
     *
     * @param {Drupal.Ajax} [ajax]
     * @param {object} response
     * @param {string} response.blub
     * @param {number} [status]
     */

    Drupal.AjaxCommands.prototype.changeDescription = function (ajax, response, status) {

        alert("asdfasdgf");
        $("#edit-user-name--description").remove();
        $("#edit-user-name--description").html(response.blub);

    };

})(jQuery, Drupal);

ajax_example.libraries.yml:
ajax_example:
  version: 1.x
  js:
    js/ajaxCustom.js: {}
  dependencies:
    - core/drupal
    - core/drupal.ajax
    - core/jquery

Tried so many things like : this
with no success
This is the error I get in the Browser:
    Uncaught TypeError: Cannot read property 'apply' of undefined
    at Drupal.AjaxCommands.invoke (ajax.js?v=8.4.4:569)
    at Drupal.Ajax.success (ajax.js?v=8.4.4:407)
    at Object.success (ajax.js?v=8.4.4:222)
    at Object.t.success (jquery.form.min.js?v=3.51:11)
    at i (jquery.min.js?v=3.2.1:2)
    at Object.fireWith [as resolveWith] (jquery.min.js?v=3.2.1:2)
    at A (jquery.min.js?v=3.2.1:4)
    at XMLHttpRequest.<anonymous> (jquery.min.js?v=3.2.1:4)
invoke @ ajax.js?v=8.4.4:569
Drupal.Ajax.success @ ajax.js?v=8.4.4:407
success @ ajax.js?v=8.4.4:222
t.success @ jquery.form.min.js?v=3.51:11
i @ jquery.min.js?v=3.2.1:2
fireWith @ jquery.min.js?v=3.2.1:2
A @ jquery.min.js?v=3.2.1:4
(anonymous) @ jquery.min.js?v=3.2.1:4
XMLHttpRequest.send (async)
send @ jquery.min.js?v=3.2.1:4
ajax @ jquery.min.js?v=3.2.1:4
e.fn.ajaxSubmit @ jquery.form.min.js?v=3.51:11
Drupal.Ajax.eventResponse @ ajax.js?v=8.4.4:316
(anonymous) @ ajax.js?v=8.4.4:255
dispatch @ jquery.min.js?v=3.2.1:3
q.handle @ jquery.min.js?v=3.2.1:3

If I use InvokeCommand error in recent logs:
Deprecated function: call_user_func_array() expects parameter 1 to be a valid callback, non-static method Drupal\ajax_example\Form\AjaxExampleForm2::ajaxCallOwn() should not be called statically in Drupal\Core\Form\FormAjaxResponseBuilder->buildResponse() (line 69 of /Applications/MAMP/htdocs/core/lib/Drupal/Core/Form/FormAjaxResponseBuilder.php) #0

Comment: `InvokeCommand` invokes a jQuery function on the elements, so you'd need `$.fn.changeDescription = function(data) { alert(data); };`. Otherwise you should use the command you've created: `$ajax_response->addCommand(new AjaxExampleCommand());`
Comment: Clive beat me to it. Yes you want the PHP class command you made, not InvokeCommand that's for arbitrary JS function calls.
Comment: Thanks for your anser, but I still get the error:  Uncaught TypeError: Cannot read property 'apply' of undefined
Even in another Controller where new  AppendCommand works fine.
And I alway do: drush cc drush and drush cr
This really drives me nuts since 3 days
Comment: Why is method null and what is "blub"? You can compare it here to a module I wrote: http://cgit.drupalcode.org/sweetalert/tree
Comment: Should be `'library' => array('module_name/library_name')),` So in your case, since the library name is the same as the module name, `'library' => array('ajax_example/ajax_example')),`
Comment: You're mixing up concepts here and changing code in the original question making it harder to follow. You can't point an Ajax event on a form item at a command directly, you can only instantiate and return them as part of an AjaxResponse inside of an Ajax callback within a form.
Comment: Plus your attachments are wrong too
Comment: Again if you want to use your AjaxExampleCommand, you need to create it and return it in the AjaxRepsonse. You DONT need InvokeCommand, that is not what you think it is.
Answer: Thanks to No Sssweat, that was the problem!
I thought it should be:
'library' => array('module_name/nameOfJSFile'));

Thanks to Kevin as well, your module sweetalert gave me the right hint.

Custom JQuery code does not load


what should as a unit test case one should write for a function like this. code snippet would be helpful

Question: func Home(w http.ResponseWriter, r *staticAuth.AuthenticatedRequest) {
    t, err := template.ParseFiles("index.html") //parse the html file homepage.html
    if err != nil {                             // if there is an error
        log.Print("template parsing error: ", err) // log it
    }
    err = t.Execute(w, nil) //execute the template and pass it the HomePageVars struct to fill in the gaps
    if err != nil {         // if there is an error
        log.Print("template executing error: ", err) //log it
    }
}

Comment: Please go through - How do I ask a good [question](https://stackoverflow.com/help/how-to-ask) ?
Comment: You shouldn't have handlers that parse templates. See: [It takes too much time when using "template" package to generate a dynamic web page to client in golang](https://stackoverflow.com/questions/28451675/it-takes-too-much-time-when-using-template-package-to-generate-a-dynamic-web-p/28453523#28453523). Once you move the template parsing out of the handler, it also becomes much easier to test.
Comment: A good unit test tests all meaningful input values, and that they produce all meaningful output values. Input includes global state, such as global variables, databases, or the filesystem. Output includes side effects (such as modifying global variables, changing database entries, or writing to the filesystem). Given that: What are the meaningful inputs for this function? And given those inputs, what should the outputs be? Write tests that cover these cases.
Answer:
func Home(w http.ResponseWriter, r *staticAuth.AuthenticatedRequest) {
    t, err := template.ParseFiles("index.html") //parse the html file homepage.html
    if err != nil {                             // if there is an error
        log.Print("template parsing error: ", err) // log it
    }
    err = t.Execute(w, nil) //execute the template and pass it the HomePageVars struct to fill in the gaps
    if err != nil {         // if there is an error
        log.Print("template executing error: ", err) //log it
    }
}

In your code, you check for and log errors, then you keep going and ignore the errors.


Power of uniformly most powerful test

Question: Let $X_{1}, \dots, X_{n}$ be independent random sample with cumulative distribution function $F_{\theta}(x) = 1 - 2^{-(x-\theta)}$ for $x > \theta$ and $0$ elsewhere, where $\theta$ is unknown parameter. Let us consider the uniformly most powerful test of $H_{0}: \theta = 0$, against $H_{1}: \theta >0$ at significance level $0.01$. For what $n$ at $\theta > 0$ power is more than $0.64$.
I know that I am supposed to use Karlin-Rubin theorem and i showed that it has monotone likelihood function, I just don't know how to manipulate this distribution to find critical region. Any help?
Comment: Power is relative to a specific alternative, and you haven't provided one.  For example, consider $\theta = 100$ and $n=100$.  In that case, your power is going to be $> 0.64$.  Consider $\theta = 0.00000001$ and $n=100$.  Your power is is going to be roughly equal to your significance level $0.01$.  So the question, as stated, can't be answered; for any $n$, you can find a $\theta$ close enough to zero such that the power is arbitrarily close to your significance level.
Comment: Why do you uses $\theta_1$ instead of $\theta$? You need to add the self-study tag to your question.
Comment: Added and changed
Comment: Okay, then notice that it is just a shifted exponential distribution with location/shift $\theta$ and scale $1/\ln 2$ (i.e. $X-\theta$ is Exp with mean $1/\ln 2$).
Comment: What critical region do you get from Karlin-Rubin? (Although you don't need this theorem for testing simple versus composite hypotheses.)
Comment: Okay I see it now, so sum of this shifted exponentials will have Gamma(1/n, n) distribution or it also need to be shifted?
Comment: There is no need for such results. Do you recognize the form of the critical region? The distribution has monotone likelihood ratio in which statistic?
Comment: I am not sure if I follow, I know its exponential, and statistic I am using in Karlin-Rubin is sum of these random variables, therefore my critical region is $\{\sum X_{i} > c\}$, and sum of exponentials has Gamma distribution. Is it a way to do it differently?
Comment: You can ignore my comment on the shifted exponential distribution as long as you are finding $c$ for the critical region $\{X_{(1)}>c\}$.
Comment: @jbowman I know that, the point of this exercise is to express $n$ as a function of $\theta$
Comment: Ah, ok, thanks for clarifying.
Answer: The pdf of your distribution is $$f(x)=(\ln 2)2^{-(x-\theta)}1_{x>\theta}\quad,\,\theta\in\mathbb R$$
So pdf of the sample $X=(X_1,\ldots,X_n)$ is $$f_{\theta}(x_1,\ldots,x_n)=(2^\theta\ln 2)^n 2^{-\sum x_i}1_{x_{(1)}>\theta}\,,$$ where $x_{(1)}=\min\{x_1,x_2,\ldots,x_n\}$.
In general, any reasonable test involving the unknown quantity is based on a sufficient statistic. And here it is clear from the joint pdf that a sufficient statistic for $\theta$ is $X_{(1)}$.
If one wishes to use Karlin-Rubin theorem, one has to show that $f_{\theta}$ has the monotone likelihood ratio (MLR) property. And here you would actually find that $f_{\theta}$ has MLR in $X_{(1)}$. That would give you the critical region $\{X: X_{(1)}>c\}$ for testing $H_0:\theta=\theta_0$ against $H_1:\theta>\theta_0$ for any specified $\theta_0$.
To find $c$ subject to a level/size restriction, you need the probability $P_{\theta_0}(X_{(1)}>c)$. And this can be found directly from the CDF you have without referring to any sampling distribution.
Just notice that $P(X_{(1)}>c)=P(X_1>c,X_2>c,\ldots,X_n>c)=(P(X_1>c))^n$
As for power of the test at some $\theta=\theta_1(>0)$, it is given by $P_{\theta_1}(X_{(1)}>c)$. You can now establish a relationship between this function of $\theta_1$ and the sample size $n$.
Comment: So the power of this test will be $P_{H_1}(X_{(1)}>c)$? Does that mean that power is independent from $n$?
Comment: Okay, finally i got it, thank you.
Comment: As @jbowman mentioned in a comment, note that power is usually defined for a specific alternative. Power at $\theta=\theta_1(>0)$ is $P_{\theta_1}(X_{(1)}>c)$. You cannot find $P_{H_1}(X_{(1)}>c)$ exactly when $H_1$ is composite.

Power of uniformly most powerful test


Rexster to visualize Titan Graph using DynomoDB as storage backend

Question: I just started using Titan Graph DB. I want to use the AWS DynamoDB as the Storage Backend. I have set up Dynamo DB locally using the steps mentioned on  Installing and Running the DynamoDB Storage Backend for Titan
All the steps have been successfully completed.
I now want to visualize the graph (Marvel Universe Social Graph), using Rexster.
I have downloaded Rexster and set it up.
From what i have read, i understand that entries have to be made to  config/rexster.xml file to conect it to my graph DB . I cannot find what exactly needs to be put in to it, if DynamoDB is to be used as backend. Can someone tell me the exact steps i should follow when dynamoDB is used as storage backend?
Answer: If you're using Titan 1.0.0 as the document you referenced states, then you will not be able to use this with Rexster because Rexster is not compatible with the underlying TinkerPop 3.0.1 version that is used.
Rexster is compatible with TinkerPop 2.x, and TinkerPop 2.x is out of service.
Comment: Any free visualizing tool you can suggest of which works with Titan 1.0.0?
Comment: Since Titan 1.0 is based on Apache TinkerPop 3, you can try using [Gephi](https://gephi.org/). Be aware that there is a [TinkerPop bug](https://github.com/apache/incubator-tinkerpop/pull/308) that are being addressed for the latest Gephi 0.9 release. For the version of TinkerPop packaged with Titan, support is only for Gephi 0.8. Please refer to the TinkerPop docs for [Gephi streaming](http://tinkerpop.apache.org/docs/3.0.1-incubating/#gephi-plugin).