$L^2$ norm and $L^{\infty}$ inequality for periodic smooth functions

Question: Let $\varphi \in C^{\infty}(\mathbb{T}^n,\mathbb{C})$ (i.e. just smooth periodic complex-valued function) and $f \in C^{\infty}(\mathbb{T}^n,\mathbb{C}^m)$. Then I was wondering if the following is true:
$$
\|\varphi f\|_{2} \leq \|\varphi\|_{\infty}\|f\|_{2}
$$.
Where the $\|\cdot \|_{2}$ is $L^2-$norm and $\|\cdot\|_{\infty}$ is the sup-norm which are defined in this case to be
$$
\|f\|_{2} := \frac{1}{(2\pi)^{\frac{n}{2}}} \Bigg(\int_{\mathbb{T}^n} f \cdot f \Bigg)^{1/2} \quad \text{where $'\cdot'$ represents the Hermitian product.}
$$
and
$$
\|f\|_{\infty} = \sup_{\mathbb{T}^n}\{|f|\}
$$
also we denote $|f| = (f \cdot f)^{1/2}$.
I managed to prove the following
$$
\|f\|_2 \leq \|f\|_{\infty}
$$
as follows
$$
|f| \leq \sup_{\mathbb{T}^n} |f|
$$
$$
\implies |f| \leq \|f\|_{\infty} \implies |f|^2 \leq \|f\|_{\infty}^2
$$
hence
$$
\int_{\mathbb{T}^n} |f|^2 d\mu \leq \int_{\mathbb{T}^n} \|f\|_{\infty}^2 d\mu = \|f\|_{\infty}^2 \int_{\mathbb{T}^n} 1 d\mu = \|f\|_{\infty}^2  \mu(\mathbb{T}^n)
$$
and taking square roots on both sides,
$$
\Bigg(\int_{\mathbb{T}^n} |f|^2 d\mu \Bigg)^{1/2} \leq  \|f\|_{\infty}  \mu(\mathbb{T}^n)^{1/2}
$$
which gives
$$
\Bigg(\int_{\mathbb{T}^n} f \cdot f \quad d\mu \Bigg)^{1/2} \leq  \|f\|_{\infty}  \mu(\mathbb{T}^n)^{1/2}
$$
multiplying $\frac{1}{(2\pi)^{n/2}}$ both sides, we obtain
$$
\frac{1}{(2\pi)^{n/2}}\Bigg(\int_{\mathbb{T}^n} f \cdot f \quad d\mu \Bigg)^{1/2} \leq  \frac{1}{(2\pi)^{n/2}}\|f\|_{\infty}  \mu(\mathbb{T}^n)^{1/2}
$$
and hence by using the fact that $\mu(\mathbb{T}^n) = (2\pi)^n$, we have
$$
\|f\|_{2} \leq \|f\|_{\infty}
$$
But this seems not so useful.
I was proceeding by showing
$$
\|\varphi f\|_2 \leq \|\varphi\|_{2}\|f\|_2
$$
which I think is False even with the given conditions and hence the above work seems useless.
Summary : I need to prove
$$
\|\varphi f\|_{2} \leq \|\varphi\|_{\infty}\|f\|_{2}
$$.
Answer: Remember that integrals are monotonic, so if $f\leq g$ a.e. then $\int f\leq \int g$. Thus if $g\geq 0$ a.e. and $f_1\leq f_2$ a.e. you get $f_1g\leq f_2g$ a.e. and thus $\int f_1g\leq \int f_2 g$.
So now see that $|\phi|\leq \|\phi\|_\infty$ a.e. and $(\phi f)\cdot(\phi f) = |\phi|^2 |f|^2$ and $|f|^2\geq 0$.
So using this we get
$$ \|\phi f\|_2 \leq  \Big\|\|\phi\|_\infty f\Big\|_2$$
and as $\|\phi\|_\infty$ is a scalar this is
$$ \|\phi\|_\infty \|f\|_2$$


BI Publisher .rtf Spacing if there is null value

Question: I am facing an issue on BI Publisher, I have some texts shown in a list.When they have value everything is fine , but when any of them is null then the space is held and shown empty line.Is it possible to wrap the empty line ?
You can notice my code above.
https://i.stack.imgur.com/F47Kh.jpg "PDF"
https://i.stack.imgur.com/bM0yn.jpg "RTF"
<code>Observações:
COMMENTS
<?if@inlines: FORM = 'ABC' ?>This is a test . <?end if?>
<?if@inlines: STS = 'LATE' ?>TESTETSTS<?end if?>
</code>
Answer: Take off the @inlines. That's what is preventing the new lines.


Speed up "NOT EXISTS" database query

Question: I have the following Postgres query generated by SQLAlchemy. The goal is to get submissions related to grading assignments and that are part of 3 of our courses (=programs), but only those that have not been reviewed already.
SELECT
    submissions.* # edited for brevity
FROM
    submissions
JOIN
    assignments ON assignments.id = submissions.assignment_id
JOIN
    modules ON modules.id = assignments.module_id
WHERE
    assignments.team IN ('grading') AND
    modules.program_id IN (11, 106, 108) AND
    submissions.gets_review IS true AND
    NOT (
        EXISTS (
            SELECT 1
            FROM reviews
            WHERE submissions.id = reviews.submission_id
        )
    )
ORDER BY submissions.created_at asc
LIMIT 15
OFFSET 0

Which generates this query plan:
                                                                            QUERY PLAN
------------------------------------------------------------------------------------------------------------------------------------------------------------------
 Limit  (cost=16964.33..16966.08 rows=15 width=167) (actual time=173.618..173.623 rows=3 loops=1)
   ->  Gather Merge  (cost=16964.33..17015.43 rows=438 width=167) (actual time=173.616..173.672 rows=3 loops=1)
         Workers Planned: 2
         Workers Launched: 2
         ->  Sort  (cost=15964.30..15964.85 rows=219 width=167) (actual time=166.425..166.426 rows=1 loops=3)
               Sort Key: submissions.created_at
               Sort Method: quicksort  Memory: 25kB
               Worker 0:  Sort Method: quicksort  Memory: 25kB
               Worker 1:  Sort Method: quicksort  Memory: 25kB
               ->  Nested Loop Anti Join  (cost=356.11..15958.93 rows=219 width=167) (actual time=166.358..166.402 rows=1 loops=3)
                     ->  Hash Join  (cost=355.68..8645.36 rows=7373 width=167) (actual time=12.691..152.481 rows=1545 loops=3)
                           Hash Cond: (submissions.assignment_id = assignments.id)
                           ->  Parallel Seq Scan on submissions  (cost=0.00..7976.62 rows=63809 width=167) (actual time=0.008..101.093 rows=50787 loops=3)
                                 Filter: (gets_review IS TRUE)
                                 Rows Removed by Filter: 93127
                           ->  Hash  (cost=346.16..346.16 rows=762 width=4) (actual time=12.585..12.585 rows=675 loops=3)
                                 Buckets: 1024  Batches: 1  Memory Usage: 32kB
                                 ->  Hash Join  (cost=44.69..346.16 rows=762 width=4) (actual time=0.318..12.372 rows=675 loops=3)
                                       Hash Cond: (assignments.module_id = modules.id)
                                       ->  Seq Scan on assignments  (cost=0.00..285.39 rows=6099 width=8) (actual time=0.010..4.978 rows=6099 loops=3)
                                             Filter: (team = 'grading'::teams)
                                             Rows Removed by Filter: 492
                                       ->  Hash  (cost=43.09..43.09 rows=128 width=4) (actual time=0.225..0.226 rows=128 loops=3)
                                             Buckets: 1024  Batches: 1  Memory Usage: 13kB
                                             ->  Seq Scan on modules  (cost=0.00..43.09 rows=128 width=4) (actual time=0.010..0.182 rows=128 loops=3)
                                                   Filter: (program_id = ANY ('{11,106,108}'::integer[]))
                                                   Rows Removed by Filter: 897
                     ->  Index Only Scan using ix_reviews_submission_id on reviews  (cost=0.42..1.00 rows=1 width=4) (actual time=0.008..0.008 rows=1 loops=4636)
                           Index Cond: (submission_id = submissions.id)
                           Heap Fetches: 4633
 Planning Time: 0.763 ms
 Execution Time: 173.760 ms

I might be over-optimizing, but 174ms seems too slow.
We have all the basic indexes plus a couple we created manually.
How could I speed up this query?
Comment: "Heap Fetches: 4633"  Vacuum your tables would be step 1.  If that doesn't work, show us the new plan
Comment: Just the seq scan on submissions seems way too slow on any reasonable hardware (and takes up over half your time).  Can you turn on `track_io_timings` and then show us `explain (analyze, buffers) select count(*) from submissions where gets_review ;`
Answer: You could try moving the NOT EXISTS predicate into an explicit anti-join to see if it gets you a better plan:
SELECT
    submissions.* # edited for brevity
FROM
    submissions
JOIN
    assignments ON assignments.id = submissions.assignment_id
JOIN
    modules ON modules.id = assignments.module_id
LEFT JOIN
    reviews ON submissions.id = reviews.submission_id
WHERE
    assignments.team IN ('grading') AND
    modules.program_id IN (11, 106, 108) AND
    submissions.gets_review IS true AND
    reviews.id IS NULL
ORDER BY submissions.created_at asc
LIMIT 15
OFFSET 0

Answer: try creating partial index on submissions table.
CREATE INDEX ix_assignment_id_created_at ON submissions (assignment_id, created_at)
WHERE (gets_review IS true);

Speed up "NOT EXISTS" database query


Firebase mail link sign-in (Dynamic Links) is not working on device

Question: I am using mail link sign-in in my application. When I test with a simulator, mail link sign-in is completely working. But when I test with a device, it does not work.
Clicking sign-in link on iPhone opens Safari like this.

But tapping OPEN button doesn't open my app.
Further, it opens my deep link url in spite of setting to open AppStore if user doesn't install my app in Firebase Console.
My code is working in a simulator. So, is there anything that I have to need setting for testing sign-in link or Dynamic Links in device?
Answer: I solved this problem. I did the following:

Delete the app
Clean the project
Restart a device
Answer:
No need to wipe the app. Long press on the link and select your app as the destination.


something went wrong with gnome3 installation

Question: i issued the following commands:
sudo add-apt-repository ppa:gnome3-team/gnome3
sudo apt-get install gnome-shell
and then i found the following change in the system :

but i dont find my desktop looking like this.
WHAT has gone wrong ? please help !
Answer: Looks like your theme has a problem. Found something similar on superuser.com here.
The answer from the source reads:

Try this, it worked for me:
sudo apt-get purge gnome-accessibility-themes
sudo apt-get install gnome-themes-standard

Then open the Gnome Tweak tool listed above and select Adwaita
Answer: Ubuntu 11.10 uses Gnome 3 by default, and you don't have to add any PPA to get that desktop. It's in the official repositories. It's called Gnome Shell.
Comment: But the screenshot suggests that the user is on Ubuntu 11.04 Natty Narwhal and not Ubuntu 11.10 Oneiric Ocelot
Comment: yes, but I would always recommend upgrading Ubuntu instead of installing Gnome from a PPA.
Answer: It's perhaps unfortunate that you have installed Gnome-Shell on Natty (11.04) with that particular PPA.
In the PPA description:

=== Ubuntu 11.04 (Natty) === This PPA contains packages from GNOME 3.0 and their dependencies. It is considered EXPERIMENTAL and MAY BREAK
  YOUR SYSTEM. There is no downgrade process.
=== 2011/12/30 === There is no further Natty/11.04 support from now on!

The Gnome-3 packages in that PPA have now moved on and are increasingly incompatible with the remaining Natty packages.  Even if you resolve this particular theming issue - you will increasingly encounter newer problems as time goes by and further updates are made.
I hate to say it - and the maintainers make it clear - you will need to reinstall your system :(

Backup you /home folder to an external hard-drive,
install 11.10
use this Q&A to install gnome-shell
copy back your files to your new home folder.


shell non integer argument in expr error

Question: I wrote the following code in shell script:
num=$1
sum=0; rn=0
less=0; fact=0
while [ $num -gt 0 ]
do
rn=`expr $num % 10`
num=`expr $num / 10`
while [ $rn -gt 1 ]
do
less=`expr %rn - 1`
fact=`expr $rn \* less`
rn=`expr $rn - 1`
done
sum=`expr $sum + $fact`
done
echo $sum

but the terminal  shows the following error without any line number :
Terminal Error pic
Please tell me where did i mess up??
Answer: The immediate problem is
less=`expr %rn - 1`

Change that to
less=`expr $rn - 1`

and you should sail home. But you can also debug your scripts using the -x option of bash which would give you a line by line analysis.
The use of expr is discouraged as you could easily replace that with ((expression)) construct (or calc if you need floating point operations). Then,
fact=`expr $rn \* $less`

will become a much easier
((fact=rn*less))

The advantage is that you should not bother escaping characters that have special meanings in shell like *
Comment: We also sometimes use variable name=$((expression)) .Does it work the same way as ((Entire thing))?? And why and where do we need to add spaces before variable for operations??
Comment: @RichiDubey For the first part of your question, the answer is yes.. The `(())` construct automatically figure out the variables for you.. For assignments in bash, it is mandatory that there are no spaces before and after the `=` sign. I can't think of any other examples where the use of spaces are restricted.


Disable typing 0 (zero) at first character position

Question: I'm using a Jquery numeric plugin that only allows numeric values to be typed in an input
<code>$("#tbQuan").numeric();
</code>
In addition to what this plugin is doing I need to disable typyng '0' (zero) at the first character position.
Any help would be appreciated.
Comment: Nothing. I'm a Jquery nube. Same goes for javascript
Comment: Can you provide a link to the plugin you are using?
Comment: http://www.texotela.co.uk/code/jquery/numeric
Answer: Try this.
<code>$('input').keypress(function(e){
   if (this.value.length == 0 && e.which == 48 ){
      return false;
   }
});
</code>
Demo
Comment: Type something like 'asdf' goto position 0 and type zero :)
Comment: Thanks. This is almost perfect since the zero appears for a second. I would have preferred for zero not to appear at all. I'll accept as an answer since it gets the job done.
Comment: @boruchsiper - Check my edited answer, it is even more better. Now you will not see 0 at all.
Comment: the above code works as it should ''BUT" if you select all and then press 0 it accepts the input - for that i implemented an additional charAt(0) check condition..to be in the safe side
Answer: For the keyUp event
<code>$('.numeric').keyup(function(event) {

var currentVal = $(this).val();

if (currentVal.length == 1 && (event.which == 48 || event.which == 96)) {
  currentVal = currentVal.slice(0, -1);
}
$(this).val(currentVal);
</code>
});
DEMO

make sure to add both 48 and 96 events to support number pad 0 and keyboard 0.
adding this way, user get to know that leading zeros are not allowed
Answer: Something like this should get you started:
<code>$("#tbQuan").numeric().keyup(function (e) {
    var val = $(this).val();
    while (val.substring(0, 1) === '0') {   //First character is a '0'.
        val = val.substring(1);             //Trim the leading '0'
    }
    $(this).val(val);   //update input with new value
});
</code>
Comment: Thanks. This almost works. The problem is that it allows to enter 0 at first position and replaces the next time another number is typed. I need to disable typing 0 at first position all together.
Comment: Whoops! Try the keyup event instead. Modified answer to reflect that. Sorry to say that you cannot use JavaScript to disable certain keys on the keyboard as that goes well beyond the scope of JavaScript. You can try to sanitize the input (which is what this script is doing).
Comment: Thanks. Looks like @ShankarSangoli beat you to the chase with a similar solution so I accepted his answer first. Though I have the same issue with his answer as with yours. The 0 appears for a moment before getting erased. I would have preferred for zero not to appear at all,
Comment: I would disagree with you on disabling certain keys in JavaScript. The numeric plugin I'm using does just that for none numeric keys.
Answer: I'd start by trying something like this:
<code>$('input').keyup(function(){
   if ( $(this).val().length === 1 && $(this).val() === 0 ){
      alert('No leading zeroes!');
   }
);
</code>
Comment: Thanks. This is almost what I need. Just that I don't need it to alert, I just want for the keydown not to happen at all just like one can't type none numeric values with the numeric plugin.
Answer: if textbox in masked then:::
<code>$('#numeric').keyup(function(event) {

    var currentVal = $(this).val();

    if (currentVal.substring(0, 1) === '0' && (event.which == 48 || event.which == 96)) {

      currentVal=currentVal.substring(1);
    }
    $(this).val(currentVal);
  });
</code>
OR *******************************
<code>$("#numeric").keyup("input propertychange paste", function (e) {
var val = $(this).val()
var reg = /^0/gi;
if (val.match(reg)) {
    $(this).val(val.replace(reg, ""));
    alert("Please phone number first character bla blaa not 0!");
    $(this).mask("999 999-9999");

}
</code>
});

First Sample DEMO :
Second Sample DEMO :


Why is my conditional not working?using fgets output

Question: I need a method for getting each input characters and putting them in a 2D array (in this case a char array).
But as I need this from file input that has several end of lines (\n), I don't want these to be inserted into the array, so I was trying to make a conditional that if the character is a newline, it should not be placed in the array, but it doesn't seem to work.
Just to make clear, I am trying make this method by myself because I didn't find one online, and fgets was the best method I found.
My code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]) {

    char words[4][4][2];
    char verif[2];

    int i, j, l = 0, lin = 4, col = lin;

    printf("Insert numbers: ");
    for (i = 0; i < lin; i++)
    {
        for (j = 0; j < col; j++)
        {
            fgets(verif, 2, stdin);
            //since I was using the IDE to write I also put a condition not to add the enter for the input but it doesn't work too lol

            if (strcmp(verif, "\n\0") != 0 || strcmp(verif, "\r\0") != 0)
            {
                printf("copying...\n");
                printf("%s\n", verif);
                strcpy(words[i][j], verif);
                l++;
            }
            else
                j--;
        }
    }

    printf("\n");

    for (i = 0; i < lin; i++)
    {
        for (j = 0; j < col; j++)
        {
            printf("-%s\t", words[i][j]);
        }
        printf("\n");
    }

    return 0;
}

the input I would use to be placed in the matrix:
1234
1234
1234
1234

With a normal input like 1234123412341234 the output (printf matrix) is ok:
-1  -2  -3  -4
-1  -2  -3  -4
-1  -2  -3  -4
-1  -2  -3  -4

Comment: Using `fgetc()` and discarding the `'\n'` or `'\r'` characters would be a lot simpler.
Comment: Coming back on @Armali: `||` is wrong here! You compare your input against two values that are not equal – thus no matter how your input looks like it can only be equal to at most one of these – meaning it remains unequal to the other one – thus if not both, one of them is *always* true... You need to check if the string not equal to *any* of the two, thus unequal to *both* of them, thus you need `&&` (while second one is obsolete anyway)
Comment: `strcmp` *compares* the *entire* string – you might want to search for the new line character only, so `strchr(verif, '\n')` – and you won't need to check for `\r` either, that character won't pass through the API anyway (`\r\n` is reduced to `\n` only unless you have opened a *file* in *binary* mode).
Comment: Just checking the first character is an optimisation – the true error was using `||` instead of `&&`, which @Armali hinted to at the first place and which I tried to explain earlier, too. Given any arbitrary `a` and `b` with `a != b` then `c != a || c != b` is a tautology as `c` can ever be equal to just one of `a` or `b` and thus *must* be unequal to the other one (if it isn't to both anyway – which is what you actually are after and get by using `&&`!).
Comment: @Armali yeah i  didn't pay attention for that lol, i saw their answer now too
Comment: Did you debug this? Why do you think that different input should result in the same output?
Comment: @gettingAway –
You confused `||` and `&&`.
Comment: Side note: String literals are null-terminated per se, and all the C-string API operates only up to the very first null character anyway. So the doubly terminated array you produce by `"\n\0"` won't be handled any differently than the singly terminated one `"\n"`.
Comment: @Jabberwocky Idk if i understood your question correctly, but what i want to is actually put in a matrix, the output is just for a verification. The input on a txt file for example, would have 1234\n1234\n1234\n1234,and the"\n" would also be added in the array
Comment: @aconcagua right??? but it still doesn't work using strchr. I used strcmp because i read some post saying that "\r\0" would be the output for a "enter" using fgets.
Comment: @Armali May i know how lolll
Comment: @Fe203 For what i understood fgets saves the each input on buffer, then if i put 123 it would  get into the array. But if i discard the last input, the \r , the array would simply recieve null, isn't it?
Comment: Actually you are using `fgets` for reading just one single character – as limit 2 allows just such one while `fgets` null-terminates. You could compare simply the first character then: `*verif != '\n' && *verif != '\r'` – you can have it much simpler, as @Fe2O3 mentioned already, by always just reading single characters, such as [here](https://godbolt.org/z/feGafrPoq), skipping *any* whitespace – or do you intend to read longer strings later on?
Comment: @Aconcagua My purpose is only reading one character thought! Your statement worked just fine! Could you explain me the difference of it  from strchr(verif, '\n')==0, like aren't these the same characters? I didn't even think about using getchar ;-;  i feel i have wasted my life lolll. Thanks a lot !
Comment: @gettingAway –
Excuse me, but how can I tell you how you came to think that you would have to use `||` where `&&` was in order? - Ah, I see Aconcagua explained it better.
Answer: fgets(verif, 2, stdin) is a contorted way to read a single byte from the standard input.  You could just write int ch = getchar(); and handle the byte value directly instead of using string comparisons.
Yet the main problem lies in the test if (strcmp(verif, "\n\0") != 0 || strcmp(verif, "\r\0") != 0): you should use && instead of || as you want to handle input that is neither a newline nor a carriage return, which translates to (not a newline) and (not a carriage return).
Here is a simpler version:
#include <stdio.h>

int main(int argc, char *argv[]) {
    char matrix[4][4];
    int lin = 4, col = lin;

    printf("Enter the digits: ");
    for (int i = 0; i < lin; i++) {
        for (int j = 0; j < col;) {
            int c = getchar();
            if (c == EOF) {
                fprintf(stderr, "premature end of file, aborting.\n");
                return 1;
            }
            if (c != '\n' && c != '\r') {
                printf("inserting %c\n", c);
                matrix[i][j] = c;
                j++;
            }
        }
    }

    printf("\n");

    for (int i = 0; i < lin; i++) {
        for (int j = 0; j < col; j++) {
            printf("-%c\t", matrix[i][j]);
        }
        printf("\n");
    }

    return 0;
}

Answer:
I would suggest using functions.
strcmp compares whole strings - you need to read a bit about them.
to compare 1 char you do not need to use string functions.
You can "manually" construct the string by null character terminating the array

int readWords(size_t size, char (*array)[size][2], FILE *fi)
{
    int result = 0;
    char buff[80] = "";
    size_t index = 0;

    for(size_t row =0; row < size; row++)
    {
        for(size_t col = 0; col < size; col++)
        {
            if(buff[index] == 0 || buff[index] == '\r' || buff[index] == '\n')
            {
                if(!fgets(buff, sizeof(buff), fi))
                {
                    result = -1;
                    goto cleanup_exit;
                }
                index = 0;
            }
            array[row][col][0] = buff[index++];
            array[row][col][1] = 0;
        }
    }
    cleanup_exit:
    return result;
}

int main(int argc, char *argv[]){

    char words[4][4][2];
    char verif[2];

    int i, j, l=0, lin=4, col=lin;

    printf("Insert numbers: ");
    if(!readWords(4, words, stdin))
    {
        printf("\n");
        for(i=0;i<lin;i++)
        {
            for(j=0;j<col;j++)
            {
                printf("-%s\t", words[i][j]);
            }
            printf("\n");
        }
    }
    else
    {
        printf("Error reading the array\n");
    }

    return 0;
}

https://godbolt.org/z/WsMqdedra


Create a simple Dropdown list

Question: I am very new in ROR. I want to create a simple dropdown list. Say select state from drop down. The selected value from list must be store in DB on click on submit button. How can I create this?
Comment: Right now the question is too vague to be answered, you need to provide some code and an actual coding problem. I would suggest reading http://guides.rubyonrails.org/getting_started.html and experiment a little.
Comment: Atleast show that you have tried , no ones going to make it for you if you yourself don't show any eagerness to achieve it
Answer: Check the documentation on form options helper.
Comment: Thanks to u also Isotope.
Answer: See the railscast video tutorial. Hope it helps.

Create a simple Dropdown list


In C, what happens in memory when we do cast int to struct*?

Question: typedef struct block
{
   size_t size;
   struct block* next;
} node;

static char arr[1000];

What happens with arr
when I do
node* first_block = (node*)arr;

?
I understand that this is equal to
node* first_block = (node*)&arr[0];

but
sizeof(node) = 8;
sizeof(arr[0])= 1;

so first element override next seven elements in the arr, because it's struct now ? Can you explain me this cast, please ?
Comment: Note that this may not work properly. `node` requires an alignment greater than what `arr` is required to have.
Comment: can you explain this please?
Comment: I'm going to use a simpler example: `char x[4]; int32_t *y = &x` It's possible that `x` has an address like `0x1001`. However, `int32_t` requires an alignment of 4 bytes. The address that `x` has breaks that contract.
Comment: If you are really planning to go ahead with this, please consider [using a union instead](http://stackoverflow.com/questions/1821486/union-versus-void-pointer). It has the same effect as casting a pointer (i.e. impose a _different_ compile-time interpretation to the _same_ raw byte data), but in a more structured manner. It also prevents potential alignment issues as raised by Bill Lynch.
Comment: The coolest pointer type cast ever is in the _fast inverse square root_ algorithm. Reading the [Wikipedia article](http://en.wikipedia.org/wiki/Fast_inverse_square_root) may actually help you understand the effect of such a type cast.
Answer: When you write
node* first_block = (node*)arr;

you are not changing anything in memory, you get a pointer to the area in memory, the type of the pointer determines how the area is treated in regard to pointer arithmetic.
first_block->next will be a pointer that is determined by the characters in the array.
as a comparison say you have a char* pointer to the same array
(if arr is declared at global scope it will contain 0's)
char* q = arr;
node* p = (node*)arr;

                arr[1000]
          +----------------------+
  q  ->   |   |   |          |   |
          | 0 | 0 | ...      | 0 |
  p ->    |   |   |          |   |
          +----------------------+

when you do
q = q + 1;

// you move the character pointer one char forward since q is a char pointer

when you do
p = p + 1;

// you move the node pointer sizeof(node) chars forward since p is a node pointer

when you do *q you get the character value of where q points to, *p gives you the node value from the char arr, i.e. the characters are interpreted as a node struct.
Comment: so when I do

    p->size = 100;

arr[0] = 100;

what will be after p->next = 0x123123 ?
arr[1] = 0x123123 ?
Comment: depends on your architecture (endianness, sizeof int)  100 is 64 hex but easiest is just to print out the value with `printf("%p", p->next);`
Answer: It's related to pointer arithmetic, when you have a pointer type *pointer, and you do this
type *next = pointer + 1;

or
type *next = &pointer[1];

you are effectilvely doing this
type *next = ((char *)pointer + sizeof(type));

Comment: yes, so after this cast, my array arr its array of structs?
Comment: No, it's not an array of structs. Because `&arr[1]` will point 1 byte after `&arr[0]`, so it's not an array of structs.
Comment: so first 8 byte will be a struct and other(1000 -8) a char ?
Answer: nothing happens to the data when the code does a 'cast'.
However,
the compiler will treat that data differently for the duration/scope of the cast.
the duration/scope of the cast is (almost always) only the statement that contains the cast.
Comment: so first 8 byte will be a struct and other(1000  -8) a char ?
Comment: No,  the scope of the cast is just the line containing the cast.  none of the data is changed.   It will be the (size of struct) bytes of array will be treated as an instance of the struct, for the duration of that one line of code.   Since an array devolves to a pointer, the code act as though that pointer were pointing to an instance of the struct (but only for that one line of code)
Answer: Memory does not know about types, so nothing happens to it when casting. Types in C just describe how the bytes in memory are interpreted.
You can treat a sequence of 8 bytes as 8 ASCII characters (char[8]) or a struct node. Casting just changes the view of the data, but the data is not affected.


How to keep indentation when using blocks in Twig

Question: I try to make a pretty RSS Feed in a Symfony project. For each item, I include one file. It's ok but when I look the output, Twig reset indentation in the block element. Here an example :
<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
  xmlns:content="http://purl.org/rss/1.0/modules/content/"
  xmlns:wfw="http://wellformedweb.org/CommentAPI/"
  xmlns:dc="http://purl.org/dc/elements/1.1/"
  xmlns:atom="http://www.w3.org/2005/Atom"
  xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
  xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
>
  <channel>
    <title>Space Raclette</title>
    <description></description>
    <language>fr</language>
    <lastBuildDate>Wed, 30 Nov 2016 11:22:45 +0100</lastBuildDate>

<item>
  <title>Topic de l'ƩtƩ du Capitaine Crochet 2</title>
  <link>...</link>
  <guid isPermaLink="false">.../39fa</guid>
  <description></description>
</item>

<item>
  <title>Topic de l'ƩtƩ du Capitaine Crochet</title>
  <link>...</link>
  <guid isPermaLink="false">.../39fa</guid>
  <description></description>
</item>

  </channel>
</rss>

What can I do to keep the indentation without have bad indentation in the "item file" ? I tried to play with spaceless and -, without success.
Here my files if it can help.
layout.rss.twig :
<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
  xmlns:content="http://purl.org/rss/1.0/modules/content/"
  xmlns:wfw="http://wellformedweb.org/CommentAPI/"
  xmlns:dc="http://purl.org/dc/elements/1.1/"
  xmlns:atom="http://www.w3.org/2005/Atom"
  xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
  xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
>

  <channel>
    <title>{{ channel.brand }}</title>
    <atom:link href="{{ app.request.uri }}" rel="self" type="application/rss+xml" />
    <link>{{ url }}</link>
    <description>{{ channel.description|striptags }}</description>
    <language>{{ channel.lang }}</language>
    <lastBuildDate>{{ last_publication.published|date('D, d M Y H:i:s O') }}</lastBuildDate>

    {% block content %}{% endblock %}

  </channel>
</rss>

index.rss.twig
{% extends 'RSSBundle::layout.rss.twig' %}
{% block content %}
  {% for publication in web_publications %}
    {{ include('RSSBundle:Publication:_single.rss.twig') }}
  {% endfor %}
{% endblock %}

_single.rss.twig
<item>
  <title>{{ publication.title }}</title>
  <link>{{ url }}</link>
  <description></description>
  <pubDate>{{ publication.published|date('D, d M Y H:i:s O') }}</pubDate>
</item>

Comment: This will be a pain. You'd better create a function that will take your rss as input and will return your beautified rss as output. For example: `{{ beautify_xml(include("hello.rss.twig")) }}` where `beautify_xml` will be in a twig extension with [this implementation](http://stackoverflow.com/a/3616722/731138).
Comment: Is it just white space you need `visually` or do you want spaces (indentation) in the source code (view source in browser)?
Comment: @AlvinBunk as we are in an XML feed, it's the same in this case. But it's for the source code, yep.
Comment: Thx @AlainTiemblo for your comment. Seems to be "overkill" just for good indentation... I don't want to lose in performance for that, so I'll keep what I currently have.
Comment: There are low-level extensions to do that, like "tidy html" and there are probably others. I developed some code generators and believe me, I prefer running the cs-fixer post generation than taking care of cs when writting my templates.
Answer: Twig can remove whitespace characters in some cases, but it never adds them. So most obvious and simple solution is just to indent the included template.

Whitespace is not further modified by the template engine, so each whitespace (spaces, tabs, newlines etc.) is returned unchanged.

You can post-process the result XML. For example you can load it into the DOMDocument and dump with formatOutput option. Or through the tidy. Anyway it requires a some additional work.
But (IMHO), Twig is not a right tool for XML processing. Better use any standard API to build XML, such as DOMDocument (with formatOutput) or XMLWriter (with setIndent()).


Let $f:[a,b]\to\mathbb{R}$ be integrable on $[a,b]$. Show that if $ F(x)=\int_a^x f(t)\,dt$ then $F(x)$ is continuous on $[a,b]$.

Question: I gave a two liner proof on a test for this as follows:
Proof: By the Fundamental Theorem of Calculus (First Form) $F'(x)=f(x)$, thus $F$ is differentiable. By an earlier Theorem, $F$ is continuous.
I looked back after submitting, and the earlier theorem states:
Theorem: Let $f:(a,b)\to\mathbb{R}$ and let $c\in(a,b)$. If $f$ is differentiable at $c$ then $f$ is continuous at $c$.
Now I am pretty sure I messed this up because the bounds of the theorem are open, not closed. What should I have done to prove this correctly?
UPDATE: I received my exam back, and missed five points on this question (only 5 points that I missed) here is the feedback my professor gave:
Excellent!
The only problem is:
Problem 6: 5.  The First Fundamental Theorem of Calculus only works is f is continuous, not if f is merely integrable.  It is not, in general, true that F is differentiable for an integrable f.
Answer: I suspect that whoever asked you this question expected this answer: since $f$ is Riemann integrable, then, in particular, it is bounded. Take $M>0$ such that $(\forall t\in[a,b]):|f(t)|<M$. If $\varepsilon>0$, take $\delta=\frac\varepsilon M$. Then, if $x_0\in[a,b]$ and $x\in[a,b]$ is such that $|x-x_0|<\delta$, the$$|F(x)-F(x_0)|=\left|\int_{x_0}^xf(t)\,\mathrm dt\right|\leqslant M.|x-x_0|<\delta|x-x_0|<\varepsilon.$$
However, what you did is not silly. For any interval (with more than one point) $I$, every differentiable function from $I$ to $\Bbb R$ is continuous.
Comment: Well that makes me feel a lot better!
Comment: Doesn't this also satisfy Lipschitz continuity?
Comment: @RealAnalysisNoob Yes, it does, since $|F(x)-F(x_0)|\leqslant M.|x-x_0|$.


Where do I stop grinding level and focus on my gear?

Question: I started to play Path of Exile and really enjoy it. I played some games of this kind before so I know the concept. I know that Path of Exile as a level cap of 100. However it is kind of long to reach as I can on the official forum and official game FAQ.
I want to know where I should stop "grinding" experience doing with the stuff I picked up on the ground because I know I'll use something else later and start focusing on having a good gear and maybe use the crafting materials I kept all the way through the dificulties.
For exemple; In diablo 2 when you were between levels 80 and 85 it was a good time to stop grinding and start gearing up.
I'm open to any Math-based or non-math-based answers as well as any experiments you can do!
Comment: I suspect this is heavily opinion or individual playstyle-based. The generic answer is something like "whenever getting a gear upgrade becomes easier than gaining a level, and when continuing gets harder". Unless you're playing hardcore, in which case it's "now".
Answer: This question will have a different answer depending on what build you are trying to accomplish.
For example, the old 'CI Fire Discharger' would require level 80 or so before being able to effectively respec from HP to CI/ES. Because of this, you would use whatever HP gear you could cheaply find until you got to 80+, and then respec and get expensive gear at the same time. This is of course an example of a build that doesn't become extremely powerful until really late, most other popular builds because powerful much earlier.
As a general rule, a time to focus more on gear would be around level 70, when you are in Merciless Act 3 and are ready to start farming Maps. Although high gear isn't needed to start the early level maps, most people will take a massive gear jump before starting them. Most CI classes will also spec out of HP and into CI at around the 60-70 mark, considering they have the CI gear ready.
Once again though, this all depends on the build you are playing and how you want to approach it as to when XP farming turns to gear farming.


Getting flash 10.2 GPU acceleration working

Question: I'm using 32 bit ubuntu 10.10 and the latest version of the NVidia drivers for an ION GPU and have downloaded the new 10.2 flash beta.
I can confirm that in firefox I am using the beta of flash but no hardware acceleration is used for flash videos.
Do I need to install some more libraries?
Change Desktop manager?
Comment: Were you expecting flash to have gpu acceleration? AFAIK there isn't any. Can you link to any data showing they're adding GPU support?
Comment: There is support in the beta See here:  http://www.osnews.com/story/24092/Flash_Player_10_2_Beta_Delivers_Hardware_Acceleration_on_Linux
Answer: After a bit of research I can answer my own question. The full way to get flash using the an nvidia ion gpu on ubuntu 10.10:
Install the new flash 10.2 beta:
wget http://download.macromedia.com/pub/labs/flashplayer10/flashplayer10_2_p2_32bit_linux_111710.tar.gz
tar zxvf flashplayer10_2_p2_32bit_linux_111710.tar.gz
sudo cp libflashplayer.so /usr/lib/flashplugin-installer/

You may need to also replace flash in other locations if you have installed in multiple places (try using 'locate libflashplayer.so' for a complete list)
Then for gpu support you also need (this was the bit I was missing):
sudo apt-get install libvdpau1

If you also want it working in chrome try:

Can you use the new beta Adobe Flash 10.2 in Google Chrome
http://lifehacker.com/5705588/how-to-get-the-flash-102-beta-working-in-google-chrome

To verify it is working go to a high-def you-tube video and play it. While it is playing right click and select - video info. You should see "Accelerated Video Rendering" if it has worked.
These instructions worked on my acer revo with a nvidia ion gpu.
Also on my blog with more links: http://decodify.blogspot.com/2010/12/getting-flash-102-beta-gpu-acceleration.html
Comment: Can you update your answer? By now 10.2 is in the updates repository for everyone, etc.
Comment: when you say "New beta Adobe Flash" which version number are you referring to?
Comment: Is this the whole story though? Isn't the aim to get the GPU to do the decoding as well, i.e. as well as saying "accelerated video rendering" it shouldn't say "software video decoding"? Following the process detailed above, I do see "accelerated video rendering" but still get "software video decoding" - and 100% CPU usage.
Answer: You must add this line to /etc/adobe/mms.cfg :
EnableLinuxHWVideoDecode=1

Answer: If it is working, the info window should say
'accelerated' decoding instead of 'software' decoding.
Each core should drop from 100% down to 5%.
if /etc/adobe/mms.cfg does not exist, you must create it (plus the directory) and add that single line mentioned above.


How do I truncate a string with an ellipsis in a Silverlight TextBlock?

Question: If I display a string too long for a TextBlock it just appears to keep writing past the edge of the TextBlock.  I'd rather it use the common technique of adding an ellipsis ("...") if the text is not going to fit in the space provided.  How should I go about doing this in Silverlight?
The references I've found all use the TextRenderer class which is not available in Silverlight
Comment: I found http://stackoverflow.com/questions/1565953/how-to-text-wrap-and-add-at-the-end which asks the same question, but both examples given in the accepted answer use TextRenderer, so they are not actually applicable for Silverlight.
Answer: You didn't say which Silverlight version this is. Assuming Silverlight 4, it's baked into TextBlock via the TextTrimming property.
<TextBlock TextTrimming="WordEllipsis"/>

The only thing you have to do is make sure your TextBlock's width is properly restricted and you use NoWrap for TextWrapping.
Answer: Set the TextTrimming property to WordEllipsis.
<TextBlock Text="My long text" TextTrimming="WordEllipsis"/>


What does it mean when I say that addition/multiplication for an equivalence relation is well defined?

Question: I have trouble understanding this concept. Why is it necessary to prove that addition or multiplication is well defined in equivalence classes? My understanding of equivalence classes is that it must be reflexive, symmetric and transitive. Doesn't proving it automatically imply that addition and multiplication can be done? Why the additional need to prove that it is 'well defined'?
Apologies if this question is too trivial; my understanding of this topic is limited.
Answer: Consider this equivalence relation on $\mathbb N$:
$$a \sim b \quad\text{iff}\quad \lfloor a/10 \rfloor = \lfloor b/10 \rfloor $$
which says that two naturals are related if they differ only in their last digit.
This is a perfectly good equivalence relation, but we can't extend addition to equivalence classes by the same rule that works for modular arithmetic:
$$ [a]_\sim + [b]_\sim = [a+b]_\sim $$
The problem is that the sum of two equivalence classes now depend on which representatives we use to define their sum. For example, the rule seems to imply that
$$ [11]_\sim + [32]_\sim = [43]_\sim \\
[17]_\sim + [35]_\sim = [52]_\sim $$
However $[11]_\sim$ is the same equivalence class as $[17]_\sim$, and $[32]_\sim = [35]_\sim$, but $[43]_\sim$ is not the same as $[52]_\sim$. So the definition doesn't really tell us which of the equivalence classes should be the result of
$$ \{10,11,\ldots,19\} + \{30,31,\ldots,39\} $$
Checking that addition on the equivalence classes "is well-defined" means convincing oneself that this situation does not occur for the equivalence relation you're looking at.
Comment: Just curious, how did you come up with this example?
Comment: @Ovi: Nothing deep -- I just looked for the simplest-to-describe nontrivial equivalence relation on a well-known ring I could come up with that _isn't_ a congruence. (And then I restricted it from $\mathbb Z$ to $\mathbb N$ so the simple explanation in terms of digits would agree with a simple symbolic definition too).
Answer: Just because a relation is an equivalence, this doesn't mean it has to be "nice" with respect to any operation you'd like to put on its classes.  To see this, look at a non-example of something being well-defined.
Let $V=\mathbb{R}^2$ be the plane with its usual vector space structure.   Put a relation on $V$ by defining $u \sim v$ if $u = cv$ for some non-zero scalar $c$.  This is an equivalence relation on $V$.  The zero vector is in a class by itself, and the other classes are the vectors that form parallel lines through the origin (with the zero vector removed).
Since classes are naturally represented by vectors, you could attempt to define a natural addition on $V/\sim$ by
$$
[u] + [v] = [u+v].
$$
But this fails to be well-defined, even though the relation in play is an equivalence.
The problem is that two different people could add the SAME TWO classes but get different answers.  That's no good.  For example, Alice wants to add the class corresponding to the $x$-axis (with zero removed) to itself.  This class is $[(1,0)]$, for example. So, Alice does
$$[(1,0)] + [(1,0)] = [(2,0)] = [(1,0)].$$
Bob will do the exact same class addition, but recognize that $[(1,0)]$ is also equal to $[(-1,0)]$.  Then Bob gets
$$[(1,0)] + [(-1,0)] = [(0,0)] \neq [(1,0)].$$
Alice and Bob have added the exact same class to itself, but got conflicting answers.
Comment: In your example, you added classes by adding representative members.  Perhaps a union of the classes would be more like addition.  Intersect with the complement of a class would be like subtracting that class.
Comment: But a union of classes is not a class again.
Comment: Curious as to why the downvotes.
Comment: Downvote was not intentional.   You would have to use the "advanced" touchpad on my computer to appreciate this.   They added so many wonderful "features" and "gestures" that my cursor is all over the place and is effectively out of control.  At this point the stackworks software will not let me change anything.  Meanwhile, I have already taken my ancient copy of Hewitt & Stromberg 450 miles north to new home in Nevada.  I remember that class well: the instructor had dementia and we had to teach ourselves.  At least we didn't have cursor malware in 1970.
Answer: Suppose we have partitioned the set of all integers into $\mathbb Z_{10}$, the set of all equivalence classes modulo $10$.
Let $[n] = \{x \in \mathbb Z : x \equiv n \pmod{10} \}$ be the equivalence classes.
Now let's define $[a] \vee [b] = [\operatorname{lcm}(a, b)]$ for all
$[a], [b] \in \mathbb Z_{10}$
Then
\begin{array}{c}
   [2] &\vee &[6] &= &[6] \\
  [12] &\vee &[16] &= &[48] \\
\end{array}
But $[2]=[12], \ [6]=[16]$ and $[6] \ne [48]$. It follows that $\vee$ is not well defined on $\mathbb Z_{10}$.
Answer: Elaborating on Henning Makholm's answer:

Consider this equivalence relation on $\mathbb N$:
  $$a \sim b \quad\text{iff}\quad \lfloor a/10 \rfloor = \lfloor b/10 \rfloor $$
  which says that two naturals are related if they differ only in their last digit.
  [Define $+$ (1)]:
  $$[a]_\sim + [b]_\sim = [a+b]_\sim$$

The problem lies in the attempted definition (1) of the function
$$
+: \mathbb{N}/_\sim \times \mathbb{N}/_\sim \to \mathbb{N}/_\sim.
$$
Definition (1) is meant to be a shortcut (as a programmer you could call it syntactic sugar) for the following indirection defintion:

(2) $+$ is the unique function, so that for every $a, b \in \mathbb{N}$ the following holds: $[a]_\sim + [b]_\sim = [a+b]_\sim$.

For this definition to be well-defined you need to prove two things:

Existence of such a function
Uniqueness of it

However, such a function cannot exist as Henning Makholm's answer demonstrates.
Going deeper and uncovering the 'hidden' problems
You would see the problem more easily if you tried to define $+$ in a direct way:

(3) Let $x, y \in \mathbb{N}/_\sim$. ... Then set $\mathbb{N}/_\sim \ni z = \cdots$ We set $x + y = z$.

How would you construct the "…" part to match the attempted definition above? You could say:

(4) Let $x, y \in \mathbb{N}/_\sim$. Let $a \in x, b \in y$. Then set $\mathbb{N}/_\sim \ni z = [a + b]_\sim.$.

Here you can see that the definition of $z$ might depend on the choice of $a$ and $b$. Even if that was not true, you would need to prove that $x, y \neq \emptyset$.
Even in the attempted definition (4) the problem is well-hidden, you could say. Let us remove the boilerplate and remind us what a function really is:

If $X, Y$ are sets, then the relation $f \subseteq X \times Y$ is called a function $f: X \to Y$ $:\Leftrightarrow$

$f$ is a left-total relation: $\forall x \in X\ \exists y \in Y. (x, y) \in f$
$f$ is a right-unique relation: $\forall (x, y) \in f\ \exists_1 z \in B. (x, z) \in f$

With $+$ being intended to be a function $+: \mathbb{N}/_\sim \times \mathbb{N}/_\sim \to \mathbb{N}/_\sim$ in mind, we can now attempt definition

(5) $+$ is the function $\{\left((a, b), c\right) \in (\mathbb{N}/_\sim \times \mathbb{N}/_\sim) \times \mathbb{N}/_\sim\, |\, [c]_\sim = [a + b]_\sim \}$.

It still needs to be proved that the given set is indeed a function. Which property of it will be violated?
Spoiler:

 The set is not right-unique as Henning Makholm's answer demonstrates.

In summary, sometimes, operating only on the high-level thinking can easily lead to unforeseen and skipped-over problems.
Well-definedness in other areas
This problem is not restricted to equivalence classes, it always appears if one uses such an indirect definition. For example,

let the exponential function $\mathrm{exp}: \mathbb{R} \to \mathbb{R}$ be the unique function so that $\forall x, y \in \mathbb{R}. f(x + y) = f(x)f(y)$.

Is $\mathrm{exp}$ well-defined?
Spoiler:

 No, uniqueness is violated. This equation is satisfied by all exponential functions. For instance, apart from the obvious $x \mapsto e^x$ solution, $x \mapsto 3^x$ also satisfies the equation: $3^{x+y} = 3^x 3^y$.

 Indeed, one needs some more properties, so that uniqueness is guaranteed:

 The exponential function $\mathrm{exp}: \mathbb{R} \to \mathbb{R}$ is the unique Lebesgue-measurable function with $f(1) = e$, so that $\forall x, y \in \mathbb{R}. f(x + y) = f(x)f(y)$.
 Source: https://en.wikipedia.org/wiki/Characterizations_of_the_exponential_function
 Original source: Hewitt and Stromberg, Real and Abstract Analysis (Springer, 1965), exercise 18.46


How to find out what larger package some command is included in?

Question: I recently had a problem, and the good people on the interwebz seemed to agree that I should run the command "cec-client".
$ cec-client
-bash: cec-client: command not found
$ sudo apt-get install cec-client
E: Couldn't find package cec-client

At this point I had to google some more, finding out that cec-client was part of something called libcec, and that I should git clone and compile this library. Even for a semi-noob like me, this seemed rather convoluted, and lots of errors ensued.
Only later did I find out that cec-client is part of something called cec-utils, which I could install with sudo apt-get install.
I wasted a few hours on this. I assume that there is an established method by which I should have been able to discover that I needed to install cec-utils.
So what is it?
Best regards,
Steen
Answer: Either search the online catalog at packages.ubuntu.com

or install and use the apt-file utility:
$ apt-file search cec-client
cec-utils: /usr/bin/cec-client
cec-utils: /usr/share/man/man1/cec-client.1.gz

Comment: Thank you so much! This really solves a lot of problems for me! :-)


Advanced search query builder on smart phone

Question: I'm developing a Windows Phone 8 app where all the pages are in portrait orientation.
I have the problem of designing/porting this kind of a GUI to smart phones:

download bmml source – Wireframes created with Balsamiq Mockups
The comboboxes on the left represent boolean operators, the comboboxes on the right represent various fields (person's name, surname, address...), the middle textboxes contain keywords.
So, I came up with this:

download bmml source
Do you think this UI is understandable for the non-technical folk of the internets? Do you have any suggestions on improving the design?
Comment: To me, your mobile mockup looks like if the first field would be a general search (not field-specific), the second field would be for *Name*, the third field would be for *Surname* and the *Address* option must be a strange looking submit button. Why did you place the AND/OR select list to the left of the field select list?
Answer: You could try this layout.

The radios are to eliminate drop-down selection tasks on a mobile. At the same time default search attributes (Name, Surname, Address) should be selected as most probable ones to minimize selection tasks, too.
Also if you have no constraints on search field number you could provide all available attributes allowing some of them to be empty while submitting.
Comment: Excellent. I love this design.
Answer: This kind of interface should be the advanced mode on computer. On phone typing and many button/combo click is painful.Very few people like to customize very closely their search with and/or even on computer. If you can, replace it with only one search with no option.Then on the result page offer filtering options, Name must be, Surname must be, address must include...
The Thunderbird Global search option maybe a good sample how one search with no option and filters can helps to find the result (https://support.mozillamessaging.com/en-US/kb/global-search)
Comment: Unfortunately, is not up to me. The client wants this kind of advanced mode on the phone.
Comment: Maybe you could present only one search, with one combo name/address then iterate. Show the result page with static text representing the first search "Name is john" and a search box, combo and button to search with AND, search with OR.The third page will have 2 static "Name is john" "AND surname is doe" and so on


C#: Storing a .Net Object in the Registry

Question: Is it possible to store a .Net object in the registry?
I want to store a generic List<> in the registry, and then retrieve it and parse it back to the List.
Is this possible, or do I need to manually serialize it and then deserialize  it back?
[UPDATE]
Following the posted answers, I am going to serialize the object and save it in the Current User's AppData folder.
Answer: It's possible, if the type included in the list is serializable.  If that's the case, you can serialize it and store it in a string value.
But it's probably a very bad idea.  The registry gets big enough as it is. Instead, put this kind of thing on the file system, in the All Users Application Data folder.
Comment: Upvoted for adding WHY the proposed approach was a bad idea. (Apparently we aren't allowed to use the expression plus a one to the power of zero any more when writing a comment. This place is getting way too anal. I wonder whether I'm allowed to include THAT content?)
Answer: Why the registry?
The appropriate place to store these kind of serialised objects is usually in the users' Application Data folder or Isolated Storage.  Though of course the method of serialisation is up to you.  XML, binary etc, it's essentially a file on disk.
You could consider things like "Local Database" or SQL Server Express, depending on your data and concurrency needs.
Some applications do store a Most Recently Used (MRU) list in the registry, but that's just by iterating all the values of a given key.  I don't recommend that approach.
Answer: Yeah, I think you'd have to serialize and deserialize it yourself. But you could store it either as a binary block or text/xml. It's possible that there is a size limit to registry data...
The big question is "is this a good thing to do?"
Answer: You will have to serialize it yourself. Beware that there might be limitations on the amount of data you can store, depending on the Windows version.
http://msdn.microsoft.com/en-us/library/ms724872(VS.85).aspx
Answer: I'll just say this first: this sounds like a really bad idea.
If you insist on doing this, you're going to have to serialize it first. The registry doesn't support inserting .NET objects.
Answer: You would have to serialize it. The registry only stores primitive values.
Answer: You would need to manually serialize it.
Answer: Not quite sure why you'd want to store .NET objects in the registry, as there's already existing functionality in the BCL that allows you to do this with XML configuration files... but saying that, it is of course possible to store .NET objects in the registry. You'd probably only want to do it if the size of the object was relatively small, but it shouldn't be a problem anyway. I guess that the obvious way to do it would be to use XML Serialization (without formatting/whitespace) and store the object as a serialized string value.


Path variables not working on 0.6.5 e.g. METEOR_SETTINGS

Question: i cannot get it working after i updated to 0.6.5.
I created a new meteor project.
I have a start.sh script that looks like this.
export METEOR_SETTINGS=$(cat ./settings.json)
meteor

settings.json:
{
  "public":{
    "bla":"blup"
  }
}

Meteor.settings on the client is undefined. It works if i add the settings json file via "--settings", but unfortunately this is not what i need.
The PORT environment variable or NODE_ENV also does not work for me.
Adding some random stuff like "export MY_ENV_VAR=foo" however works.
Am i missing s.th.? It all worked well before. I would really appreciate your help.
Thx!
(also created an issue: https://github.com/meteor/meteor/issues/1381)
Answer: If you are trying to test your meteor app locally (dev mode) or you want to deploy your app to the Meteor hosting, then just pass the file path as settings param:
meteor --settings settings.json

In case of running from bundle on your own server, then you need the environment variable.
Docs.
Comment: This is the clearest note I've seen about how to do this, thank you. Your note the "dev mode" means any time you're not using a compiled bundle was very helpful.


How to set up half minute hero to display gamepad buttons instead of keyboard keys?

Question: I use a gamepad, but the game is trying to be smart by displaying the keyboard keys as tooltips. How can this be changed?
Comment: Is your gamepad plugged in as you launch the game? (Is it the XBox gamepad?)
Comment: @badp Yes it is. Apparently I'm not the only one bugged by this: http://steamcommunity.com/app/214830/discussions/0/882961586639965092/. It's not an XBox gamepad, if that matters, it's a BigBen one (with the same button colors).
Answer: Go into controls, and click "Key Config". Then hit left/right at the top (settings)
Then hit "A".


Pipes freezing - different theories

Question: When water freezes in a pipe and the faucet is closed the water between the faucet and the frozen part cannot escape. This leads to increase in pressure as more water freezes. Because as long as there is still unfrozen water in the pipe the ice expands along the pipe. The increase in pressure is what causes a part of the pipe between the frozen part and the faucet to burst.
Now if we let the faucet trickle and assume the ice freezes in the same spot as when we do not let the faucet trickle the ice expanding from the frozen part will not be able to lead to a build up of pressure.
So apart from the fact that water freezes less likely when it is moving letting the faucet trickle should mainly be done to release the pressure between the faucet and the frozen part of the pipe. Note that ice can always expand in the other direction (to the water supply side) by displacing water.
Is this mechanism correct?
EDIT: Found this interesting video regarding pressure buildup
EDIT2 : After further reading, I came across the term latent heat. Because the evaporation of water cools the surrounding environment letting a faucet drip can actually accelerate freezing. But the freezing will then probably occurs first at the faucet itself. Given the above considerations, this could actually be beneficial in as such that there is no water trapped because the freezing starts at the faucet and gradually moves upstreams.
Comment: Not quite.  Letting water trickle brings in water from the source that is presumably warmer, replacing the water trickling out preventing freezing.
Comment: @GeorgeAnderson, the presumption is that the water freezes even with a trickle. That's certainly possible. See also any river in the north. The question is valid from a physics perspective, though maybe not from a home improvement one. There's no practical difference.
Comment: @isherwood Sure, agreed, that's why there are frozen waterfalls. I've had two bursted water pipes, they did a LOT of damage. My only point is that I believe it's a pretty common practice to leave faucets open to a trickle, not to just "keep water moving", but to replace it with presumably warmer water from the source. You need enough of a "trickle flow" to keep it from freezing, so I don't think we are disagreeing.
Comment: [Get into it.](https://datagenetics.com/blog/december22013/index.html)
Comment: Does this means that a toilet that likes to sporadically run won't suffer burst pipes? The only time that's good... They should invent a mechanism that would bleed valves under cold or high-pressure situations to prevent damage: a home BOP.
Comment: @dandavis Cold yes - if you can catch it in time - *but hard to do* because it is a very small difference between 33 degree flowing water and 31 degree frozen solid. High-pressure **will not help**, because the high pressure would be between the ice clog (e.g., where pipe is outside the house) and the valve - once that is detected, releasing the pressure won't do much - and in fact will result in a flood when the ice melts on its own and now the water runs freely. You could make a very complex mechanism **but heat wrap around the problem areas is a lot cheaper**.
Comment: Another option to avoid damage is an anti leak system that does close a valve near the incoming pipe location if any unusual water flow is detected - cracked pipes by freezing water, failing joints, pit corrosion etc.
Answer: Yes that is correct , the pipe generally burst where the water has not frozen. I once looked at burst tubes in a heat exchanger that was off-line. Individual exchanger tubes had 4  or 5 bursts each. The cold came in ( heat went out) through the baffles that were about two feet apart ; between the baffles there were bursts two feet apart where the water had not yet frozen.

Pipes freezing - different theories


Two different actions in one form

Question: I have a form with two different submit buttons.  One is to delete the corresponding row in the MySQL, which is done on the same page, the other is to save the row to another database, which is done on a separate page.  The delete action works fine, but I cannot figure out how to send the save form data to the other page without putting it in the "action" value.  I've tried JavaScript, but haven't had much luck.  It's a bit of a lengthy post, but I figure the more information I give, the easier it will be for a solution to be found.
Here's just the save submit button:
   echo "<input type=\"submit\" name=\"save\" value=\"Save\" onclick=\"this.form.action='publishmod.php'\">	";

Here's the form code (main page):
   echo "<form name=\"editmod\" method=\"post\">";
   echo "
";
   echo "".$row['id']."	";
   echo "
".$row['title']."
	";
   echo "
".$row['mod_url']."
	";
   echo "
".$row['developer']."
	";
   echo "
".$row['type']."
	";
   echo "
".$v162."$nbsp".$v164."$nbsp".$v172."
	";
   echo "
".$row['title'].",$nbsp".$row['developer']."
	";
   echo "<input type=\"submit\" name=\"save\" value=\"Save\" onclick=\"this.form.action='publishmod.php'\">	";
   echo "<input type=\"submit\" name=\"delete\" value=\"Delete\">	";
   echo "
";
   echo '<input type="hidden" name="id" value="', htmlspecialchars($row['title'], ENT_QUOTES, 'UTF-8'), '" />';
   echo '<input type="hidden" name="id" value="', htmlspecialchars($row['mod_url'], ENT_QUOTES, 'UTF-8'), '" />';
   echo '<input type="hidden" name="id" value="', htmlspecialchars($row['developer'], ENT_QUOTES, 'UTF-8'), '" />';
   echo '<input type="hidden" name="id" value="', htmlspecialchars($row['type'], ENT_QUOTES, 'UTF-8'), '" />';
   echo '<input type="hidden" name="id" value="', htmlspecialchars($row['id'], ENT_QUOTES, 'UTF-8'), '" />';
   echo "</form>";
   }

Publish code (page that the save action is supposed to redirect to):
Variable sanitation omitted for Stack Overflow purposes.
$name = $_GET['title'];
$desc = "Installation tutorial for '.$name.'";
$url = ereg("^[A-Za-z_\-]+$", $name) + ".php";
$keywords = "'.$name.', '.$dev.'";
$type = $_GET['type'];
$link = $_GET['mod_url'];
$dev = $_GET['developer'];
$id = $_GET['id'];

// Query

$savequery = "INSERT INTO search (title, description, url, keywords, type, mod_url, developer, v162, v164, v172)
            VALUES ('$name', '$desc', '$url', '$keywords', '$type', '$link', '$dev', '$v162', '$v164', '$v172')";

// Mod file creation

$file = ereg("^[A-Za-z_\-]+$", $name) + ".php";
$handle = fopen($file, 'w');
$data = '<?php
    $title = "'. $name. '";
    $keywords = "'. $name. ','. $developer. '";
    $description = "How to install '. $name. ' for PC and Mac.";

    include("templates/modheader.php");
    include("templates/modfooter.php");
    ?>';

$save = $dbsave->query($savequery) or die(mysqli_error($dbsave));

// Run creation

echo $save;
fwrite($handle, $data);
print " mod file created!";
fclose($handle);
?>

Comment: **Danger**: You are **vulnerable to [SQL injection attacks](http://bobby-tables.com/)** that you need to [defend](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php) yourself from.
Answer: Don't send it to another page. Use one page and branch with an if (or switch or whatever) statement.
e.g.
if (isset($_POST['save'])) {
    include('save.php');
} elseif (isset($_POST['delete'])) {
    include('delete.php');
} else {
    # logic for when the page is arrived at without the form being submitted with a submit button
}

As an aside. A <form> may not be the parent element of a
, and no element that may have a  as a child element may also have an <input> as a child element,  you will find some browsers will move elements around to make them acceptable in a way that is going to break your form. Write valid HTML.
Answer: I Think you should change type of submit to button for both delete and save and the use following jquery code:
$("#savebutton_id").onclick(function(){
$("#formid").attr('action','Your save Page');
$("#formid").submit();
});
$("#deletebutton_id").onclick(function(){
$("#formid").attr('action','Your delete Page');
$("#formid").submit();
});

Comment: Would you suggest I keep the delete action on the same page, but just handle both with this script?
Comment: It is ok with same page but just change type to button instead of submit.
Answer: you can send data to other pages using hyperlink
eg:Shoes
we can get the category variable in the next page by using
$_GET['category'];

Two different actions in one form


multiplicative order in field

Question: Let $\alpha$ be primitive element of GF(7). Then order of $\alpha$ is 6, i.e. $o(\alpha)=6$. Now we know that $\alpha^4$ is not equal to 1, and that  $o(\alpha^4)$ = $\frac{6}{gcd(6,4)}$. This also can be written as $gcd(6,4)=\frac{6}{o(\alpha^4)}$. This means that $\frac{6}{o(\alpha^4)}$ divides 4.
Now we can write $\alpha^4=\alpha^{Q\frac{6}{o(\alpha^4)}}=(\alpha^6)^{\frac{Q}{o(\alpha^4)}}=1$!!
I am getting this confusion. I might be making an error I am not aware of, it will help if you can look over this and point me in the right direction.
Comment: I took the liberty of adding the *cyclic-groups* tag, because that's what the question really is about (in a way). No need to add anything to Sammy Black's excellent answer that includes both the general formula for the order of an element in a cyclic group and the sample calculation verifying it in the present case.
Answer: You may be making this a bit more complicated than it actually is.  The primitive element $\alpha$ generates a cyclic group of order $6$:
$$
\big\langle \alpha \big\rangle = \big\{ 1, \alpha, \alpha^2, \ldots, \alpha^5 \big\} \cong C_6
$$
Now, you seem to be interested in the element $\beta = \alpha^4$ and its order in $GF(7)^\times$.  Look at some powers:
$$
\begin{align}
\beta^2 &= \left( \alpha^4 \right)^2 = \alpha^8 = \alpha^2 \\
\beta^3 &= \beta \beta^2 = \alpha^4 \alpha^2 = \alpha^6 = 1
\end{align}
$$
This explicit calculation shows that
$$
o(\beta) = o(\alpha^4) = 3.
$$
Alternatively, you can arrive at this order by applying the formula:
$$
o(\alpha^4) = \frac{6}{\gcd(6, 4)} = \frac{6}{2} = 3.
$$
Comment: I know that $o(\beta)=3$, but then I also see that I can write this element $\beta=(\alpha^6)^{\frac{Q}{3}}$ which makes it equal to $1.$ I would like to just confirm if the way I have used the theorem that $(x^a)^b=(x^b)^a$ is correct or it might just hold for integers and that is why I get a wrong answer that $\beta=1$.
Comment: I am not sure what you're asking.  What is $Q$?
Answer: Yes, there is a subtle error. I understand $GF(7)$ to be a field of size $7$, in which case it is isomorphic to $\mathbb{Z}_7$.
From Gallian's book, "Contemporary Abstract Algebra", page 75
$\textbf{Theorem 4.2}$ Let $a$ be an element of order $n$ in a group and lek $k$ be a positive integer. Then $<a^k>=<a^{gcd(n,k)}>$ and $|a^k|=\frac{n}{gcd(n,k)}$.
This does not mean the element $a^k$ equals $a^{gcd(n,k)}$, rather it means they generate the same subgroup. If we apply the theorem and do the substitutions correctly, we get
$k=6$ and $n=7$, hence
$$|a^4|=\frac{6}{gcd(6,4)}=3$$.
Therefore, because of your argument which is correct, the element $a^4 \in GF(7)$ seems sketchy. The reason is that there is no element of order $6$ in $\mathbb{Z_7}$. The order of any element divides the order of the group, but we have a group of prime order, so they all have order 1 or 7.
The argument is fine, the original assumption is false and hence the contradiction.
Comment: The finite field $GF(7)$ has underlying *additive* group $\Bbb{Z}_7$.  However, the *multiplicative* group of units $GF(7)^\times = GF(7) \setminus \{ 0 \}$ has $6$ elements, is cyclic, and its generator is the primitive element $\alpha$ that the OP mentions.

multiplicative order in field


Solving a polynomial equation

Question: Find a polynomial $f$ of degree at the most 2, such that for every polynomial $g$ we have
$$\int_0^1 f(x)g(x)\mathrm{d}x = g\left(\frac{1}{2}\right)$$
I started off my assuming $f(x) = a_0 + a_1x + a_2x^2$ and integrating for $g(x) = 1$, $x$ and $x^2$ and solving the equations for $a_i$ but it doesn't seem like the results I get satisfy the equation for all $g$. What am I doing wrong?
Comment: Are you sure you have the question right? Is it possible that it's only meant to work for $gh$ of degree at most 2?
Comment: @RoryDaulton the question ask such that for every polynomial $g$ so taking $g(x)=1$ doesn't satisfy the equation.
Comment: Yes, you are right, I misread the question. I was wrong and I'll delete my comments.
Comment: @Sabyasachi by method you have mentioned, I got $a_0=\frac {-3}2, a_1=15$ and $a_2= -15$. Where does it fell according to your calculations? I mean for what $g$ s?
Comment: $f(x)=\frac {-3}2 +15x-15x^2$ seems to be the answer. but not sure.
Answer: There is no solution. Polynomials are a dense subset of $L^2(0,1)$ or $C^0(0,1)$. The only working choice is $f(x)=\delta(x-1/2)$, but it is a distribution, not a polynomial.
Comment: I suspected that there was no solution, so either it was a trick question on the assignment, or some kind of a typo.
Answer: Note that your $f$ has to satisfy the first $3$ equations you got hence it has to satisfy $a_0=-\frac{3}{2},a_1=15,a_2=-15$ but since you found a counter example that means that $f(x)=\frac{-3}{2}+15x-15x^2$ doesn't satisfy the condition that means that no polynomial satisfy the condition.By the way the polynomial I used for the 4th equation was $g(x)=x^4$.
Answer: We can reduce the problem to the case that $g(x) = x^k$ for $k \in \mathbb{N}$.  We find that if $f(x) = a_0 + a_1 x + a_2x^2$, then
$$ \int_0^1 f(x)g(x) dx = g(1/2) ~~ \textrm{ implies } ~~ {a_0 \over k+1} + {a_1 \over k+2} + {a_2 \over k+3} = {1 \over 2^k} ~~ \forall k \in \mathbb{N}.$$
Writing this equation for each of $k = 0,1,2$ we get three equations in three variables, which can be expressed as the augmented matrix
$$ \left[ \begin{array}{ccc|c} 1 & 1/2 & 1/3 & 1 \\ 1/2 & 1/3 & 1/4 & 1/2 \\ 1/3 & 1/4 & 1/5 & 1/4 \end{array} \right].$$
Reducing this we find that if $f$ exists, its coefficients must be
$$ a_0 = -3/2, ~~ a_1 = 15, ~~ a_2 = -15. $$
Plugging these back into the first display,
$$ {-3/2 \over k+1 } + {15 \over k+2} - { 15 \over k+3 } = {1 \over 2^k} $$
which simplifies to
$$ 2^k(-1.5k^2 + 7.5k + 6) - k^3 -6k^2-11k-6 = 0 $$
and we need this equation to hold for all nonnegative $k$.  It does connivingly hold for $k = 3$ as well, but for no other choices of $k$.

Solving a polynomial equation


$I$ an ideal $\implies f(I)=I$?

Question: Let $R_1$ and $R_2$ be rings and suppose there is an ideal $I$ such that $I\subset R_1$ and $I\subset R_ 2$.
Suppose $f:R_1\to R_2$ is an homomorphism.
If $x\in I$, is it true $f(x)=x$? If don't, maybe we can have at least $f(I)=I$?
I couldn't prove it, I think is not true, someone knows some counter example?
Thanks in advance
Comment: Hint: A special case would be that if $I$ is an ideal of a ring $R$ and $f: R\to R$ is a homomorphism, then $f(I) = I$.
Comment: Dear @TobiasKildetoft if $f:R_1\to R_2$ is an isomorphism can we have $f(x)=x$, if $x\in I$?
Comment: We can, but we need not. See my answer.
Comment: I'm sorry, I meant if $f:R_1\to R_2$ is an isomorphism we _necessarily_ have $f(x)=x,if \in I$?
Comment: As I said, that need not be the case, as my answer shows.
Comment: @TobiasKildetoft I"m working on your answer, thanks
Answer: Here is a more fleshed-out version of my comment: As I mentioned there, a special case would be that then any ideal of a ring would be preserved under endomorphisms of the ring.
To find an example where this fails, take for example any ring $R$ and consider $R\times R$. This has a nice automorphism which switches the two factors. Can you find an ideal not preserved by this automorphism?

$I$ an ideal $\implies f(I)=I$?


Can shard key in MemSQL have NULLs?

Question: What are the rules regarding shard key and key for clustered columnStore ?
I need to make a column as Shard key and also for Clustered columnStore, but it may contain Nulls
What will be the impact of keeping a Nullable column as Shard key ?
I have already tested out the data load using this column and on a high-level, everything looks good for the first batch, but will it break anything while writing or reading down the line ?
<code>CREATE TABLE test (
name varchar(25) DEFAULT NULL,
ID int(11) DEFAULT NULL,
update_date date DEFAULT NULL,
SHARD KEY (update_date) USING CLUSTERED COLUMNSTORE
)
</code>
Answer: NULL values are allowed in shard keys and columnstore keys, and function like any other value - so if you define shard key on a column with some NULLs then all null values will be placed on the same partition.

Can shard key in MemSQL have NULLs?


Is there such a thing as a smaller vent cap than the 4"

Question: I need a vent cap to fit without touching an adjacent vent pipe i.e.vent cap cover needs to be < 4 1/2 " ( possibly might work <5" ) to fit into opening to exhaust air outside from a bathroom.
Comment: Unclear what you are asking. Perhaps a photo of the vent where it exits the house would help.
Answer: How about using an off-set vent cap like this: Sears.com offset vent
Or extend and vent to the side: Whirlpool 5-in x 4-in Galvanized Steel Round Duct Elbow
Answer: 3" is a less-common but still available size.
Here's a few options in 3"

A [dryer vent cap][1]
A [misc vent][2] cap
[Another][3]

Caution if constricting a 4" fan outlet to a 3" vent, the flow restriction can cause the fan to encounter too much resistance and burn up.
[1]: https://seiho.com/product/cfx/cfx.html
[2]: https://seiho.com/product/sfx/sfx.html
[3]: https://seiho.com/product/kx/kx.html


Is ratio of members of two progression increases?

Question: I have two progressions:
$$\begin{align}P_1&: xy, xy + (x+2)(y+2), xy + (x+2)(y+2) + (x+4)(y+4),\dots,  \sum_1^i (x+2(j-1))(y+2(j-1))\end{align}$$
$$\begin{align}P_2&: (x+2)(y+2),  (x+4)(y+4),\dots,   (x + 2i)(y+2i)\end{align}$$
$x, y$ are natural numbers.
I just want to know if the ratio $P_1(i):P_2(i)$ is an increasing function. It appears to be. But how to prove it?
I would like to add that $x > 3$, $y > 3$ are odd numbers.
Comment: It depends on the choice of $x$ and $y$
Comment: Care to elaborate? I do not see, how. It appears, it is always increasing in my experiments.Can you give an example, when it is not increasing?
Comment: For $x=2,y=3$ I got $0.0733333, 0.0553288, 0.0446208, 0.0374708, 0.0323389, 0.0284676, 0.0254389, 0.0230022, 0.0209979, 0.0193195$
Comment: Thank you. What do you think, is it possible to find x, y where the ratio not increases if x, y are odd numbers x >3 y > 3? It would be great to know.
Comment: I calculated for $x=2, y=3$, and I have increasing sequence:0.3000000 0.6190476 0.9444444 1.2727273 1.6025641 1.9333333 2.2647059 2.5964912
 2.9285714 3.2608696 3.5933333 3.9259259 4.2586207 4.5913978 4.9242424 5.2571429 5.5900901
Answer: Term $k$ of $P_1$ is
$$[x+2(k-1)][y+2(k-1)]=xy+2(k-1)(x+y)+4(k-1)^2$$
Summing by terms from $k=1..n$ we get
$$P_1(n)=nxy+n(n-1)(x+y)+\frac23(2n-1)n(n-1)$$
Meanwhile
$$P_2(n)=(x+2n)(y+2n)=xy+2n(x+y)+4n^2$$
Therefore as $n \to \infty$ then
$$\frac{P_1(n)}{P_2(n)} \to \frac14(x+y)+\frac13 n$$
which continues increasing indefinitely for all values of $x, y$.


How to remove window title bar without maximizing?

Question: I want to remove title bar in VLC MEDIA PLAYER without maximized.
Is there anyway to solve this?
I am googling for 5 hours but I can't find the answer.
Comment: Hello. this would be a good question to ask at VLC support. Nothing to do with the Ubuntu OS. Sorry.
Comment: @david thanks T^T...
Comment: Did you get a different answer somewhere else? Care to share.
Answer: There is no obvious way to control window decorations (i.e., display of window border and title), except perhaps with the Compiz window manager.
You could still do this with devilspie or devilspie2. These are small daemons that monitor the creation of windows, and do something with windows that match rules you created. This may work only on systems running on Xorg. Ubuntu 21.10 and later by default run on Wayland, although one still can switch to the traditional Xorg display server.
For example, following configuration file, ~/.config/devilspie2/vlc.lu will cause a window with the title "VCL media player" to be undecorated:
if (get_window_name() == "VLC media player") then
    undecorate_window();
end

An undecorated window still can be moved if you drag the window while holding the "Windows" key. In standard Ubuntu, this is Super, in other desktop environments, it is sometimes Alt left.


Does $\sum_{n=1}^{\infty} (\frac{1}{n}-\frac{1}{\sqrt{n(n+1)}})$ converge

Question: $$\sum_{n=1}^{\infty} \left ( \frac{1}{n}-\frac{1}{\sqrt{n(n+1)}}\right )=\sum_{n=1}^{\infty} \left ( \frac{\sqrt{n(n+1)}-n}{n\sqrt{n(n+1)}}\right )$$
By ratio test I get $$ \lim_{n\to \infty} \frac{\frac{\sqrt{n(n+1)}-n}{n\sqrt{n(n+1)}}}{\frac{1}{n}}=\frac{0}{0}$$
So i can't conclude anything. I tried comparison tests, but i get $\le$ something divergent.
Comment: Surely you could do a better attempt at the limit?  Flip those fractions and L'hospital's rule like pancakes on a stove.
Comment: Look in your book for the material on "indeterminate forms".
Answer: \begin{align*}
\sum_{n=1}^{\infty}\frac{\sqrt{n(n+1)}-n}{n\sqrt{n(n+1)}}
&=\sum_{n=1}^{\infty}\frac{(\sqrt{n(n+1)}-n)(\sqrt{n(n+1)}+n)}{n\sqrt{n(n+1)}(\sqrt{n(n+1)}+n)}\\
&=\sum_{n=1}^{\infty}\frac1{\sqrt{n(n+1)}(\sqrt{n(n+1)}+n)}\\
&=\sum_{n=1}^{\infty}\frac1{n(n+1)+n\sqrt{n(n+1)}}\\
&\le\sum_{n=1}^{\infty}\frac1{n^2}.
\end{align*}
Comment: Brilliant. thanks
Comment: @RushThaMan You're welcome!
Answer: Use Taylor's expansion at order $1$:
\begin{align*}\frac1n-\frac1{\sqrt{n(n+1)}}&=\frac1n\Biggl(1-\frac1{\sqrt{1+\frac1n}}\Biggr)=\frac1n\biggl(1-1+\frac1{2n}+o\Bigl(\frac1n\Bigr)\biggr)\\ &=\frac1{2n^2}+o\biggl(\frac1{n^2}\biggr)\sim_\infty\frac1{2n^2} \end{align*}
and the latter converges.
Answer: Compare to $$\sum_{n=1}^\infty\left(\frac1n-\frac1{\sqrt{n\cdot n}}\right)$$ on one side and $$\sum_{n=1}^\infty\left(\frac1n-\frac1{\sqrt{(n+1)(n+1)}}\right)$$on the other.
Answer: You don't need ratio test or a clever bound for the general term... Like most problems on MSE, a simple asymptotic expansion fits the bill.
$$\frac{1}{n}-\frac{1}{\sqrt{n(n+1)}} = \frac{1}{2n^2} + o\left(\frac{1}{n^2}\right)$$


req.user data not displayed in the view

Question: I have an express server with passport-local stategy, passport-local and passport-local-mongoose also installed.I want to access current user model as json to read and write data into it. My headache is that object doesn't want to display the data inside my view. It's loading with no errors and I cannot understand what's happening. Please help me!
Here is my express config:
var express = require('express'),
app = express(),
morgan = require('morgan'),
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser'),
expressSession = require('express-session'),
hash = require('bcrypt-nodejs'),
mongoose = require('mongoose'),
path = require('path'),
passport = require('passport'),
localStrategy = require('passport-local').Strategy,
port = process.env.PORT || 8080,
User = require('./app/models/user'),
routes = require('./app/routes/api');

mongoose.connect('mongodb://localhost:27017/dashboard');
app.use(express.static(__dirname + '/src'));
app.use(morgan('dev'));

app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(require('express-session')({
secret: 'keyboard kat',
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());

passport.use(new localStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

app.use(function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET', 'POST');
res.header('Access-Control-Allow-Methods', 'X-Requested-With, content-          type, Authorization');
next();
});

app.use('/user', routes);

app.get('/', function (req, res) {
res.sendFile(path.join(__dirname + '/src/views', 'index.html'));
});

app.use(function (req, res, next) {
var err = new Error('not found :(');
err.status = 404;
next(err);
});

app.use(function (err, req, res) {
res.status(err.status || 500);
res.end(JSON.stringify({
    message: err.message,
    error: {}
}));
});

app.listen(port);
console.log('Magic happens on port ' + port);

And the route which I use to pull the data:
router.get('/data', function (req, res) {
res.send(req.user);
});

Сhrome dev tools returns correct object:
Dev Tools
Angular service:
angular.module('main')
.factory('MenuService', function ($http) {

    function getData() {
        $http.get('/user/data')
            .success(function (data) {
                return data;
            });
    }

    return {
        info: getData
    }
});

Controller:
angular.module('main')
.controller('menuController', function ($mdSidenav, MenuService) {
    var vm = this;

    vm.toggleMenu = function () {
        $mdSidenav('menu').toggle();
    };

    vm.info = MenuService.info();

});

And finaly the view:
<md-toolbar layout="row" ng-controller="menuController as menu">

    <md-button class="md-icon-button md-primary" ng-click="menu.toggleMenu()" aria-label="open menu">
        <md-icon md-svg-icon="../../assets/img/hmg.svg"></md-icon>
    </md-button>

Dashboard

{{menu.info.name}}

</md-toolbar>

And nothing happens :( No view, no errors, absolutely nothing:
Browser
Answer: you can write this statement in async call.
return vm;

your vm is nothing but this object.You dont need to return it from controller.
Your controller as syntax is automatically bind this object to scope object.
Please remove it.
Let the remain statement as it is.
MenuService.info().then(function(resp){
       console.log(resp); //here is the response
       vm.info = resp.data;
    }, function(err){
       //todo when no data arrived
    });

Answer: You need to return a promise
 when dealing with async calls or use pub-sub pattern for telling that your data arrived.
What is happening is that the  getData  function gets called, in the background fetches the data, but it is not returned to the the caller of the getData caller. Why? Because inside getData nothing is returned. Something needs to be returned.
Here is a solution returning the promise.
Update : Sorry, sometimes I forgot that $http returns a resp object, which has the data. Updated the code according to that.
So in your service :
angular.module('main')
.factory('MenuService', function ($http) {

    function getData() {
        return $http.get('/user/data'); //no preprocessing just returning the result of the http call
    }

    return {
        info: getData
    }
});

And in your controller
angular.module('main')
.controller('menuController', function ($mdSidenav, MenuService) {
    var vm = this;

    vm.toggleMenu = function () {
        $mdSidenav('menu').toggle();
    };
    //todo this will be called whenever menuController gets initiated
    //better to put into user action or run only one time...
    MenuService.info().then(function(resp){
       console.log(resp); //here is the response
       vm.info = resp.data;
    }, function(err){
       //todo when no data arrived
    });

    return vm;
});

Also .success and .error are deprecated according to docs

The $http legacy promise methods success and error have been deprecated. Use the standard then method instead. If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error.
Comment: Thank you for your answer, @eenagy! I made as you wrote, but still nothing happens :(
Comment: here:[Postman](http://i.imgur.com/sqhgtHj.jpg?1) and [Browser](http://i.imgur.com/LwZZ11B.jpg?1)
Comment: Thank you! I forgot to write 'vm.info = resp.data' insted of 'vm.info = data' :) You just saved my head from blowing :)

req.user data not displayed in the view


Subversion versionate remote code

Question: I have a svn server already set up. I need to place project code onto another machine in a different subnet than svn's server.
It's like that: There's this server set up with subversion, holding a lot of codes from many projects. I need to place the code in a different machine than svn's server, to allow access to an LDAP server hosted in a different subnet. I used a trick before by checking out the code onto this machine every time I submitted new code to svn server's machine. My question is if there's any way of making svn manage the code remotely onto this machine rather than make a local dir repository on itself.
Thanks
Comment: Welcome to Stack Overflow! Unfortunately, it's difficult to understand what you are asking for. Can you elaborate a bit, perhaps show us what you tried?
Comment: If you really want to mirror the **repository**, not just a working copy, look at `svnsync`. However, you will still need a working network connection between the two. Also note, that mirrors are read-only.
Comment: I don't quite understand what the different subnet has to do with it. Do you want to check out the code to the LDAP server each time a commit is made?
Comment: I want to make a mirror repository that automatically commits any changes done to original onto another machine that will serve the code. This second machine is the only one able to access the LDAP server because it is in another subnet than svn server's
Comment: Thanks, that's just what I need. Now I'll have to make svnsync work like a service, syncing every change done on the original repository automatically..
Comment: Ok, so I convertet my comment into an answer, and added some ways to automate the sync.
Answer: If you really want to mirror the repository, not just a working copy, look at svnsync. However, you will still need a working network connection between the two. Also note, that mirrors are read-only.
There are many ways to trigger the sync:

The usual way is to call it from a post-commit hook on the master. If you call the sync normally, i.e. synchronously, users may notice that the commit takes longer as the have to wait until the sync has finished. This is probably not a big problem if you have a fast connection, however, if you are synching to a remote site, or to multiple mirrors, it can be rather annoying.
To avoid this delay, you can perform the sync asynchronously. On Unix, this is as simple as appending a & to the command. On Windows, I couldn't get this to work.
Alternatively, you can just run a small script on either the master or the slave, that runs synsync every n seconds. This will cause some additional network load due to unnecessary syncs, and the slave will update a bit slower, but this might be acceptable in your case.

Subversion versionate remote code


Many to one search query

Question: I am facing one problem regarding Many to One relationship in JPA. The problem I am getting at this moment is to get data by using where clause.
Skills class:
    @Id
    private long skillsID;
    @Basic
    private String longDescription;
    @Basic
    private String shortDescription;
    @Basic
    private String colOrder;
    @Basic
    private String isActive;
    @Basic
    private String changeDate;
    @ManyToOne(fetch=FetchType.EAGER)
    private Category category;

Second Entity is:
Category  class:
    @Id
    private long categoryID;
    @Basic
    private String name;
    @Basic
    private String colOrder;
    @Basic
    private String isActive;
    @Basic
    private String changedDate;
    @OneToMany(mappedBy = "category")
    private Collection<Skills> skills;

So in JPA, when i excute following code, it throw me exception like:
java.lang.IllegalArgumentException: An exception occurred while creating a query in EntityManager:

Exception Description: Problem compiling [SELECT s.longDescription  from Skills s, Category c  where s.categoryID =  c.categoryID].

[57, 69] The state field path 's.categoryID' cannot be resolved to a valid type.

JPA Code is:
Query q = em .createQuery("SELECT s.longDescription  from Skills s, Category c "+
"where s.categoryID =  c.categoryID");

So, how can I get data from Skills to Category based on the foreign key?
Comment: There is no need to SHOUT at us.
Answer: There is no field categoryID in Skills entity.
Just use it's category field in the Query:
Query q = em .createQuery("SELECT s.longDescription from Skills s, Category c " +
                          "WHERE s.category =  c");

Many to one search query


How can I tell if an element reference does exist in blazor

Question: If an element is hidden in first render (for example the element is in an if statement scope which has evaluated as false, so won't get rendered), and some event makes it appear (if statement evaluate as true) the inner element reference gets updated after render. This works absolutely fine.
But in case the opposite event flow (first is true, than gets hidden by some event), the element reference does not get updated after render, still shows the original id instead of null or empty string. In this case if I call JsInterop with that element reference, it would give an error that element does not exists (which is obviously true). The problem is that the element reference still has the former id, it didn't get changed after render.
The question is how can I tell if an element is visible (rendered, existing) or not?
Answer: Blazor does not destroy the ElementReference object. It is persisted for further usage. But it is always populated with new data; that is the insurrected ElementReference object gets a new id. Thus you can always compare two consecutive values of the id
You can set an element reference to its default value:
elementRef = default(ElementReference);

This is equivalent to setting a reference object to null.
And you can check weather an element reference does exist like this;
if (EqualityComparer<ElementReference>.Default.Equals(elementRef,
                                             default(ElementReference)))
 {
     // Does not exist...
 }

Play with this code, and see that whatever you've said is wrong, unless I didn't get you.
@page "/"

@if (display)
{

Welcome to your new app.

}

<button @onclick="@(() => display = !display )">Toggle</button>
<button @onclick="ConsoleWrite">Console</button>
@code{
    private bool display = true;
    ElementReference elementRef;

    private void ConsoleWrite()
    {

        Console.WriteLine(elementRef.Id);

        if (!EqualityComparer<ElementReference>.Default.Equals(elementRef, default(ElementReference)))
        {
            Console.WriteLine("return false");
        }

        // Set the element reference to its default value
        elementRef = default(ElementReference);

        if (EqualityComparer<ElementReference>.Default.Equals(elementRef, default(ElementReference)))
        {
            Console.WriteLine("Return true after being set to its default value");
        }

        Console.WriteLine("elementRef.Id is null now" + elementRef.Id);

    }
}

Comment: I have tried this solution but unfortunately it doesn't work. The comparer results in false, and the elemenetRef id stays the same after the element has been hidden and the component got rerendered. Also I don't think that ElementReference can be destroyed since it is a struct, so it just gets overridden by the new value it should get before OnAfterRender() is called.
Comment: After startup, I pressed the console button, this is the output:
return false
Return true after being set to its default value
elementRef.Id is null now

this is after pressed the toggle then the console again:
blazor.webassembly.js:1
blazor.webassembly.js:1 Return true after being set to its default value
blazor.webassembly.js:1 elementRef.Id is null now
Comment: You explicitly set the element reference to its default value in ConsoleWrite method. If I restart, and press the toggle first (hide the text) than press the ConsoleWrite button, this is what I get:
return false
blazor.webassembly.js:1 Return true after being set to its default value
blazor.webassembly.js:1 elementRef.Id is null now

As you can see, if I do not set the element reference back to its default value "by hand" It does not get updated by the time OnAfterRender gets called.
Comment: Although this looks a workaround, but I can just set it back to default when I hide the element. I mark your answer as a good one, since it helped me, thanks a lot, but I still would be interested how to get it work out of the box... Thanks again!
Comment: I'd suggest you post an issue in github requesting the Blazor team to consider an out of the box feature...


When we pass a primary-key to UI, should not it be considered as mixing of 2 layers and a BAD practice?

Question: When we pass a Db identifier of any object to the UI (Let's say the PrimaryKey of an object in the url query string) aren't we mixing two layers (Persistnet layer and presentation layer) basically?
A data-base identifier sounds like a persistent layer related data only to me in a way, but when we 'have' to pass it on UI, isn't is a kind of BAD practice, where I have no idea what could be a better one though.
Is it in an exceptional case?
In short, how does the multi-tier architecture addresses this practice, passing a persistent layer data to UI?
Answer: It's a kind of a Leaky Abstraction everybody has to deal with.
There is more examples of persistance leaking to other layers as for example validating string lenght in domain layer because the lenght in the database column is set to some value. Another example could be exposing EF IQueryable from DAL to domain layer, because doing that the potenital database scheme is leaking to the domain layer.
So I think there is a acceptable compromise we could deal with and we can't eliminate leaky abstraction at all but we should work hard to have it at minimum. Exposing the ID to UI is a such acceptable compromise I deal with because it's simple and everybody understand it.
But if someone has a silver bullet I will be glad to hear about :)
Comment: +1 Nice explanation. Id is such a natural thing. Whenever you want to identify an object particularly you need and identifier of some sort. Having different id for presentation is overkill. So exposing persistent id AS READ ONLY to presentation tier can hardly be a BAD practice. However, setting persistence id from the presentation tier IS BAD practice.
Comment: Having said that, just because an item has a unique id doesn't mean that id has to come from a database or have been generated by the persistence layer.
Answer: The application user needs identifiers so she can correctly identify and interact with the data in the database. There's nothing bad about exposing the same identifiers in all layers of your solution. It would be hard to get anything useful done without them.
I expect you are really talking about surrogate keys rather than identifiers or "primary keys" in general. The question is, why did you need to create such a key in the first place? In principle, surrogate keys are lousy way to abstract your presentation tier from the data tier precisely because they create the sort of dilemma you are describing. The fact that people use them that way is usually due to: SQL's poor support for keys and general lack of data independence; a legacy of industry bad practices; inadequate development tools.


WWE '13 Universe Draft Mode

Question: I'm currently playing through the WWE 2013 Universe Mode for the XBOX 360. Draft Mode is enabled and I just played through one-year of playthrough for the "season" but haven't been presented with any sort of "Draft Day" or similar activities.
How do you start the Draft mode?
Answer: If you go to Edit Your Show (where you can change your title belts), at the bottom you can turn draft on and off.
Only two shows can draft at the same time. If you have three shows drafting then it won't work.
Comment: So if I make a third show, I'd have to disable RAW or Smackdown's Draft day?

WWE '13 Universe Draft Mode


How do I prevent randomly injected repeat characters in vim

Question: I sometimes encounter the following behaviour when editing large files in vim (it only appears to occur with > 500 lines).
When creating a sentence in insert mode occasionally a character will be repeated on screen (the v in visual):

Changing to normal mode and moving to the line below removes the errant letter (the v is removed):

The closest issue I could find while searching for a solution was described here - in my case setting the TERM variable to xterm-color (as opposed to the current setting of xterm-256color) was not effective.
Any suggestions for how to debug this would be appreciated.
Comment: I imagine it's more likely to be a plugin than vim itself. Try disabling some/all and see what happens?
Comment: Good call. In my case it was related to the [GitGutter plugin](https://github.com/airblade/vim-gitgutter) in combination with setting the `updatetime` interval to be too small.
Answer: As suggested by Holloway, it was related to a plugin.  In my case, when following the install instructions for GitGutter, I had reduced the updatetime to be 250ms.  I was able to resolve my issue by increasing this (set updatetime=2500).  The plugin is a little less responsive, but it's still extremely useful and I no longer get the repeat errors.