Resolve 16-Queens Problem in 1 second only

Question: I should resolve 16-Queens Problem in 1 second.
I used backtracking algorithm like below.
This code is enough to resolve N-Queens Problem in 1 second when the N is smaller than 13.
But it takes long time if N is bigger than 13.
How can I improve it?
#include <stdio.h>
#include <stdlib.h>

int n;
int arr[100]={0,};
int solution_count = 0;

int check(int i)
{
    int k=1, ret=1;
    while (k < i && ret == 1) {
        if (arr[i] == arr[k] ||
            abs(arr[i]-arr[k]) == abs(i-k))
            ret = 0;
        k++;
    }
    return ret;
}

void backtrack(int i)
{
    if(check(i)) {
        if(i == n) {
            solution_count++;
        } else {
            for(int j=1; j<=n; j++) {
                arr[i+1] = j;
                backtrack(i+1);
            }
        }
    }
}

int main()
{
    scanf("%d", &n);
    backtrack(0);
    printf("%d", solution_count);
}

Comment: @NathanTuggy I think this one is on the fence: on the surface, it asks for a performance enhancement, but on the other hand it requires a change that is deep enough to be a programming question.
Comment: @NathanTuggy Actually, OP's algo is fine. It's the data structure that needs some fine-tuning.
Comment: This appears to be off-topic because it's asking for general performance enhancements to working code. You might have better luck on [CodeReview.SE], but be sure to read their help center before you post it there.
Comment: @dasblinkenlight: Well, sure, but it's not clear *what sort of change is needed*: it's asking for guidance on generally picking an algorithmic improvement of some sort or other.
Answer: Your algorithm is almost fine. A small change will probably give you enough time improvement to produce a solution much faster. In addition, there is a data structure change that should let you reduce the time even further.
First, tweak the algorithm a little: rather than waiting for the check all the way till you place all N queens, check early: every time you are about to place a new queen, check if another queen is occupying the same column or the same diagonal before making the arr[i+1] = j; assignment. This will save you a lot of CPU cycles.
Now you need to speed up checking of the next queen. In order to do that you have to change your data structure so that you could do all your checks without any loops. Here is how to do it:

You have N rows
You have N columns
You have 2N-1 ascending diagonals
You have 2N-1 descending diagonals

Since no two queens can take the same spot in any of the four "dimensions" above, you need an array of boolean values for the last three things; the rows are guaranteed to be different, because the i parameter of backtrack, which represents the row, is guaranteed to be different.
With N up to 16, 2N-1 goes up to 31, so you can use uint32_t for your bit arrays. Now you can check if a column c is taken by applying bitwise and & to the columns bit mask and 1 << c. Same goes for the diagonal bit masks.
Note: Doing a 16 Queen problem in under a second would be rather tricky. A very highly optimized program does it in 23 seconds on an 800 MHz PC. A 3.2 GHz should give you a speed-up of about 4 times, but it would be about 8 seconds to get a solution.
Comment: [My implementation](http://ideone.com/HavRN2) of the same idea does 16Q  in less than 1s. But it uses 4 threads.
Comment: Here is [my implementation on ideone](http://ideone.com/wXR7hb), it does 14Q in about 4 seconds.
Comment: Thank you, dasblinknlight and Evgeny Kluev.
Bug Evgeny's code exceeded Time limit in ideone.com.
Did I miss something?
Comment: @dasblinkenlight, Thank you. It works for 14-Queens. But it takes several minutes for 16-Queens. Is there any idea to improve speed more?
Comment: @dasblinkenlight, I improved your code by using mirror. [code](http://ideone.com/9oJkhI). It takes half of time.
Is there any more improvement idea?
Comment: @Raymond Did you read Eugene's implementation (link from the second comment on this question). There's also a link in the last paragraph of the answer, it could be helpful too.
Answer: I would change while (k < i && ret == 1) { to while (k < i) {
and instead of ret = 0; do return 0;.
(this will save a check every iteration. It might be that your compiler does this anyway, or some other performance trick, but this might help a bit).


How to create several empty lists at once?

Question: I'd like to create 3 empty lists and assign them to different variables.
blue <- list()
green <- list()
red <- list()

Is there a possibility of a simultaneous assignment?
Comment: Do you really need them to be separate variables in your global environment? That's usually a red flag as far as best programming practives go. Normally it's much easier to work with similar data values inside a list itself. And if you are initializing with empty lists, that kind of implies you are going to be filling them up later and appending one item at a time to a list can be a slow operation in R. If a named list works, then `Map(function(...) list(), c("blue","green","red"))` would do the trick. You could use `list2env` is you really need to.
Comment: I don't know what these `vector.create` and `matrix.create` functions do. What packages are you using? It's better to initialize lists to their final size first and then fill them rather than assigning into non-existing indices. It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions.
Comment: You are right, I'm using a for-loop to 'fill' the lists and the operation is way too slow...

`for(i in 1:length(files){
    blue[[i]] <- matrix.create(files[i])
    red[[i]] <- vector.create(files[i])
    green[[i]] <- vector.create(files[i])
}`

would it work using `map`?
Comment: And yes, the operation is very slow. `length(files)` is 20000.
Comment: How do I know if I need them as separate variables in the global environment? –
Answer: Yes, it's possible.
red <- blue <- green <- list()

ls()
[1] "blue"  "green" "red"

Note, that the lists at first have the same memory address,
sapply(list(red, blue, green), data.table::address)
# [1] "0x55ee16ce46a0" "0x55ee16ce46a0" "0x55ee16ce46a0"

but it will change as soon the objects are manipulated (i.e. a copy is created).
red[[1]] <- 'foo'; blue[[1]] <- 'foo'; green[[1]] <- 'foo'

sapply(list(red, blue, green), data.table::address)
# [1] "0x55ee16f1ea48" "0x55ee16f1e930" "0x55ee16f1e818"

Comment: Oh, thats nice!
Comment: @qwr Yes, but this shouldn't matter, since addresses will change as soon you manipulate the objects. See edited answer.
Comment: will these reference the same list object or different objects? doing something like this in python will make all variables point to the same list.
Comment: I tried some simple loops and it seems that the variables point to different lists.
Comment: If for some reason we're not happy with this issue, we can still use the `replicate` solution from [edit history](https://stackoverflow.com/revisions/76409194/1).
Comment: Ok, I wasn't sure about R's copy on modify mechanic (I think it's covered in Advanced R by Hadley)


Is this a valid method and does it have a common name? (covariance analysis)

Question: We measured the same persons four times (T1a,T1b,T2a,T2b). Our theory is that the differences between T2a and T2b are caused by the influence of T1a on T2a and of T1b on T2b. Our hypothesis is that if we remove the influence of T1a/b on T2a/b, the difference between T2a/b will be zero. This is more or less like an analysis of covariance for repeated measures but I couldn't find anywhere what the GLM for this case looks like (or how it is done in R).
Hence, we calculated the regression of T2a~T1a and T2b~T1b. Then we calculated
T2a' = T2a - beta1*T1a   and   T2b' = T2b - beta1*T1b and then a paired t-test for comparing T2a' and T2b'.
Is our method legit and if so does it have a name?
Is it comparable to an analysis of covariance for repeated measures?
And if not, what do instead (and how to do it)?
Comment: I would do this as a multilevel model, I think.
Answer: I don't think your analysis is valid. The problem is that when you calculate T2a' and T2b' there is uncertainty in the beta1s and you pretend that those estimates  are fixed and correct. Hence your standard error of the difference will be two low, and your estimate too low.
You can use a multilevel model or a structural equation model.
For a structural equation model, set up your data as wide, so a person is a row.
For the multilevel model, set it up so each person has a row for their t2a score and a row for their t2b score.
Here's some code to load the libraries, and make up some data:
library(lavaan)
library(lme4)
set.seed(12345)
d  <- data.frame(id = 1:100,
                 t1a = rnorm(100),
                 t1b = rnorm(100),
                 t2a = rnorm(100),
                 t2b = rnorm(100))

Here's the structural equation model:
model1 <- "
  # regressions
  t2a ~ t1a + t1b
  t2b ~ t1a + t1b
  # intercepts
  t2a ~ a * 1
  t2b ~ b * 1

  # compare intercepts
  d := a - b"

fit1 <- sem(model1, d)
summary(fit1)

The important bit of output is the parameter d:
Defined Parameters:
                   Estimate  Std.Err  z-value  P(>|z|)
    d                -0.217    0.153   -1.421    0.155

Now I can reshape the data:
a <- setNames(d[c("t1a", "t1b", "t2a")],
              c("t1a", "t1b", "t2"))
b <- setNames(d[c("t1a", "t1b", "t2b")],
              c("t1a", "t1b", "t2"))

a$group <- "a"
b$group <- "b"

a$id <- 1:100
b$id <- 1:100

dLong <- rbind(a, b)

And fit a mixed model:
summary(lmer(t2 ~ t1a * group + t1b * group + (1|id), data = dLong))

The important parameter is groupb
Fixed effects:
            Estimate Std. Error t value
groupb       0.21719    0.13731   1.582

The two parameters are the same, and the SEs differ by a little (as the sample size increases, the difference drops).
Comment: I accepted your answer as it answered the main question. But yesterday, I also created a follow up question [Mixed linear models and adjusted means](http://stats.stackexchange.com/questions/255735) concerning the details. Maybe you would be so kind to give some ideas there as well?
Comment: Thank you for your answer, today I went back to work and tried to apply it. But I came across one question concerning both of your approaches. Why do you regress t2a/b with both t1a & t1b and not only with the corresponding one? Did I miss something?
Comment: If those effects don't matter, they should be zero, so won't have an effect. But if they are there, they should be in the model. (In the lavaan model they are easier to remove.)
Comment: Sure, I'll take a lok.


Order of execution of LINQ methods returning same results but different SQL in this code. What exactly is going on inside?

Question: So, here's my code:
Notice the positions of the ToList() method here, which is of IEnumerable, comparing it line by line.
Customers.ToList().Where(m=>m.ID > 3).OrderByDescending(m=>m.Name).FirstOrDefault();

Customers.Where(m=>m.ID > 3).ToList().OrderByDescending(m=>m.Name).FirstOrDefault();

Customers.Where(m=>m.ID > 3).OrderByDescending(m=>m.Name).ToList().FirstOrDefault();

Let's go through it line by line:
Customers.ToList().Where(m=>m.ID > 3)
.OrderByDescending(m=>m.Name).FirstOrDefault()

.ToList() - Enumerable
.Where() - Enumerable
.OrderByDescending() - Enumerable
.FirstOrDefault - Enumerable

Customers.Where(m=>m.ID > 3).ToList()
.OrderByDescending(m=>m.Name).FirstOrDefault()

.Where() - Queryable
.ToList() - Enumerable
.OrderByDescending() - Enumerable
.FirstOrDefault() - Enumerable

Customers.Where(m=>m.ID > 3).OrderByDescending(m=>m.Name)
.ToList().FirstOrDefault()

.Where() - Queryable
.OrderByDescending() - Queryable
.ToList() - Enumerable
.FirstOrDefault() - Enumerable

Now, here are their SQL, by order:

SELECT [t0].[ID], [t0].[Name] FROM [Customer] AS [t0] GO
SELECT [t0].[ID], [t0].[Name] FROM [Customer] AS [t0] WHERE [t0].[ID]
SELECT TOP (1) [t0].[ID], [t0].[Name] FROM [Customer] AS [t0] WHERE
  [t0].[ID] > @p0 ORDER BY [t0].[Name] DESC

It seems that line1 gets the ENTIRE collection and passes it through the wire, while line3 gets only ONE entity.
According to the SQL output, I can infer that:
    line1: Memory-intensive code; requires more bandwidth since more data is passed in the wire;
    line3: Database-intensive code; requires less bandwidth since less data is passed in the wire
I'm curious as to what goes on internally between each lines of codes. They are relatively similar, and I get the same exact results.
What exactly goes on in here (within the insides of C# and its features?)?
Answer: .ToList() method makes it Enumarable and generates SQL at that time. After that you are using LINQ to Objects.
So, for example, at first line you are getting whole table, because you are calling .ToList() on Customers.
It's not a good solution, because you are getting whole records into your memory, so call .ToList() at the end of your query always if there are no reasons to call it before.
Answer: Methods like .Where() and .OrderBy() use deferred execution, which means that all they do when called is modify the expression tree for the query - they do not cause the query to be executed. The underlying query is only executed when it is enumerated by something (e.g. by doing a foreach on it).
.ToList() on the other hand is intended to return an in-memory list of the query results, that is, it actually causes the query to be executed. It is conceptually similar to doing something like the following pseudocode
foreach (item in query)
   list.add(item)

In your examples, the query is executed by the .ToList() and from that point on you are doing a new query, this time against the in-memory collection.
So, in the 1st example the Customers query it is executed immediately by the ToList(), the .Where() and .OrderBy() just modify a new expression tree using the Linq to objects query provider and this Linq to objects query is executed by the FirstOrDefault().


Como realizar a soma de valores que multipliquei?

Question: Realizei uma operação que multiplica a quantidade de valores pelo valor unitário de cada um, obtendo o valor total por produto. Como poderia somar os valores totais de todos os produtos? tentei com um Sum dentro de um Sum...
EDIT1: Tentei usar RollUp mas acabo estourando o limite de 100mb
Comment: Você poderia postar seu código SQL para melhor lhe indicarmos o uso do `sum`. Dependendo dos campos do `select`, pode exibir um `group by`. E você precisa especificar se é SQL Server, MySQL, Oracle etc.
Answer: creio ser algo como :
<code>select cod_produto , sum(valor_unitario * quantidade) valor_total
from   vendas
group by cod_produto
</code>


PHP posting variables

Question: The problem that I am having is PHP won't allow me to send the variable "$IsEdit" to another page. Here is the HTML & PHP for the two pages:
<form action="Form2.php" enctype="multipart/form-data" method="POST">
    <?php
        $Test=Test;
    ?>
    <input type="submit" value="Run test" name="submit">
</form>

On the next page...
<?php
    echo $_POST["Test"];
?>

This gives me the notice:

Notice: Undefined index: IsEdit in C:\xampp\htdocs\Form2.php on line 2

Can someone please explain how to set things so that the second page displays the line "Test", please?
Comment: If you'd done ANY Kind of basic debugging, like checking the "view source" of that page, you'd (hopefully) NOT see that php code. You have no form field named `test`, and a PHP variable definition is utterly meaningless to the browser. PHP runs on the server, HTML is "executed" on the client. Just because you defined a php variable on the server doesn't mean that the browser will magically create an `` field for you when that html reaches the client.
Comment: and that `Test` in `$Test=Test;` is (treated as) a constant here.
Comment: There is nothing related to `IsEdit` in this code. `Test` should be in quotes since it is a string.
Comment: Take a look at the tutorial PHP has, http://php.net/manual/en/tutorial.forms.php. Note how the elements are passed `name="name"`, `$_POST['name']`. Your `Form2.php` must have `$_POST[' IsEdit']`, not `$_POST['Test']`. So make an element named `IsEdit` and give it a value.
Comment: The error does not support the question's code.
Answer: Hi try using the hidden type input element it will work in that way.
<form action="Form2.php" enctype="multipart/form-data" method="POST">

<input type="hidden" value="<?php echo "your value here"; ?>" name="Test" id="Test">

<input type="submit" value="Run test" name="submit">
</form>

Then you can get the value of Test in the next page using
<?php
 echo $_POST["Test"];
?>

Answer: Use a hidden input field
<?php $test=Test; ?>
<input type="hidden" name="test" value="<?php echo $test;?>"/>

This is really a hack not a fix. The problem lies with how you're handling this form.
Comment: Yours got DV's because in this statement `$test=Test` PHP will likely throw an error because 'Test' is not a string and PHP might try to interpret as a constant. In other words, your code is wrong.
Comment: Interesting. Could you expand on the problem of how I've mishandled the form, please?
Comment: Just not very good to splice in php like I suggested. I would recommend using PHP only for your backend service and building out your front end with JS and HTML only, using AJAX to fetch data. Blending PHP and HTML makes the code harder to maintain in the long run. I learned that the hard way at my last job.
Comment: While the OP might have posted that code it is *your job* as someone providing an answer to suggest there are problems with code like that and determine what is going on before speculating. ¯\\_(ツ)_/¯
Comment: My point was that often people don't include all of their code. It could have been a constant that was defined earlier in the code and so NOT an error.

PHP posting variables


Easiest free setup for c# development

Question: Am using windows xp sp3 on netbook and i need to compile c# programs for learning. I don't have fast computer or fast internet connection or fast money.
Can someone suggest the best way to get me going?
Thanks yous!
Answer: http://www.microsoft.com/express/Downloads/
The express editions are free from Microsoft. The default download manager will resume where it ended if the download break due to bad internet connection.
If you don't have internet goto your local library and it is likely they will have internet. Coffee shops and some food places (like ihop) also have good internet.
Comment: Nothing happens if you don't register.
Comment: The Microsoft will be very sad because they're giving away software for free and you're not even bothering to register.
Comment: Do I have to do something after 30 days?
Comment: You just need to register it, but it's free to do so :)
Comment: What happens if I don't register?
Comment: I'm ok with that. Just don't want them to take a picture of me thru webcam and send it to the FBI.
Answer: I believe the C# command-line compile (csc.exe) is included with the .NET Framework and recent versions of Windows (not sure of XP). So if you already have the .NET Framework installed, you should not need anything else.
Comment: That is true, but Visual Studio Express is also free and much more powerful.
Comment: Sure, but software that is already installed on your machine takes less time to download, especially if you pay your Internet access by minute or volume.
Comment: The lowest Vista has csc.exe by default?
Comment: it's part of .NET, and since vista includes .NET, yes.
Comment: Thank you Sekhat, I will check on another laptop which has Vista and see if it has csc.exe installed.
Comment: vista home does not have csc.exe :(
Answer: I also like SharpDevelop. I'm not saying that it's easier than Visual Studio, but i find it very convenient. Indeed, given the fact, that you don't have a fast internet connection it can be even more preferable.
Answer: If you want something more than "express" offers (which is good anyway), try MonoDevelop. It evolved from SharpDevelop, and among other things has nUnit and SVN support built in. Frequent releases and good support. Plus it'll work on a range of operating systems, or you can just host it in a VM if your choice of operating system somehow isn't supported (unlikely).
Comment: Do i still need .net installed?
Comment: @Yehonatan - it uses Mono, a parallel open source implementation of the CLI.
Answer: Visual C# 2008 Express Edition.

Easiest free setup for c# development


Create a rewrite rule in htaccess for root of domain

Question: I am trying to create a RewriteRule in htaccess for the domain root without effecting all the links and images. For example I want to rewrite the domain only if a file or directory is not supplied, if there is a file or directory specified after the domain name I want the rule to be ignored.
Basically I'm just trying to rewrite www.domain.com to be index.php?sectionID=1&page=1
RewriteRule ^(.*)$ index.php?sectionID=1&page=1

Answer: RewriteRule ^$ index.php?sectionID=1&page=1


Technical name of the slope on electric guitar body

Question: Most common electric guitars have a slope on the edge of the largest part of their body, where the forearm lays. Has this slope a specific name?
Answer: It's referred to as a contour, or forearm contour.
Comment: Yes although they're less common on acoustics. I would imagine it would be difficult to build a contour into an acoustic. An arch top has sort of a natural contour built in. Good luck!
Comment: Interesting, they use a solid block of wood with the contour built into it. Great find!
Comment: Thanks a lot, and: is it the same for acoustic guitars? I am searching for details on building techniques of the forearm contour in acoustic guitars.
Comment: I would like to see how's made _inside_ the left corner from which originates the contour in guitars as these: https://www.maestroguitars.com/wp-content/uploads/2018/04/Waist.jpg https://www.washburn.com/wp-content/uploads/2018/05/WCG15SCE12.jpg
Comment: Found it, finally. https://s958.photobucket.com/user/edwinsonguitar/media/MOL--Paul%20R%20Crossover%20Consort/IMG_0009_4-3.jpg.html?sort=2&o=17


duplicate taxonomy array being called

Question: I am working on a music site with a couple other programmers who have left.
We are using taxonomy terms or "tags" for each node, to determine the url/subdomain the node will be shown, on effectively creating different subdomains of content.
There is only one debug statement in the code, and even if there was another hiding somewhere, it does not explain why it shows two different arrays from the same taxonomy on the homepage.
I use the following code to reveal what terms are associated with the node:
 $terms = array();

 foreach($node->taxonomy as $term) {
   $terms[$term->name] = $term->name;
 }

 print 'debug:
' . check_plain(print_r($terms , 1)) . '
';

I get the following output:

    debug:
    Array
    (
        [national] => national
        [nyc] => nyc
    )
    debug:
    Array
    (
        [national] => national
        [nyc] => nyc
    )

Why is it showing 2 groups of arrays from the same taxonomy? The posts are only tagged once with these two tags "national" and "nyc."
Also on any nodes tagged with only "national," "washington" shows up as well in the duplicate array. I think it may be coming from another content type because when I performed a redirect on the node, using
unset($terms['national']);
      $value = array_shift($terms) ;
      if($region != $value) {
        $link = 'http://' . $value . '.thedelimagazine.com/' . drupal_get_path_alias("node/$node->nid", $path_language = '');
        drupal_goto($link, $query = NULL, $fragment = NULL, $http_response_code = 301);

it redirected to a different content type "CD of The Month." using term "washington" it should choose the other term in the first array; in the case above "nyc."  and go to the same node type in this case "blog,"  I performed this redirect using drupal_get_path_alias for other logic cases and it worked fine.

debug:
Array
(
    [national] => national
)
debug:
Array
(
    [national] => national
    [washington] => washington
)

The debug is called inside this function
function region_filter_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  /*global $user, $base_url;*/
  switch ($op) {

    case 'view':

      if( (arg(1) == 0)){ }

      else {

The site is http://www.thedelimagazine.com.
Answer: Is this in a hook function? It's possible your hook function is being called more times than you expect which gives you your extra debug statement.
Comment: yes it is in hook node api.  but why the two different arrays? i think it is coming from a different content type "CD of The Month." I added this info into my question
Comment: this is not the right answer but i doubt the question will be answered and i want the points on my account.

duplicate taxonomy array being called


Expected value and differentiation commute in a simple case

Question: In the text below (from Ross's book on probability), shouldn't it be
$$
\frac{d}{dt}\left(\sum e^{tX}p(x)\right)=\sum \frac{d}{dt}\left(e^{tX}\right)p(x)
$$
and similarly for the integral? i.e., shouldn't the probability mass/density function unaffected by the differentiation operator?
Comment: The text is just emphasising that the order of the linear operations can be interchanged and not distracting the reader by distributing the stuff on which they are operating.  $~\frac{\mathrm d ~}{\mathrm d t}\sum_x (\operatorname{stuff}) = \sum_x \frac{\mathrm d ~}{\mathrm d t} (\operatorname{stuff})$
Answer: You are correct, indeed
$$
\frac{d}{dt}\left[\sum_x e^{tX}p(x)\right]
= \sum_x \frac{d}{dt}\left[e^{tX}p(x)\right]
= \sum_x \frac{d}{dt}\left[e^{tX}\right]p(x)
$$
as you suggest since $p(x)$ is constant with respect to $t$. Ross does not need to simplify it for some reason.


Fibonorial of a fractional or complex argument

Question: Let $F(n)$ denote the $n^{\text{th}}$ Fibonacci number$^{[1]}$$\!^{[2]}$$\!^{[3]}$. The Fibonacci numbers have a natural generalization to an analytic function of a complex argument:
$$F(z)=\left(\phi^z - \cos(\pi z)\,\phi^{-z}\right)/\sqrt5,\quad\text{where}\,\phi=\left(1+\sqrt5\right)/2.\tag1$$
This definition is used, for example, in Mathematica.$^{[4]}$ It produces real values for $z\in\mathbb R$, and preserves the usual functional equation for Fibonacci numbers for all $z\in\mathbb C$: $$F(z)=F(z-1) + F(z-2).\tag2$$

The fibonorial$^{[5]}$$\!^{[6]}$$\!^{[7]}$ is usually denoted as $n!_F$, but here we prefer a different notation $\mathfrak F(n)$. It is defined for non-negative integer $n$ inductively as
$$\mathfrak F(0)=1,\quad \mathfrak F(n+1)=\mathfrak F(n)\times F(n+1).\tag3$$
In other words, the fibonorial $\mathfrak F(n)$ gives the product of the Fibonacci numbers from $F(1)$ to $F(n)$, inclusive. For example, $$\mathfrak F(5)=\prod_{m=1}^5F(m)=1\times1\times2\times3\times5=30.\tag4$$

Questions: Can the fibonorial be generalized in a natural way to an analytic function $\mathfrak F(z)$ of a complex (or, at least, positive real) variable, such that it preserves the functional equation $(3)$ for all arguments?
Is there an integral, series or continued fraction representation of $\mathfrak F(z)$, or a representation in a closed form using known special functions?
Is there an efficient algorithm to calculate values of $\mathfrak F(z)$ at non-integer arguments to an arbitrary precision?

So, we can see that the fibonorial is to the Fibonacci numbers as the factorial is to natural numbers, and the analytic function $\mathfrak F(z)$ that I'm looking for is to the fibonorial as the analytic function $\Gamma(z+1)$ is to the factorial.

Update: While thinking on this question it occurred to me that perhaps we can use the same trick that is used to define the $\Gamma$-function using a limit involving factorials of integers:
$$\large\mathfrak F(z)=\phi^{\frac{z\,(z+1)}2}\cdot\lim_{n\to\infty}\left[F(n)^z\cdot\prod_{k=1}^n\frac{F(k)}{F(z+k)}\right]\tag5$$
or, equivalently,
$$\large\mathfrak F(z)=\frac{\phi^{\frac{z\,(z+1)}2}}{F(z+1)}\cdot\prod_{k=1}^\infty\frac{F(k+1)^{z+1}}{F(k)^z\,F(z+k+1)}\tag{$5'$}$$
This would give
$$\mathfrak F(1/2)\approx0.982609825013264311223774805605749109465380972489969443...\tag6$$
that appears to have a closed form in terms of the q-Pochhammer symbol:
$$\mathfrak F(1/2)=\frac{\phi^{3/8}}{\sqrt[4]{5}}\,\left(-\phi^{-2};-\phi^{-2}\right)_\infty\tag7$$
and is related to the Fibonacci factorial constant.
Comment: The complexity of the expression for ${\frak F}(z)$ is somewhere in between that of [Euler's $\Gamma$ function](http://en.wikipedia.org/wiki/Gamma_function) and that of [Barnes' G function](http://en.wikipedia.org/wiki/Barnes_G-function).
Answer: (Main Result: I have a formula for what you want, its practical and it works!)
Since you ask multiple questions, I suppose what follows isn't a complete answer. I learned this trick the other day, so I'm more than happy to share it here,
If you want an integral that can generalize the recurrence,
$$(1) \quad \mathfrak F(0)=1,\quad \mathfrak F(n+1)=\mathfrak F(n)\times F(n+1).$$
You can do so by assuming the formula is of a certain form and that $k(t,n)$ satisfies a delay differential equation.
$$(2) \quad \mathfrak F(n)=\int_0^{\infty} e^{-t} \cdot k(t,n) \ dt$$
We can then demand that the eigenvalue for the differential operator is equal to $F(n+1)$.
$$(3) \quad \partial_t [k(t,n+1)]=F(n+1) \cdot k(t,n)$$
It then follows that applying integration by parts to $(2)$ yields,
$$\mathfrak F(n+1)=\int_0^{\infty} e^{-t} \cdot k(t,n+1) \ dt={F(n+1)} \cdot \int_0^{\infty} e^{-t} \cdot k(t,n) \ dt={F(n+1)} \cdot \mathfrak F(n)$$
$$\Rightarrow \mathfrak F(n+1)=\mathfrak F(n)\cdot F(n+1).$$
To obtain an explicit form for the integration kernel, we must solve $(3)$, which is classified as a delay differential equation. Whether or not an explicit solution exists is uncertain without further investigation. However, the kernel can certainly be found numerically.
However, we can certainly define the kernel that satisfies $(3)$ to be the Fibonacci kernel.
Tentative (Approximate) Solution
I didn't post this originally because its a bit cheap for a solution. Effectively, this solution indexes the new factorial differently. Set,
$$k(t,n)=t^{F(n)}$$
And also we have,
$$F(z)=(\phi^z-\cos(\pi \cdot z) \cdot \phi^{-z})/\sqrt{5}$$
Then we have,
$$\mathfrak F(n+1)=\mathfrak F(F^{-1}(F(n+1)-1)) \cdot F(n+1)$$
instead of,
$$\mathfrak F(n+1)=\mathfrak F(n) \cdot F(n+1)$$
Asymptotics and a Formula
I've switched notation since its the reason I came up with this. According to Wolfram Alpha, we have this relation for the asymptotics of the fibonorial,
$$(4) \quad n!_F \sim C \cdot \cfrac{\phi^{n \cdot (n+1)/2}}{5^{n/2}}$$
Given this, lets hope we can find a function $g(n,t)$ such that,
$$(5) \quad \lim_{n \rightarrow \infty} \cfrac{n!_F \cdot g(n,t)}{(n+t)!_F}=1$$
I find that, and I leave you to verify, that,
$$(6) \quad g(n,t)=5^{-t/2} \cdot \phi^{(t^2/2+t/2)} \cdot \phi^{n \cdot t}$$
Now that we know what $g(n,t)$ is, multiply by both sides by $t!_F$ and simplify, assuming $t$ is a positive integer. We get,
$$(7) \quad t!_F=\lim_{n \rightarrow \infty} \cfrac{n!_F \cdot g(n,t)}{F(1+t) \cdot F(2+t) \ ...\ F(n+t)}$$
Now we formally extend $t$ from $N \gt 0$ to $t \in C$. Using this, I can construct (perhaps the first?!) table of "F-Gamma" values using $n!_F=\mathfrak F(n+1)$,
$$
\begin{array}{c|lcr}
n & \mathfrak F(n) & \ln(\mathfrak F(n))\\
\hline
1 & 1 & 0\\
1.1 & 0.966975 & -0.033582\\
1.2 & 0.951630 & -0.049579\\
1.3 & 0.951521 & -0.049692\\
1.4 & 0.963404 & -0.037283\\
1.5 & 0.982610 & -0.017543\\
1.6 & 1.003127 & 0.003122\\
1.7 & 1.018567 & 0.018396\\
1.8 & 1.023911 & 0.023630\\
1.9 & 1.017193 & 0.017048\\
2.0 & 1 & 0\\
\end{array}
$$
Here's a graph (I didn't say it'd be pretty ;))

Check the recurrence, defined in $(1)$. It works!!!
Answer: Extending what Zach466920 said:
$$\partial_t[k(t,n)]=F(n+1)\cdot k(t,n+1)\tag1$$
We can develop a power series solution for this.
Let
$$k(t,n)=\sum_{m=0}^\infty \kappa(n, m)\ t^m$$
We equation $(1)$ as:
$$\sum_{m=1}^\infty m\ \kappa(n, m)\ t^{m-1}
=\sum_{m=0}^\infty(m+1)\ \kappa (n, m) \ t^m
=F(n+1)\cdot\sum_{m=0}^\infty \kappa(n+1, m)\ t^m$$
Which gives us the recurrence relation:
$$(m+1)\ \kappa(n, m)=F(n+1)\ \kappa (n+1,m)$$
I have no idea how to solve this recurrence equation or even if it is solvable. However if it is you should be able to get a series out of it. It then becomes a problem of solving that series until you can finally find a closed form for $k$.

With help from @Semiclassical we have the solution for $\kappa(n, m)$ as $$\kappa(n,m)=\left(\prod^n_{m=0}\frac{m+1}{F(n+1)}\right)\kappa(0, m)=\frac{(m+1)^{n+1}}{\mathfrak{F}(n+1)}\kappa(0, m)$$
The question is now finding $k(t, n)$ from this relation.

We have that $k(0, n) = 0$ or else there will be trouble with the convergence of $\mathfrak F$. This means that $$\mathfrak F(n) = \sum_{m=1}^\infty \kappa(n, m) \int_0^\infty e^{-t} t^m dt=\sum_{m=1}^\infty \kappa(n, m) \Gamma(m)$$ Consequently $$\sum_{m=1}^\infty \kappa(0, m) \Gamma(m)=1\tag 2$$ Which means that the seeding terms of $\kappa(n, m)$ seem to shrink faster than $\Gamma(m)$ grows as $m\to \infty$ and $n=0$.
Once a solution can be found for whatever $\kappa(0, m)$ is then a series for $k(t, n)$ can be established. I did some experimentation to see if $\kappa(0, m)$ could be guessed by letting $$\kappa(0, m)=\frac1{2^m\Gamma(m)}$$ as to satisfy condition $(2)$. This however lead to a value of $\mathfrak F(0)=\sqrt{3}$. This is clearly wrong.

If we let $\kappa(0, m)=\frac{a_m}{\Gamma(m)}$ we have $$\mathfrak F(n) = \sum_{m=1}^\infty \frac{(m+1)^{n+1}}{\mathfrak (n+1)}a_{m}\\
\implies \mathfrak F(n)^2F(n+1)=\sum_{m=1}^\infty (m+1)^{n+1} a_m$$ If we let $n=0$ we have $$1=\mathfrak F(0)=\sum_{m=1}^\infty a_m(m+1)=\sum_{m=1}^\infty m a_m + \underbrace{\sum_{m=1}^\infty a_m}_{=1\text{ by }(2)}$$
Therefore: $$\sum_{m=1}^\infty ma_m = 0$$
No idea what this means and I am unsure whether further manipulation will actually get anywhere. I feel quite lost carrying these last few out. I am open to ideas on how to determine $a_m$.
Comment: How can we be sure that there is a unique $a_m$ satisfying the last statement? I've found a possible candidate: $$a_m = \frac {2m \cos(\pi m - \pi) -2 \cos(\pi m - \pi)}{2m-1-\cos(\pi m - \pi)}$$ which unfortunately blows up when $m=1$. Although one could maybe say
$$\sum_{m\geq 1} ma_m = a_1 + \sum_{m\geq 2} ma_m = 0$$
which would mean that $a_1 = 1$. Have I gone wrong somewhere?
Answer: I think I've found a suitable [see EDIT below] way to generalize the fibonorial in the reals! (I've taken inspiration from an answer to this question.)
The first terms of the fibonorial sequence $\mathfrak{F}(n)$ are:
$$\mathfrak{F}_7(n)=\color{red}{1},1,2,6,30,240,3120,65620$$
where $\mathfrak{F}_7(n)$ is just $\mathfrak{F}(n)$ interrupted after the seventh term, for no particular reason. If we were to find the difference between consequent terms in this partial sequence we'd obtain
$$\Delta\mathfrak{F}_7(n)=\color{red}{0},1,4,24,210,2880,62500$$
and if we were to go on, we'd arrive at the point where we'd obtain a single number, in this case $$\Delta^7\mathfrak{F}_7(n)=\color{red}{47844}$$
and if we were to go even further, we'd find an infinite sequence of $0$s. (Indeed this process is akin to differentiation of a polynomial.)
As you can notice, I've highlighted the first terms of each sequence of differences in red. The sequence of these red terms I define to be $c(n)=\Delta^n\mathfrak{F}(0)$, and by inspection and induction one obtains that
$$c(n)=(-1)^n\sum_{k=0}^n(-1)^k\binom{n}{k}\mathfrak{F}(k)$$
Now the fibonorial sequence can be approximated as follows:
$$\begin{align}
T_q(n)&=\frac{c(0)}{0!}+\frac{c(1)}{1!}n+\frac{c(2)}{2!}n(n-1)+\cdots+\frac{c(q)}{q!}n(n-1)\cdots(n-q+1)\\
&=\sum_{j=0}^q \frac{c(j)}{j!}\frac{n!}{(n-j)!}
\end{align}$$
This can of course be generalized to real $x$ by using the $\Gamma$ function:
$$T_q(x)=\sum_{j=0}^q \frac{c(j)}{j!}\frac{\Gamma(x+1)}{\Gamma(x-j+1)}$$
which means that the limit of $T_q(x)$ as $q\to\infty$ should give us the Maclaurin series for a generalization of $\mathfrak{F}(n)$, which I shall call $\Phi(x)$:
$$\Phi(x)=\sum_{j=0}^\infty \frac{c(j)}{j!}\frac{\Gamma(x+1)}{\Gamma(x-j+1)}=\sum_{j=0}^\infty \frac{(-1)^j}{j!}\sum_{k=0}^j\binom{j}{k}\frac{\Gamma(x+1)(-1)^k}{\Gamma(x-j+1)}\mathfrak{F}(k)$$
EDIT: unfortunately, I have just realized that this generalization is an oscillating function which happens to be equal to $\mathfrak{F}(n)$ when $x$ is natural, but is awfully off otherwise. I won't delete the answer because I want to know what has gone wrong!


Change remove from cart button to an image button

Question: I want to change the remove-button, that removes line items from the cart to an image button representing a trash can like this:

The code I am using in a custom module looks like this:
<? php
function mymodule_custom_form_views_form_commerce_cart_form_default_alter(&$form, &$form_state, $form_id) {
  foreach ($form['edit_delete'] as &$item) {
    $item['#type']='image_button';
    $item['#src']='sites/all/themes/mytheme/images/trash.svg';
    $item['#alt']='Remove';
  }
}

That code shows the icon instead of the text as expected, but unfortunately it introduces a major issue: now pressing the button doesn't remove the correponding line item, but wrongly successively removes the last added line-items. So when I added item1, item2, item3 to the cart in this order, then no matter which corresponding remove-button you press, item3 is removed. Next time, you press one of the remove-buttons of the remaining 2 line-items, then item-2 is removed.
What's wrong with the above code?
Comment: Can't this be done with CSS?
Comment: Yes , that can be done and an user did it: https://www.drupal.org/project/commerce/issues/916348#comment-6643332 but I would like to realise it with the in drupal already implemented image button functionality.
Comment: Ah yeah, since CSS wouldn't solve the trigger problem. I see.
Answer: You need to unset the #value on your image_buttons:
  $item['#type']='image_button';
  $item['#src']='sites/all/themes/mytheme/images/trash.svg';
  $item['#alt']='Remove';
  unset($item['#value']); // this line here

The line item that is deleted is determined by the #triggering_element in your $form_data. This element is determined by a function _form_button_was_clicked($element, &$form_state) in form.inc in the core.
It seems that when you a #value has been set on your image_button, every image button is detected to have been clicked.
  // line 2227 in form.inc
  elseif (!empty($element['#has_garbage_value']) && isset($element['#value']) && $element['#value'] !== '') {
    return TRUE;
  }

That means at the end of the ride, the last image button is always set as the #triggering_element, and the last line item is always removed.
Unsetting the #value fixes that. Setting it to an empty string doesn't, somehow.
Answer: Instead of unsetting the #value property (which works, but I find it personally counter-intuitive), you could try setting it by using the form_type_image_button_value() function.
As an example:
function my_custom_module_form_views_form_commerce_cart_form_default_alter(&$form,
&$form_state, $form_id) {
  if (!empty($form['edit_delete'])) {
    foreach (element_children($form['edit_delete']) as $key) {
      $form['edit_delete'][$key]['#type'] = 'image_button';
      $form['edit_delete'][$key]['#src'] = 'sites/all/themes/trash.png';
      $form['edit_delete'][$key]['#alt'] = 'Remove';
      $form['edit_delete'][$key]['#value'] =
        form_type_image_button_value($form['edit_delete'][$key], NULL, $form_state);
    }
  }
}

The form_type_image_button_value() function is built to correctly extract the clicked image button's value from the $_POST array taking browsers' peculiarities into account.
Good luck!
P.S.: Rewrote the hook implementation mildly to use element_children() when iterating through the line item delete elements.
Comment: I implemented your above code and now the same wrong behavior in reversed order happens: on first button press, item-1 is removed, then item-2 ans so on …!
Comment: Let me check that again, thanks for the feedback.
Comment: Sorry, but sine I won't be online tomorrow, I'll have to give the bounty to the first answer because this one is working despite your one may be more elaborated once working.
Comment: Fair enough, that is AFAICT the most established approach for this issue (which is not Drupal specific). Cheers and good luck with your projects!


What is considered to be the natural (injective) homomorphism $\frac{IL+J}{IL} \rightarrow I \otimes \frac{R}{L}$?

Question: Let $R$ be a ring and $I,J,L \unlhd R$ such that $J \subseteq I$.

What is considered to be the natural homomorphism $\frac{IL+J}{IL} \rightarrow I \otimes \frac{R}{L}$ ?
Remark: It must be injective!

Will $x + IL \mapsto x \otimes L$ or $x+IL \mapsto 0 \otimes (x+L)$ work?
We also have $x+IL \mapsto x \otimes (x+L)$ but this isn't a homomorphism.
What can I take here? Thanks.
Answer: Recall for an $R$-module $M$ and $\mathfrak{a}$ ideal of $R$ the canonical isomorphism
$$M \otimes_R R/\mathfrak{a} \cong M/\mathfrak{a}M$$
In particular
$$I \otimes R/L \cong I/IL$$
since $IL+J \subset I$, you have the inclusion $$\frac{IL+J}{IL} \to \frac{I}{IL} \cong I \otimes \frac{R}{L}$$
Comment: The purpose of this question is to prove that $0 \rightarrow \frac{IL+J}{IL} \rightarrow I \otimes \frac{R}{L} \rightarrow \frac{I}{J} \otimes \frac{R}{L} \rightarrow 0$ (where we consider the natural homomorphisms) is exact. The $2nd$ arrow is clearly $p \otimes id$ where $p$ is the canonical epimorphism. I'm aware that taking isomorphisms we have the sequence $0 \rightarrow \frac{J}{IL \cap J} \rightarrow \frac{I}{IL} \rightarrow \frac{I/J}{L(I/J)}  \rightarrow 0$ which is exact (with the natural homomorphisms that I know), but it does not imply that the first is exact...
Comment: So, what we define to be the isomorphism $\frac{I}{IL} \rightarrow I \otimes \frac{R}{L}$? I know that the inverse is given by $x \otimes (r+L) \mapsto rx+IL$
Comment: It's $i+IL \mapsto i \otimes (1+L)$.


Representing Registers using Unions

Question: I am trying to set up the internal registers of a HCS12 processor using unions. Here is the way I currently have the unions:
union byte{
    struct{
        unsigned int B0: 1;
        unsigned int B1: 1;
        unsigned int B2: 1;
        unsigned int B3: 1;
        unsigned int B4: 1;
        unsigned int B5: 1;
        unsigned int B6: 1;
        unsigned int B7: 1;
    }idv;
    unsigned int All: 8;
};

union allPurpose{
    struct {
        union byte A;
        union byte B;
    } AB;
    unsigned int D: 16;
};

The issue is that when I initialize A to 170 and B to 187 using the int All. D should be 43,707 but is 170. I know that nested unions work but for some reason it is not working. If anyone can see something wrong and can help it would be appreciated.
Edit: Here is the code that is using the union in.
HCS12.accumulator.AB.A.All=0xAA;
HCS12.accumulator.AB.B.All=0xBB;
printf("\nReg A: %d",HCS12.accumulator.AB.A.All);
printf("\nReg B: %d",HCS12.accumulator.AB.B.All);
printf("\nReg D: %d",HCS12.accumulator.D);

The Union allPurpose is just in a another structure.
Comment: So this code is actually run on what platform?
Comment: No,I am setting A and B separately. D is not set but should be 0xAABB.
Comment: See my answer. Settle its correctness (or otherwise) by viewing the memory layout of a structure instance in your debugger.
Comment: It runs on a PC running Windows 7 And I am using GNU-GCC compiler. It is not meant to run on the HCS12.
Answer: You cannot assume that union byte A; and union byte B; are packed contiguously in memory.
(In fact, on modern architectures, is unlikely that they would be due to their being only one byte in size).
The specific packing arrangements are down to compiler and platform choice. A typical arrangement is 4 byte packing, meaning that your structure looks like this:
 struct {
     union byte A;
     /*Three bytes of packing*/
     union byte B;
 } AB;

Comment: Generally this is good advice. However, HCS12 is a somewhat modern architecture that doesn't give a damn about alignment. You can read 8 bit or 16 bit accesses anywhere in memory.
Comment: Now is there a way to set the packing arrangement to have it contiguous?
Comment: It's not standard C. You'll have to read your compiler documentation. For example, in MSVC2012 you can use a #pragma pack directive.
Comment: OK thank you for your help. I will try to find out if GNU-GCC compiler has a similar setting.
Answer:
First of all you should never use bit fields in embedded systems, for multiple reasons. Most likely your problems come from the bit order being poorly specified for your compiler (which is likely Codewarrior?).
I would strongly advise to use the following 100% portable syntax instead:
#define PEAR    (*(volatile uint8_t*)0x000Au)
#define NOACCE  0x80u
#define PIPOE   0x20u
#define NECLK   0x10u
#define LSTRE   0x08u
#define RDWE    0x04u

You shouldn't use the default primitive data types in C (such as unsigned int) when working with embedded systems. Use uint16_t etc from stdint.h instead.
It doesn't make any sense to make a union of one 8 bit member and one 16 bit member. This could be the cause of the problem.
In general avoid using structs/unions when mapping hardware registers, because the compiler may introduce padding anywhere inside the struct. Since the HCS12 is a good core which doesn't care about alignment, this won't be an issue in your specific case however.

EDIT
Your printf code looks fishy. printf() uses argument promotion to int. Look in the debugger memory map instead. What values does it say that your variables have?
Comment: Maybe it was the way I stated it I am not using the HCS12 for running the code. The unions are represent/simulate the HCS12 processor internal registers.
Comment: @Nathan So you are using a PC? In that case, I'm afraid you don't have a clue about what you are doing... HCS12 is a 16-bit big endian CPU. Your average PC is a 32/64 bit little endian CPU. Your code is 100% non-portable between HCS12 and a PC.
Comment: I am aware of that. This code is part of my program to simulate the HCS12 on a PC. Sorry that may have been my fault for the confusion.
Comment: @Nathan You need to take a step back from the code and read up on [endianess](http://en.wikipedia.org/wiki/Endianess), to begin with.

Representing Registers using Unions


What is the domain of this function

Question: The domain of $f(x)= (x-1)^{1/2}$ are all the real numbers. Now I can sub in x=0 into the expression, and I get the square root of -1 which is a complex number. So is this okay?
Comment: Assuming you are talking about the real numbers ($\Bbb R$) only for the domain, you can't then have a complex number including in that domain.
Comment: @frog1944  If $f(x) = (x - 1)^{1/2}$ is a real-valued function of a real variable, we need to restrict the values of $x$ so that we do not include a complex number in the *range*, which is why the domain of $f$ is $[1, \infty)$.
Comment: @N.F.Taussig I completely agree with you, but wasn't the question asking if it's okay to include a complex number in the *domain*. I was stating that we can't include a complex number in the domain.
Answer: The domain of $f(x)= (x-1)^{1/2}$ is all real $x\ge 1$. If you are talking about the domain of a function over the real numbers, you have restricted it to the values of $x$ for which the function is real.
You are correct in saying that $f(0)$ is not a real number. However, this means that $x=0$ is not apart of the domain, and thus it cannot be all real numbers.
Answer: Domain of a function is defined as the set of input arguments for which the function is defined.
The function is not defined for $x<1$ and so, the domain of the given function is $$x\geq 1$$
Comment: Consider using `\geq` vs `=>`.
Comment: @YoTengoUnLCD Thank you for editing
Answer: You state immediately that "The domain of $f(x)=(x−1)^{1/2}$ are all the real numbers". How did you arrive at that?   If we require that f(x) be a real number, then the domain is "all real number larger than or equal to 1".
Answer: Assuming you are finding the domain over the real numbers ($\Bbb R$), then $$\sqrt {x-1} \geq 0$$
As you can't have the square root of a number less than 0 in the real numbers. Solve the expression by squaring it out and then putting the $1$ on the right hand side and you find the domain is:
All real $x$, where $x \geq 1$

What is the domain of this function


Passing information to modal in for loop

Question: Im attempting to change the way that my table currently works. Right now the table is created by looping through all of the samples passed to it through the context in views.py of my Django app, and that works fine. The change i want to make however is to create a modal when the delete sample button is clicked show the user a warning message before they delete it. The problem im running into is that the {{ sample.id }} in the modal is identifying the first sample in the table (seems to not be part of the for loop). Any help would be much appreciated!

        Status	Mh to Mh	Shot & Sec	Date Created	Manage

    {% for sample in samples %}

            {{ sample.status }}
            {{ sample.mh_to_mh }}
            {{ sample.shot_and_sec }}
            {{ sample.date_created }}

                View Details
                Delete
                <button type="button" class="btn btn-danger btn-sm" data-toggle="modal" data-target="#myModal">Delete Modal</button>

                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Delete Sample

Are you sure that you want to delete this {{ sample.id }} sample?

                            <button type="button" class="btn btn-default" data-dismiss="modal">No</button>
                            Delete

    {% endfor %}

Comment: Not as good with my html as other languages, thanks for the idea! I naming each id like `Delete'
                    '` and it worked like a charm!
Answer: Multiple elements in HTML should not have the same ID. Although no error is thrown, the JS will always refer to the first element with the ID (in this case myModal)
It is better to move the modal out and pass the data needed when you open it. Have your HTML as such

        Status
        Mh to Mh
        Shot & Sec
        Date Created
        Manage

    {% for sample in samples %}

        {{ sample.status }}
        {{ sample.mh_to_mh }}
        {{ sample.shot_and_sec }}
        {{ sample.date_created }}

            View Details
            Delete
            <button type="button" class="btn btn-danger btn-sm" data-toggle="modal" data-target="#myModal"
                    data-id="{{ sample.id }}"
                    data-url="{% url 'contracts:delete_sample' sample.id %}">Delete Modal
            </button>

    {% endfor %}

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Delete Sample

Are you sure that you want to delete this  sample?

                <button type="button" class="btn btn-default" data-dismiss="modal">No</button>
                Delete

Then you need some JavaScript to set the correct values from data attributes
$('#myModal').on('shown.bs.modal', function(event) {
    $("#sampleId").text($(event.relatedTarget).data('id'));
    $("#actualDeleteBtn").attr('href', $(event.relatedTarget).data('url'));
})


Why is $\mathbb{Z}_2[X]$ a principal ideal domain?

Question: I used that $\mathbb{Z}_2[X]$ is a principal ideal domain to understand something but than I realized that in the lecture, we only noted that if we have a field, its polynomial ring is a domain. How do I see that it is a principal ideal domain?
Comment: If $k$ is a field $k[X]$ is an Euclidean domain (hence a fortiori a PID) since given two polynomials $f,g$ we can always find $q,r$ such that $f=gq+r$ and $\deg r<\deg g$ or $r=0$.
Comment: Ah, nice! (15 chars)
Comment: In fact, given any ring $A$ and polynomials $f=a_nx^n+\cdots$ and $g=b_kx^k+\cdots$ we can write $b_k^Nf =gq+r$ for appropriate $N,q,r$. If $b_k$ is invertible, we can always obtain a bonafide division. In particular, we can always divide by monic polynomials in any ring, which is nice.
Answer: 2 is a prime number so the ring $\mathbb{Z}_2$ is actually a field.


How can I enclose some XML elements in a bounding box?

Question: I want to enclose the pair of checkboxes and the radio buttons here:

...in a rectangle or "bounding box" so that it look something like this:

...but less ugly, of course. How can I do that with the following XML as a starting point:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="hhs.app.SettingsActivity">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="5dip"
        android:text="@string/select_your_printer"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <CheckBox
        android:id="@+id/ckbxNoPrinter"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/no_printer" />

    <CheckBox
        android:id="@+id/ckbxZebraQL220"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:checked="true"
        android:text="@string/zebra_ql220" />

    <Space
        android:layout_width="match_parent"
        android:layout_height="5dp" />

    . . .

    <RadioGroup
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <RadioButton
            android:id="@+id/radbtnBar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/using_labels_black" />

        <RadioButton
            android:id="@+id/radbtnPlain"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            android:text="@string/using_plain_labels" />
    </RadioGroup>

    <Space
        android:layout_width="match_parent"
        android:layout_height="2dp" />

    . . .
    </LinearLayout>

</LinearLayout>

?
UPDATE
I tried to apply Der Golem's suggestion, like so:
<LinearLayout
    android:orientation="vertical"
    android:layout_width="wrap_content">
    <shape
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle"
        android:layout_width="wrap_content">
        <stroke
            android:width="4dp"
            android:color="#f000"
            android:layout_width="wrap_content" />
        <TextView
            android:text="@string/after_fetching_palabra"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            />
    </shape>
</LinearLayout>

...but that does nothing (good); the TextView is just in there as a test, starting with one simple widget to begin with.
NOTE: This is a LinearLayout within a LinearLayout. When I remove this, it's fine, but with it, the Layout won't even render.
UPATE 2
So I take it that I put the shape in a \res\drawable folder. But in Droidio, it gives me four, count 'em, four, drawable folders, namely:
drawable-hdpi
drawable-mdpi
drawable-xhdpi
drawable-xxhdpi

Do I need to put the xml in each of those folders, or can I create a "generic/default" plain old "drawable" folder and put it there?
Comment: No, the size of the shape is in **dp**, which makes it "self-scaling". You only need the xml in your `/res/drawable` folder. - Using your words, `create a "generic/default" plain old "drawable" folder and put it there`
Comment: Glad it helped. By the way, Shape Drawables are nice beasts, worth a deeper study.
Comment: Added a tip on how to accomplish this here: http://www.codeproject.com/Tips/776325/How-to-Enclose-Multiple-Android-Widgets-in-a-Recta
Comment: So are Duckbilled Platypi (if you are willing to disremember, or at least assiduously avoid, their poison toe).
Comment: New related question here: http://stackoverflow.com/questions/23790506/which-element-do-i-need-to-modify-to-add-padding-between-a-drawable-and-its-encl
Comment: Nice article, indeed.
Answer: Use a vertical LinearLayout to enclose your CheckBoxes and another one to enclose your RadioButtons and assign them an xml drawable as the background (you could alternatively use a 9 patch, if you feel more comfortable with):
The two extra LinearLayouts are children of the outer container.
/res/drawable/box.xml (self contained xml drawable):
<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle"
    >
    <stroke
        android:width="4dp"
        android:color="#f000"
    />
</shape>

For reference: http://developer.android.com/guide/topics/resources/drawable-resource.html#Shape
[EDIT]
Apply the xml drawable as a normal background:
This is just one of the two layous: the "CheckBox" one:
...

<LinearLayout
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/box"
    >
     <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="5dip"
        android:text="@string/select_your_printer"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <CheckBox
        android:id="@+id/ckbxNoPrinter"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/no_printer" />

    <CheckBox
        android:id="@+id/ckbxZebraQL220"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:checked="true"
        android:text="@string/zebra_ql220" />
</LinearLayout>

...

[EDIT 2]
Now a little digression.
You asked for a simple square box and nothing else, so that's what I provided.
BUT. In the link I provided is shown in details how you can (for instance) not only make the corners round, but also give your shape a different background color or even a color gradient.
Just to name some interesting properties of the Shape Drawable.
Comment: Check out my edited answer: an xml drawable is like any other drawable. The two extra LinearLayouts are children of the outer container. The shape is itself a self contained drawable in its own xml file.
Comment: Thanks; now I've got an Update 2


Mandelbrot set; are these trajectories chaotic?

Question: I am using the complex Mandelbrot set, with an exponent of 2 so that the iterative equation is z = z^2 + c. The escape threshold is 4.0, and the maximum number of iterations is 5000.
I find that all trajectories that belong in the set are cyclical, with the exception of a few trajectories that do not repeat during the iterations. Some of these acyclical trajectories' starting locations are:
-1, -0.25
-1, 0.25
0.25, -0.5
0.25, 0.5
Are these trajectories chaotic? Is it the acyclical nature of the trajectory that makes it chaotic?

Where the exponent is 4, there are also acyclical trajectories:

Keep in mind that the exponent does not need to be an integer, and does not need to be positive either.
Comment: Is the pair of scissors the only set with this apparent pattern, or are there perhaps other similar patterns with a higher iteration count maximum?  If you lower the maximum, does the pattern change significantly?
Comment: If the exponent $a$ is not an integer, there is no continuous function that can reasonably be called $z^a$ for all complex numbers $z$. Any calculation will involve an artificial choice of branch cut.
Comment: In line 132 of that code, you have the term sqrtf(in.imag() * in.imag()) in the denominator, so it is undefined if in.imag() is 0. Thus the function does not work on the imaginary axis. When the exponent is not an integer, there will always be a set of points you have to exclude to get a continuous function; this is called a branch cut. There are many ways to choose a branch cut and it is arbitrary.
Comment: "imaginary axis" should be "real axis" in my comment above.
Comment: Dear abiessu, thank you for your time. I will try out your ideas. For now, I edited the question to show the acyclical trajectories where the exponent is 4. So, it's not just the standard Mandelbrot set that has acyclical trajectories.
Comment: Dear abiessu, where max iterations is 50000, there are a couple of acyclical trajectories. Where max iterations is only 500, there is a large number of acyclical trajectories. Was this what you were expecting?
Comment: Hi Ted, thanks again for your input. The pow function was given to me, for quaternions. I just dropped the last two components. As far as I can tell, the non-integer exponent works like a charm. I'm not certain what you are saying: what is a branch cut, and where does it come up in my code? https://github.com/sjhalayka/bezier_fractal_2d/blob/d017cd5db9bee462088d5eea11450277c791a3ed/main.h#L118 P.S. Thanks Ted. I kept your past suggestions in mind when asking this particular question.
Comment: Thanks again, Ted!
Answer: You have a few points of confusion that make this question (and your previous ones here and on StackOverflow) difficult to answer. Here is some clarification.

The Mandelbrot set lives in the context of complex dynamics, i.e. the study of the iteration of analytic functions mapping the complex plane to itself. A huge majority of MSE questions on the Mandelbrot set should tagged [complex-dynamics], rather than [fractals].

Given a complex analytic function, it makes no sense to refer to a single trajectory as chaotic. It might make sense to refer to the dynamics of the function itself as chaotic on some closed subset of the plane. Bob Devaney is generally credited with writing down the exact criteria that a function should satisfy to be considered chaotic a on a set.

The fundamental set associated with the chaotic dynamics of a complex analytic function is the Julia set. For a polynomial, the Julia set can be characterized as the closure of the set of repelling periodic points of that polynomial. To be clear, the Julia set of a function lives in the dynamical plane for that function - i.e. the plane where the iteration happens.

The Mandelbrot set specifically involves the iteration of functions chosen from the family
$$
f_c(z) = z^2 + c,
$$
where $c$ is a complex parameter. Specifically, the Mandelbrot set is defined to be the set of all complex numbers $c$ such that the Julia set of $f_c$ is connected or equivalently, such that the orbit of the critical point $z_0=0$ under iteration of $f_c$ remains bounded. In particular, the Mandelbrot set provides a general classification of the types of dynamics that arise for quadratic functions.
Note that the the Mandelbrot set lives in the parameter ($c$) plane - not in the dynamical ($z$) plane; in particular, trajectories don't live in the Mandelbrot set.

Here's a picture that might help clarify:

On the left, we see the Mandelbrot set with the single point $z_0=-0.9+0.15i$ highlighted in yellow. The corresponding Julia set appears on the right, together with an orbit that starts at the green dot and is ultimately attracted to a cycle of period two indicated by the two red dots.
If we change the point, we change the dynamical picture. For example, here's the picture for your point $c=0.25+0.5i$:

You can play with these sorts of images on this web page.

Judging from your pictures, I would guess that you are asking about the nature of the critical orbits (i.e. the orbits from the point $z_0=0$) of the functions $f_c$ for various choices of $c$, like $c=0.25+0.5i$. My second picture above shows how I would illustrate the orbit on the Julia set for that particular value of $c$. The dynamics of $f_c$ for each of the points you list happen to be parabolic, which is a bit tricky to deal with. There have been several discussions on this site involving parabolic dynamics.
Comment: @shawn_halayka In fact, *every* polynomial is chaotic on its Julia set - that's really the whole point of the Julia set. :) The function $f(z)=z^2$, for example, is chaotic on the unit circle. You can find an illustrative explanation of that fact on [this web page](https://marksmath.org/visualization/complex_square_iteration/).
Comment: The Mandelbrot set does *not* break the $f_c$s up into chaotic vs not chaotic. Rather, it provides a classification of the types of dynamics that are possible for quadratic functions. The different components of the Mandelbrot set correspond to values of $c$ where the critical orbit of $f_c$ is attracted to periodic orbits of various lengths. The main cardioid corresponds to attractive fixed points, the large circle just to the left corresponds to orbits of period 2, and the baby-brots all correspond to higher order periods.
Comment: I don't think it's common to use Lyapunov exponents in complex dynamics. While it could certainly be done, I think there's a lot of structure complex dynamics that precludes the need for Lyapunov exponents. The fact that every polynomial has a Julia set, for example, is not true for real dynamics.
Comment: I implemented the code to calculate the Lyapunov exponent and it returns a negative value for trajectories in the set, and a positive value for trajectories that are not in the set. I see now that tells us nothing more than the Z complex variable's magnitude would.
Comment: Mark, you're just plain awesome. Thank you so much for your explanation of things.
Comment: P.S. where then does chaos emerge with regard to the Mandelbrot set?
Comment: Someone told me that calculating the Lyapunov exponent will tell me if the system is chaotic or not. I have the trajectories, I just don't know where to start when calculating this Lyapunov exponent. Any help would be greatly appreciated.


Lavaan: How to free a constraint in one group out of two, while at the same time using effects-coding scaling method?

Question: I am examining differences in latent means between two groups using the following syntax:
<code>   smmlanguage<-'

   injury =~ NA*IN1+c(in1,in1)*IN1+c(in2,in2)*IN2+c(in3,in3)*IN3+c(in4,in4)*IN4
   illness =~ NA*IL1+c(il1,il1)*IL1+c(il2,il2)*IL2+c(il3,il3)*IL3+c(il4,il4)*IL4+c(il5,il5)*IL5

   ISIg =~ NA*injury + c(IN,IN)*injury + c(IN,IN)*illness

   IN4~~IL5
   IL1~~IL2

  IN1 ~ c(iin1,iin1) * 1
  IN2 ~ c(iin2,iin2) * 1
  IN3 ~ c(iin3,iin3) * 1
  IN4 ~ c(iin4,iin4) * 1
  injury ~ c(IIN,IIN) * 1

  IL1 ~ c(iil1,iil1) * 1
  IL2 ~ c(iil2,iil2) * 1
  IL3 ~ c(iil3,iil3) * 1
  IL4 ~ c(iil4,iil4) * 1
  IL5 ~ c(iil5,iil5) * 1
  illness ~ c(IIL,IIL) * 1

  in1 == 4 - in2 - in3 - in4
  iin1 == 0 - iin2 - iin3 - iin4

  il1 == 5 - il2 - il3 - il4 - il5
  iil1 == 0 - iil2 - iil3 - iil4 - iil5

  IIN == 0 - IIL

  ISIg ~~ c(DVp11,DVp12)*ISIg

  ISIg ~ c(DVk11,DVk12)*1

  d := (DVk12 - DVk11) / ((217*DVp12 + 220*DVp11)/(217*220)^0.5)
   '

  fit.smmlanguage<-cfa(smmlanguage,EnglishGreek, group='Dataset',  estimator="MLM",
               std.lv=FALSE)

  summary(fit.smmlanguage, fit=TRUE, standardized=TRUE)
</code>
According to a scalar invariance examination, I want to free the between group equality constraints of the intercepts of IN2 and IL4. However, I need to label them and apply the effect coding constraint at the same time (all works fine without effects-coding, but I want to use it). If I label them, I need to give the intercepts different labels for each group to release the between group constraints. However, if I do that, I cannot apply the effect.coding constraints, because I need to use the labels, and if I have different labels for each group, which one do I use? I tried using the (effect.coding = TRUE, group.equal = c(loadings,intercepts), group.partial = c("IN2 * 1", IL4 * 1) line on the 'cfa' command, but for some reason, it severely distorts the fit of the model, so I decided to do the full syntax myself.
Thanks!
Answer: You need to define the effects-coding constraint only with the anchor indicators (i.e., the ones that are equal / without DIF).
Conceptually, you could apply the effects-coding constraint separately per group, using each set of labels (like in the configural model).  However, when only one indicator (per factor) has different parameters in the partial-scalar model, then the effects-coding constraint actually implies equality anyway.  That is why the effects-coding constraint should only be applied to anchor indicators.
Comment: Got it! Thank you very much for your time as always!


Convex Set and an interior point

Question: Given a bounded convex set in $R^2$ with atleast 3 non-collinear points, can we find a point in $R^2$ such that any line passing through it cuts boundary atleast or exactly two points.
Can we prove it logically, I know that any point in triangle formed by 3 non-collinear points should work.
Comment: Any point inside the convex set works.
Answer: The answer is NO.
For example, the convex set $S= \mathbb R^2$ doesn't have this property.
A non-trivial counterexample is the region below the graph of your favourite concave down function. A vertical line will only meet the boundary once.
One another hand, if your question is
Question: Given a bounded convex set in R2 with at least 3 non-collinear points, can we find a point in R2 such that any line passing through it cuts boundary atleast or exactly two points.
The answer is yes. Note that any such set contains a triangle and hence a disk.
We will prove the following stronger statement.
Lemma If $A \subset \mathbb R^2$ is a bounded set which contains a disk, then any line through any point in this disk will meet the boundary at least twice.
Proof: Fix an arbitrary point $\alpha$ strictly inside. Draw an arbitrary ray from $\alpha$ in any direction. A small interval at the beginning is inside $A$, and towards infinity the ray gets outside $A$ (because $A$ is bounded).
A standard argument show that there is at least a boundary point in between [let me know if you need the details], and this point is not $\alpha$
Now, if we pick any line through $\alpha$, it is made of two such rays in opposite direction. Each of the rays contains a point, which is not $\alpha$, which is on the boundary, and those two points are distinct (since $\alpha$ is the only common point on the two rays).
Comment: @Sushil Then, the second part is the proof. If you meet these notions before, what the lemma says is that "Every bounded set with non-empty interior has the property you want". The condition you give imply non-empty interior.
Comment: If x is an interior point of a bounded convex set  $A$ then every line through x meets the boundary at exactly two points. Equivalently, every ray (half-line) through it meets the boundary at exactly one point. To prove this you have to take any unit vector u and consider the supremum of all $r>0$ such that $x+rx \in A$. Call this supremum $\rho$.Then show that $x+\rho u $ belongs to the boundary of A. For $r>\rho$ we can show that $x+ru$ is in the exterior of A and for $00$, because there is already a ball in interior.
Comment: and it also shows that there are exactly two points.
Answer: Let $S \subsetneq \mathbb{R}^2$ be a convex set with at least 3 non-collinear points $A,B,C \in S$. That means $\Delta ABC \subset S$, since $S$ is convex and hence contains the convex hull of any subset.
Let $M$ be the center of mass of $\Delta ABC$, then $M$ is an interior point of $\Delta ABC$. Hence, $\exists r > 0$ such that the open ball $\mathcal{B} = B(M,r) \subsetneq \Delta ABC \subset S$.
Note that since $M$ is an interior point of $\mathcal{B}, S$ and $\Delta ABC$, any line through $M$ is a diameter of $\mathcal{B}$, hence it will cut the boundary of $\mathcal{B}$ in exactly 2 places.
Can you finish this?
Comment: What if $S= \mathbb R^2$?
Comment: @N.S. i thought OP wants bounded sets, $\mathbb{R}^2$ is not bounded

Convex Set and an interior point


How to connect custom network namespace to root network namespace?

Question: I would like to connect the root network namespace to my custom network namespace in my Ubuntu box. Here is my network diagram:

Basically my custom network namespace is the one who control the vm network (such as assigning IP, etc).
I would like to see if I can set up a veth pair such that other Host which is the same subnet of eth1 (10.0.1.0/24) can access to it.
I was trying to do ip link set command but no luck with that as the interface (qg-1ee92648-d5) that I want to connect to is in the custom network namespace
Here is my Host network configuration:
vagrant@ubuntu:~$ ip link show
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN mode   DEFAULT group default
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP mode DEFAULT group default qlen 1000
link/ether 00:0c:29:cd:e0:99 brd ff:ff:ff:ff:ff:ff
3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP mode DEFAULT group default qlen 1000
link/ether 00:0c:29:cd:e0:a3 brd ff:ff:ff:ff:ff:ff

vagrant@ubuntu:~$ ip addr show
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 00:0c:29:cd:e0:99 brd ff:ff:ff:ff:ff:ff
    inet 192.168.106.129/24 brd 192.168.106.255 scope global eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::20c:29ff:fecd:e099/64 scope link
       valid_lft forever preferred_lft forever
3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 00:0c:29:cd:e0:a3 brd ff:ff:ff:ff:ff:ff
    inet 10.0.1.10/24 brd 10.0.1.255 scope global eth1
       valid_lft forever preferred_lft forever

My custom namespace configuration:
vagrant@ubuntu:~$ sudo ip netns exec  qrouter-7646dc10-7727-41b4-addd-8d08888cd764 ip
 link show
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN mode DEFAULT group default
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
2: qr-d174c5e5-c7: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP mode DEFAULT group default qlen 1000
    link/ether fa:16:3e:b3:cc:c2 brd ff:ff:ff:ff:ff:ff
3: qg-1ee92648-d5: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP mode DEFAULT group default qlen 1000
    link/ether fa:16:3e:f2:1d:2f brd ff:ff:ff:ff:ff:ff

vagrant@ubuntu:~$ sudo ip netns exec  qrouter-7646dc10-7727-41b4-addd-8d08888cd764 ip
 addr show
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: qr-d174c5e5-c7: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether fa:16:3e:b3:cc:c2 brd ff:ff:ff:ff:ff:ff
    inet 10.0.0.1/24 brd 10.0.0.255 scope global qr-d174c5e5-c7
       valid_lft forever preferred_lft forever
    inet6 fe80::f816:3eff:feb3:ccc2/64 scope link
       valid_lft forever preferred_lft forever
3: qg-1ee92648-d5: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether fa:16:3e:f2:1d:2f brd ff:ff:ff:ff:ff:ff
    inet 10.0.1.102/24 brd 10.0.1.255 scope global qg-1ee92648-d5
       valid_lft forever preferred_lft forever
    inet 10.0.1.101/32 brd 10.0.1.101 scope global qg-1ee92648-d5
       valid_lft forever preferred_lft forever
    inet6 fe80::f816:3eff:fef2:1d2f/64 scope link
       valid_lft forever preferred_lft forever

Answer:
Use Linux Bridge and inter-connect namespaces via veth pair.
Use OpenVSwitch and its internal ports

Refer to this step-by-step guide:
http://www.opencloudblog.com/?p=66
For example (quote from above post) if you want to connect two namespaces with one linux bridge and two veth pairs, in order to realize a topology in this graph:

# add the namespaces
ip netns add ns1
ip netns add ns2
# create the switch
BRIDGE=br-test
brctl addbr $BRIDGE
brctl stp   $BRIDGE off
ip link set dev $BRIDGE up
#
#### PORT 1
# create a port pair
ip link add tap1 type veth peer name br-tap1
# attach one side to linuxbridge
brctl addif br-test br-tap1
# attach the other side to namespace
ip link set tap1 netns ns1
# set the ports to up
ip netns exec ns1 ip link set dev tap1 up
ip link set dev br-tap1 up
#
#### PORT 2
# create a port pair
ip link add tap2 type veth peer name br-tap2
# attach one side to linuxbridge
brctl addif br-test br-tap2
# attach the other side to namespace
ip link set tap2 netns ns2
# set the ports to up
ip netns exec ns2 ip link set dev tap2 up
ip link set dev br-tap2 up
#

Please refer to original post for more details on OVS.
Cheers
Comment: Whilst this may theoretically answer the question, [it would be preferable](//meta.stackoverflow.com/q/8259) to include the essential parts of the answer here, and provide the link for reference.
Comment: @MarkHenderson my bad, edited, will take more care next time. cheers.
Comment: No worries, that's a much better answer now :)
Answer: Same as you, I struggled with veth, and failed to make it work.
Then I found this, which says:
Before MACVLAN, if you wanted to connect to physical network from a VM or namespace, you would have needed to create TAP/VETH devices and attach one side to a bridge and attach a physical interface to the bridge on the host at the same time, as shown below.

Now, with MACVLAN, you can bind a physical interface that is associated with a MACVLAN directly to namespaces, without the need for a bridge.

So I tried this:
$ sudo ip netns add ns0
$ sudo ip netns exec ns0 ip link set lo up
$ sudo ip link add macvlan0 link eth0 type macvlan mode bridge
$ sudo ip link set macvlan0 netns ns0
$ sudo ip netns exec ns0 ip link set macvlan0 up
$ sudo ip netns exec ns0 ip addr add 172.29.6.123/21 dev macvlan0
$ sudo ip netns exec ns0 ping 172.29.0.1
PING 172.29.0.1 (172.29.0.1) 56(84) bytes of data.
64 bytes from 172.29.0.1: icmp_seq=1 ttl=64 time=0.360 ms
64 bytes from 172.29.0.1: icmp_seq=2 ttl=64 time=0.412 ms

It is working!


Fitting Vine Copula tree by tree

Question: I am using the R programming language. I want to manually fit the D-vine copula for tree level 2 using BiCopHfunc(). Still, I got a different result (optimal parameter and copula families) when using RVineStructureSelect(), which gives an optimal parameter and copula families output. Could someone please provide the R code to fit the 3-dimensional vine copula in tree level 2, where V variables as the conditioning variables? My code is:
copQV<-BiCop(family = 14, par = 13.37)
h1<-BiCopHfunc2(pData[,1],pData[,2], copQV)

copVD<-BiCop(family = 1, par = 0.77)
h2<-BiCopHfunc1(pData[,2],pData[,3], copVD)

summary(BiCopSelect(h1, h2))

Comment: Thanks for your help. Very much appreciated.
Comment: When you use the `RvineStructureSelect,` the function builds the entire R-vine copula model for you. However, you only try to fit specific copula families to the second tree. Hence, of course, you will get a different result. If you want to specify a D-vine copula model with your choice of the bivariate copula families and their parameters, then you should not use the `RvineStructureSelect` function. Instead, you should build your model step by step using the `VineCopula` package.
Comment: Anytime. I am happy to help.  :)
Comment: @Dr.Alenezi, please make that as an answer.
Comment: @User1865345-solidarityMods Ok.
Answer: To specify the specific type of the copula family in the R-vine copula model,

You need to specify the variable structure.
Then, you need to build vine matrices for each of the following:

Variable structure
Copula family
parameter for each copula family.

Then, you need to use the RVineSeqEst() which will estimate the model parameters sequentially starting from the first tree.
You can fit RvineStructureSelect function to select for you the vine copula model. Then, you can extract the matrices for the structure, family and parameters. For example:
myfunc <- RVineStructureSelect(your-data)
myfunc$Matrix
myfunc$family
myfunc$par

Then, you can modify the copula families as you like and then, re-run your model again using your need families and their parameters.

Fitting Vine Copula tree by tree


Is there a name for music where only the bass instruments are used

Question: I just love the bass, there are youtube channels with bass players that just do bass solo. Is there a name for this.
I can't find anything on spotify that resembles for example this:
Answer: There isn't a specific name for music that has only bass (maybe "solo bass music"?). Off the top of my head the only record that comes to mind that is solo bass is a classical record, Edgar Meyer playing the Bach cello suites. I'm sure there are some others. Your best bet is to search for albums where the bassist is the leader/featured artist. There may or may not be solo pieces on them but the bass will probably be featured prominently on a few tunes. Also you must check out "Big Bottom" by Spinal Tap, just basses, drums and vocals, bass heaven!
Comment: In a more serious vein, ex-Minutemen bassist Mike Watt and ex-Black Flag bassist Kira Roessler has a bass duet project called dos.
Comment: @Tetsujin I went to see a buddy of mine playing guitar with Paul Schaffer here in Vegas in 2019 and they played "Big Bottom" with about 5 bass players on stage! Will Lee was in town and played with them, it was a gas!


Is it possible to access the names of all build path jar files on which java project depends

Question: The build path includes user libraries, tomcat libraries. Is it possible to return these jar names into a string list ?
Comment: Return where? Ant, Maven, ...?
Comment: Do you want to list in your application all the jars that have been loaded? I suppose it is a web app on Tomcat...
Comment: @Alin Stoian Its a web app running on websphere
Comment: @Tichodroma return this jar names into a string list, ive updated the question
Answer: I think this would do the trick....
Source: http://dev-answers.blogspot.com/2006/06/how-do-you-print-java-classpath.html
<code>  public String getClasspathString() {
     StringBuffer classpath = new StringBuffer();
     ClassLoader applicationClassLoader = this.getClass().getClassLoader();
     if (applicationClassLoader == null) {
         applicationClassLoader = ClassLoader.getSystemClassLoader();
     }
     URL[] urls = ((URLClassLoader)applicationClassLoader).getURLs();
      for(int i=0; i < urls.length; i++) {
          classpath.append(urls[i].getFile()).append("\r\n");
      }

      return classpath.toString();
  }
</code>
Comment: I am afraid not... :(   I suppose when you say a different project you mean a different java process, in which case, you won't be able to get a hold of the class loader for that other process, so you won't be able to run this... But if this is for different projects deployed in a web server, you have to keep in mind that all of them share the same class loader, and so they share the same class path...
Comment: Thanks, this solution looks robust enough to return all of the jars that a project depends on ? regardless if they are server jars, external jars, application jars ?
Comment: yes, this should return all the jar files regardless where they are coming from
Comment: I think this is a good solution, only slight issue I see is that the code must be run in same project as where project resides. Is it possible to run this from a separate project so as to inspect multiple projects ? I will accept this as answer regardless but is this amendment possible ?
Answer: You can also read this article:
http://tomcat.apache.org/tomcat-6.0-doc/class-loader-howto.html
If you are interested also in the server jars, not only the application ones, you will have to list some additional directories:
common.loader : ${catalina.base}/lib,${catalina.base}/lib/*.jar, ${catalina.home}/lib,${catalina.home}/lib/*.jar
<code>System.out.println(System.getProperties().getProperty("catalina.base", null));
System.out.println(System.getProperties().getProperty("catalina.home", null));
</code>


Tema que é usado na landing do Atom IDE

Question: Como o pessoal do suporte do Atom demora muito a responder, gostaria de saber se a comunidade @Stackoverflow sabe o tema que é usado na landing page do Atom IDE?
https://ide.atom.io/
Answer: Existe um thema criado com as mesmas definições de cores da demonstração do site da Atom, ele foi criado por um desenvolvedor que tambem gostou das definições de cores porem nao consegui encontrar porque o autor principal não trabalhava mais na Atom.
O nome deste thema é "atom-ide-dark-syntax" ele está disponível no link: https://atom.io/themes/atom-ide-dark-syntax, para instalar clique no botão Install dentro da pagina do link anterior.
Depois de instalado o Thema, na IDE Atom vá em Settings depois clique em Themes. Na caixa de seleção "UI Theme" escolha "Atom Dark" e em "Sintax Theme" escolha "Atom Ide Dark".
Answer: Verifiquei diretamente no Forum da aplicação, e infelizmente o dono do tema não trabalha mais na empresa. A empresa aguarda anciosamente pelo retorno, e logo depois disso, por projetos como este tema, em ação.

Tema que é usado na landing do Atom IDE


Who first suggested weak stationarity and strict stationarity?

Question: I wonder who first suggested and defined weak stationarity, and which paper it is. It seems that many paper using it as given, but I'm just curious of how it is defined and proved, and the discussions over the definition.
Answer: It was developed by Khintchine in Korrelationstheorie der stationare stochastischen Processe, Math. Ann. 109, 604-615.
As $\rm [I]$ notes:

The second line of development began with a series of papers in 1932-1934  by the Russian mathematician Khintchine who introduced both stationary and weakly stationary stochastic processes and developed the correlation theory for weakly stationary processes [see Khintchine (1934)]. This development was important not only for time series analysis but was also one of the pioneering works in the modern theory of stochastic processes. Later,  Kolmogorov (1941a) developed the geometric theory of weakly stationary time series and Cramér (1942) discovered the important spectral decomposition of weakly stationary processes…

Reference:
$\rm [I]$ The Spectral Analysis of Time Series, Lambert H. Koopmans, Academic Press, $1995, $ sec. $2.1, $ p. $29.$
Comment: It seems unlikely that this is the original, because it gives short shrift to [George Udny Yule,](https://en.wikipedia.org/wiki/Udny_Yule) who studied these processes a generation or two before 1932.
Comment: Thanks @whuber for pointing this out. I would then look for the specific paper/reference of Yule which contains the development of the relevant concepts.


log4j.xml path problem

Question: I am trying to get log4j working using xml configuration. I have log4j.xml added to classpath but while running I am getting :
log4j:WARN No appenders could be found for logger (test.DateFormatter).
log4j:WARN Please initialize the log4j system properly.
If I place a log4j.properties instead it seems to pick up the configuration.
Any ideas
Answer: It's good to have a log4j.xml in the classpath but it also has to provide the correct configuration. So maybe you post the content of your log4j.xml file so we can help you (maybe typo in logger configuration?).
You should also have a look at the log4j manual. The section "Default Initialization Procedure" describes how log4j will try to find the initialization file.

log4j.xml path problem


Is there any open source tools available for chimeric sequence detection?

Question: Is there any tools for detecting and removing chimeric sequences from 16s,WGS,WTS sequences other than USearch. The alternative should be open source so that it can be used for commercial purposes.
Answer: There is http://qiime.org/tutorials/chimera_checking.html
As I understand from your question this would sufice.
Answer: VSEARCH is another open source answer to USEARCH.


Credit Given - Geometricly Modeling Infinity with 3 planes and 9 circles - Ratio of Circles

Question: Refer to the attached diagram sketch to help visualize the equation.
I am requesting help with an interesting math problem. Basically, I am diagraming infinity using three planes. These planes connect with each other at either side at 120 degree angles.
These connection lines never really connect at the center, as they go on into infinity, but appear to (think repeating 9). Three perfect circles are placed on each of the planes. When viewed 2 dimensionally, the circles appear to be ellipses.
The Problem: What is the width/height ratio of these illusional ellipses? For computational purposes, put the three perfect circles on each plane touching each other. The actual width of the minor axis  for the smallest illusional ellipse can be set to 1 for computational purposes (or really any number you fee like).
The Diagram: I have used the 1:3 ratio to make the circles in this diagram (120 by 360, 360 by 1080, and 1080 by 3240). I suspect that this ratio is not correct; however, the answer should be fairly close to this ratio. I am not entirely sure if the ratio will be different for each of the circles, but it could be.
Thank you in advance for your time working on this problem. If you have seen it before, great! If not, hopefully you will enjoy the challenge. Solving this problem in needed to complete a logo for a non-profit organization. Credit will be given to whoever solves this.
Comment: Ok, so maybe I'm off base here, but this is what comes to mind. First off, I see you're splitting things up as if they were on a plane. The way my mind conceptualized the problem was that the three planes are actually X,Y,Z in 3D space. So if that's the case, we can treat each "side" as it's own plane and do the calculations before the projection from 3D to 2D. That projection is going to depend on how much foreshortening you want. For that, I recommend looking at [Graphical Projections](http://en.wikipedia.org/wiki/Graphical_projection). Does this jive with what you're asking?
Answer: As @JTrana suggests in a comment, the answer depends on how much foreshortening you want to do. If you look down on a tripod, you'll see the legs make $120^\circ$ angles, no matter how "open" the tripod is, so that part is unchanging; circles fitted between the legs of the tripod, however, will appear as ellipses of varying eccentricities for different degrees of tripod open-ness.
Since there's no inherent foreshortening to go along with the apparent $120^\circ$ separation of the legs, then, you may use any ellipse you like in your logo, secure in the knowledge that it corresponds to some amount of foreshortening. This gives you the artistic freedom to use ellipses you find aesthetically pleasing (aspect ratio = golden ratio, perhaps?).
If, however, you really-really want the image to represent the shadow of a particular 3D configuration, then we can do that, too. I'll walk you through it.

Let $OABC$ be a translucent triangular pyramid (ie, a tetrahedron) with equilateral base $\triangle ABC$ and identical isosceles lateral faces such as $\triangle OBC$. (The lateral edges of the pyramid are like the legs of the tripod.) A circle painted on $\triangle OBC$ will cast an elliptical shadow onto the base; one dimension of this ellipse (the one parallel to $\overline{BC}$ will match the diameter of the circle; the perpendicular dimension will undergo the same deformation as the shadow cast by face $\triangle OBC$ itself.
Now, the shadow of $\triangle OBC$ is $\triangle PBC$, where $P$, the shadow of $O$, is the center of $\triangle ABC$. Observe that here, too, that one dimension of the shadow (namely $\overline{BC}$) matches that of the face, while the perpendicular dimension has been deformed. Writing $M$ for the midpoint of $\overline{BC}$, we can express the deformation factor as
$$k = \frac{|\overline{PM}|}{|\overline{OM}|}$$
so that the shadow ellipses have aspect ratios $1:k$.
Since $\triangle ABC$ is equilateral, we have that $|\overline{PM}| = \frac{1}{3}|\overline{AM}|$; moreover, $|\overline{AM}| = \frac{\sqrt{3}}{2}|\overline{BC}|$. Thus, we can write
$$k = \frac{1}{2\sqrt{3}}\;\;\frac{|\overline{BC}|}{|\overline{OM}|} = \frac{\sqrt{3}}{6}\;\frac{\text{base of } \triangle OBC}{\text{altitude of } \triangle OBC}$$
If you like, we can express $k$ in terms of other aspects of the tetrahedron.

If the edges of base $\triangle ABC$ have length $b$, while the lateral edges have length $\ell$, then applying the Pythagorean Theorem to $\triangle OMB$ yields $$|\overline{OM}|^2 + \left(\frac{1}{2} b\right)^2 = \ell^2 \qquad \text{so that} \qquad k = \frac{b\;\sqrt{3}}{3\sqrt{4\ell^2 - b^2}}$$
If the lateral edges make an angle of $\theta$ with each other, then $|\overline{OM}| = \ell \cos(\theta/2)$ and $|\overline{BC}| = 2 \ell \sin(\theta/2)$, so that $$k = \frac{\sqrt{3}}{3}\;\frac{\sin(\theta/2)}{\cos(\theta/2)} = \frac{\sqrt{3}}{3}\;\tan\frac{\theta}{2}$$
If the pyramid is in fact a regular tetrahedron ---with all edges equal and making $60^\circ$ angles with each other--- then either of the above reduces to $$k = \frac{1}{3}$$
If the pyramid is a right-corner tetrahedron ---with lateral edges at right angles to each other--- then we have $$k = \frac{\sqrt{3}}{3}$$

... and so forth.
Comment: THANK YOU!! I was so happy when I saw this reply, your time is much appreciated!!!!!!


MySql Query to add column with random Yes or No

Question: I know this seems like a super easy question but for the life of me I cannot figure it out and when I google it, the only answers that I get just deal with getting a random number. I'm learning MySql/Workbench. I am trying to write a query for one of my tables to add a column (easy enough). But my goal is to population each row with a Random Boolean (yes or no). As I previously said, everywhere I look, it only deals with getting a random number but I just need the rows to have a Random yes or no. Thank you for any suggestions or help
Answer: If you want a random 0 or 1 (for No and Yes respectively) then all you need is to compare the result of the function RAND() with 0.5:
select *,
  rand() < 0.5 as randomcol
from tablename

If you want to get No or Yes then use a CASE expression:
select *,
  case when rand() < 0.5 then 'Yes' else 'No' end as randomcol
from tablename

Answer: Populating rows of a table with random values can be accomplished by 'getting a random number' and then using % 2 on the results to clamp it either 0 or 1.  Then just insert it into the desired tables / columns.
For example:
INSERT INTO "your_table" ("col1","col2","random")
VALUES ("val1", "val2",(RAND()*1000)%2)

This would add rows with constant values for col1 and col2 into your_table, but the random column will get populated with a random number between 0-999, which we then get the modulus of 2 to clamp the final result to either 0 or 1.
Also, if you want to make the values generated random but consistent, you can pass in a seed to make the sequence of generated values repeatable (ie RAND(10) will always produce the same result, so you can use an incrementing seed to produce psudo-random results that you can consistently repeat).


Multiple Ec2 instances on Amazon free aws account

Question: I created amazon micro instance with IP email@example.com .
While using amazon free service, if I create 2nd micro instance then will it be chargable? or only one micro instance is available on for free services. ?
Answer: You get 750 hours a month of micro instances on a free account. Since there are between 672 and 745 hours in a month, that means you can run one instance 24x7. You can run more instances for less time, if you want, but be sure not to go over 750 instance-hours in a month, or you will be charged. You can confirm this and check other free tier allowances here.
Comment: thanks, means I use 5 instance each around 50 hours per month, then no charge right? Can you please tell me how this hours usage get counted?
Comment: You're charged an hour for each hour that the instance is running at all, even if only for a few seconds. So if you start an instance at 08:59:30 and stop it again a minute later at 09:00:30, you'll be charged for two hours -- 08:00-09:00 and 09:00-10:00 -- since it was running in both of those hours.
Comment: generally once someone create intance, it keep working. Like someone hosted site then it has to be working all time. so 24*30=  720 would be considered any way that website is being used or not, right? if I have two instance running then 720* 2 = 1440 hours per month. is that correct?
Comment: any suggestion for previous comment
Comment: Yes, that's correct. If you keep your instances running all the time then they use between 672 and 745 hours per month. It doesn't matter if they're at 0% CPU usage or 100% CPU usage, just whether they're in the "Running" state or not.