text:
Q: $\mathbb Z[\sqrt{-7}]$ and $\,\Bbb Z[\sqrt{1+4k}]$ are not UFDs I can prove this for $\sqrt{-5}$. What changes for the above question? Is it a similar proof? What would be the irreducible elements? Are they $1$ and $7$ ?

A: Hint $ $ It's simpler: UFDs are integrally closed, but $\,\Bbb Z[\sqrt{-7}]\,$ is not since $\,(1+\sqrt{-7})/2 $ is a root of $\,x^2-x+2.\,$ Said more simply it fails RRT = Rational Root Test, which holds true in any UFD.
Remark $ $ The RRT proof fails because some gcd it employs fails to exist in $\,\Bbb Z[\sqrt{-7}].\,$ Since gcds always exist in a UFD, we can use such gcd failure to prove rings are not UFDs. Let's use this to prove a more general case (for variety vs. traditional proofs).
Lemma $\  \Bbb Z[\sqrt d]$ is not a UFD if $\,\color{#0a0}{d\equiv 1\pmod{\!4}}\ $
Proof $ $ Assume it is a UFD. $\ \color{#0a0}{ww'}=(1\!+\!\sqrt d)(1\!-\!\sqrt d) = 1-d = \color{#0a0}{4k},\,\  \color{#c00}{w} = 2-w'\,$
therefore the gcd product $\ (2,\color{#0a0}w)(2,\color{#0a0}w') = (4,2w',2w,\color{#0a0}{4k}) = 2(2,w',\color{#c00}{w}) = 2(2,w')$
Cancelling $\,(2,w')\,\Rightarrow\, (2,w) = (2)\,\Rightarrow\, 2\mid w\,\Rightarrow\, w/2 = (1\!+\!\sqrt d)/2\in \Bbb Z[\sqrt d]\ \Rightarrow\!\Leftarrow$
Further $ $ if $\,w=\sqrt{c^2d}\,$ then $\,\Bbb Z[w]\,$ UFD $\,\Rightarrow\, c\mid 1,\,$ else $\,(w/c)^2 = d\,$ contra RRT (as above).
Alternatively by gcds $\,(c,w)^2 = (c^2,cw,c^2d) = c(c,w)\,\Rightarrow\, (c,w) = (c)\,\Rightarrow\, c\mid w\,$ in $\,\Bbb Z[w],\,$ i.e. $\,w/c\in \Bbb Z[w],\,$ so $\,c\mid 1\,$ in $\,\Bbb Z.$
Combining the two yields a purely gcd-based proof of the following well-known fact.
Theorem $\,\ \Bbb Z[\sqrt d]\, $ a UFD $\,\Rightarrow\, d\,$ squarefree and $\,d\not\equiv 1\pmod{\!4}$
Note $\ $ The proof of the theorem also works if we instead assume the ring is a PID and read the tuples as ideals vs. gcds [since the proof uses only laws common to both: $ $  distributive, associative, commutative, and $(a,b,bc) = (a,b)\,$]. Then it yields $\,(2,w)\,$ is noninvertible (so nonprincipal).

A: $$(1+\sqrt{-7})×(1-\sqrt{-7})=8=2×2×2.$$We show $2,1+\sqrt{-7},1-\sqrt{-7}$ are irreducibles.
So let $2=(a+\sqrt{-7}b)(c+\sqrt{-7}d)$ where $a,b,c,d \in \Bbb Z$, then taking norms $4=(a^2+7b^2)(c^2+7d^2)\implies b=d=0$ , since for $e,f\in \Bbb Z$ and  $f\not =0\implies e^2+7f^2\geq 7$. Also either $a$ or $c$ is $+1,-1$ as $2^2=4=(ac)^2$ and $\Bbb Z$ is a UFD i.e. either $a+\sqrt{-7}b$ or $c+\sqrt{-7}d$ unit.
Next, let $1+\sqrt{-7}=(a+\sqrt{-7}b)(c+\sqrt{-7}d)$ with $a,b,c,d\in \Bbb Z$. Again taking norms $8=(a^2+7b^2)(c^2+7d^2)\implies bd=0$ and both $b,d$ are not zero as $8$ has no integral square root. So without loss of generality assume $b=0$ and $d\not=0\implies 8=a^2(c^2+7d^2)$ . Note that $d$ must be $+1,-1$ , otherwise $c^2+7d^2\geq 28$. Also $c\not=0$ , as $7\not |8$. Hence $c$ must be $+1,-1$ otherwise $c^2+7d^2\geq 11$. Therefore $a=1,-1$ i.e. $a+\sqrt{-7}b$ is unit.
Similarly $1-\sqrt{-7}$ is irreducible.


text:
Q: How to extract frames using mencoder into specific directory? I can't seem to extract images into a specific directory.
The current command I am running is
mplayer -vo jpeg CustomLogoAni.mp4

Is it also possible to set the prefix for the file? Similar to ffmpeg   %d.jpg
When combining the images I run the command:
mencoder "mf://*.jpg" -ovc x264 -o output.avi

But it does not work.
Can anyone help?

A: You want -vo jpeg:outdir=/tmp/frames/ for output to a specific directory. I don't believe a prefix is possible.

A: This command works very well with ffmpeg. It doesn't matter if you want to convert a 1080p video and you have a slow computer, it converts it on its own pace.
ffmpeg -i "Katy Perry - Firework.mp4" image%08d.png

The %08d format seems to follow the common printf format. It generates a filename like image00000001.png.
ffmpeg can convert a whole video into images.
https://www.ffmpeg.org/ffmpeg.html#Video-and-Audio-grabbing
I couldn't find any info on the specific output directory, however it seems that on Windows you can navigate thru directories with '.'
ffmpeg -i "Katy Perry - Firework.mp4" ./temp/image%08d.png

redpajama_set_name: RedPajamaStackExchange


text:
Q: Use proc from inside another proc on TCL I'm trying to write a script in tcl to execute some analysis on VMD. First I'm creating an atom selection inside a procedure, then I'm trying to use it on another procedure.
The atom selection from VMD is implemented as a Tcl function. The data returned from atomselect is the name of the function to use. You can read more here.
When I create the atom selection outside a proc I can use it inside one just passing it as global. But now that I'm creating it inside one, when I try to use it it's just a string with the procedure name.
Resuming,
This works:
set all [atomselect top all]

proc test {} {
    global all
    $all num
}

test # Outuputs 7111

But this don't:
proc create {} {
    global all
    set all [atomselect top all]
}

proc test {} {
    global all
    $all num
}

create
test # Outputs -> invalid command name "atomselect1"

A: The problem is that the command created by the atomselect command is being deleted when the procedure returns. I strongly suspect that this is being done using a local variable deletion trace (on some variable that is otherwise unused). When atomselect is run in the global scope, there's no such natural deletion event (unless the global namespace is deleted, and that's an interpreter-ending event) so the trace never gets called and the created command persists indefinitely.
If we rewrite your create like this:
proc create {} {
    global all
    # Double quotes just because of the highlighting here
    set all [uplevel "#0" atomselect top all]
}

then the atomselect runs in the global scope (and the created command should persist) but all the rest of your code is in your procedure.
More properly, it should be done like this:
proc create {} {
    global all
    # Double quotes just because of the highlighting here
    set all [uplevel "#0" [list atomselect top all]]
    # Or this, to better show that we're talking about running a command:
    #   set all [uplevel "#0" [list \
    #       atomselect top all]]
}

This becomes far more important when you pass arguments with spaces (or other metasyntax characters) in, as list not only produces lists, but also substitution-free commands. (In fact, building commands and command fragments is absolutely one of the main uses of the list command; actual lists for ordinary data storage and manipulation tend to be made with some other command.)


text:
Q: Batch file progress percentage How can I show the progress of a long running operation in windows batch (cmd) file in percentage? Can you share some example code?

A: Here is how...
Note: This code is a slightly modified version of this answer.
@echo off

for /f %%a in ('copy /Z "%~dpf0" nul') do set "CR=%%a"

FOR /L %%n in (1,1,10) DO (
    call :show_progress %%n 10
    ping localhost -n 2 > nul
)

echo Done!
exit /b

:show_progress
setlocal EnableDelayedExpansion
set current_step=%1
set total_steps=%2
set /a "progress=(current_step * 100) / total_steps"

set /p ".=Progress: !progress!%%!CR!" <nul

if !progress! equ 100 echo.

exit /b

A: An example would be scanning a large file/database, showing progress instead of a blinking cursor, for ages!
set c=<no. of lines in file>
for /l %i in (1,1,%c%) do cls & set /p="Scanning for target ... "<nul & (set /a per=%i00/%c% >nul & echo !per!%)& ping 127.0.0.1 -n 2 > nul & REM when target found, send agents to greet
echo Complete.

The code in brackets () are for progress percentage.
Tested in Win 10 CmD>


text:
Q: Proofs by contradiction and set theory I'm having trouble understanding proofs by contradiction. I'm running things by memory and not by understanding what a contradiction is. I'd like to know what we're assuming and how to start. My understanding is that if we have $p \rightarrow q$ it suffices to show $p \land \lnot q$ and we starting with $\lnot q$.
Here are two examples I found:
$$(A-B) \cap (B-A)=\emptyset \\ \text and \\ |A \cup B| = |A| +|B| \rightarrow A\cap B =\emptyset   $$
Well, for this first one, I don't have an if/then statement so do I just assume that $(A-B) \cap (B-A)  \neq \emptyset$ ? I know that this set is the empty by simple logic rules.
For the second one, do I assume $p \land \lnot q$ for  $ \lnot (A\cap B =\emptyset)  $

A: Yes, to prove that $(A\setminus B)\cap(B\setminus A)=\varnothing$ for all $A$ and $B$, you can begin by assuming that $(A\setminus B)\cap(B\setminus A)\ne\varnothing$. Then let $x\in(A\setminus B)\cap(B\setminus A)$; clearly $x\in A\setminus B$, so $x\in A$. But also $x\in B\setminus A$, so $x\notin A$. This is a contradiction, so the original assumption that $(A\setminus B)\cap(B\setminus A)\ne\varnothing$ must be false. If $p$ is this assumption, and $q$ is $x\in A$, then the argument shows that $p\to(q\land\neg q)$. However
$$\Big(p\to(q\land\neg q)\Big)\to\neg p$$
is a tautology, so we infer $\neg p$, i.e., that $(A\setminus B)\cap(B\setminus A)=\varnothing$.
I would prove the second one by showing that
$$|A\cup B|=|A|+|B|-|A\cap B|\;;$$
it follows immediately that if $|A\cup B|=|A|+|B|$, then $|A\cap B|=0$ and hence that $A\cap B=\varnothing$.

A: To prove $p \rightarrow q$ by contradiction, one assumes to the contrary that $p \wedge \neg q$ holds and then tries to prove a contradiction, which is a statement of the form $r \wedge \neg r$, where $r$ is any formula you like.
Remark. We can compute the negation of $p \rightarrow q$ as follows:
$$\neg(p \rightarrow q) = \neg (\neg p \vee q) = \neg \neg p \wedge \neg q = p \wedge \neg q$$
So its negation really is $p \wedge \neg q$.


text:
Q: How to have editable table in ASP.net? I want to know is there any way to have editable table in ASP.net like in MVC.
I searched for it but could not find any tutorial or answer, what I found was an asp.net MVC editable table.
http://www.codeproject.com/Articles/165410/ASP-NET-MVC-Editable-DataTable-jQuery-DataTables-a
Is this also possible in simple asp.net?

A: It's called an editable DataGrid. Here's short tutorial: http://wiki.asp.net/page.aspx/1360/add-edit-update-delete-gridview/

A: If you're after the click label to make editable, then you just need to make Template Columns and bind the click event of the labels to make the row editable.


text:
Q: django: Issue with the url paths I need little help with how to redirect the link to the right url. I have one object that has 2 categories rents and sales. When the form is submitted I can successfully redirect the user to the right place but that is from the views --- return redirect(category +'/'+ listing_id) ---
Any trick how can I do the same from the HTML? Any help is appreciated!
urls.
path('rents/',rents, name = 'rents'),
path('rents/<int:pk>',RentView.as_view(), name = 'rent'),
path('sales/',sales, name = 'sales'),
path('sales/<int:pk>',SaleView.as_view(), name = 'sale'),

html:
First one has url localhost/dashboard/sales/1 . It should be localhost/sales/1, but I'm not sure how to remove that dashboard. Since the current page is dashboard.
<button class='btn-view'>View</button>

Second case: I have two categories: sales and rents. It seems to work if I leave it like this, but if there is a query from rents it will redirect the URL to sales.
<button class='btn-view'>View</button>

A: You are missing the / in href which is the cause of "dashboard" being added in the URL "localhost/dashboard/sales/1". To resolve the issue just add a / like following.
<button class='btn-view'>View</button>

For the second case you can use if template tag like following.
{% if contact.category == "sales" %}
    <button class='btn-view'>View</button>
{% else %}
    <button class='btn-view'>View</button>
{% endif %}

Or you can pass the name of URL from view based on category.
<button class='btn-view'>View</button>

Ensure that you pass "url_name" in the context from view function/method.


text:
Q: GIT LFS with Artifactory's multi-push replication feature We are in the process of evaluating GIT  LFS and Artifactory for storing large binary files. The local (main) Artifactory server will have multi-push replication enabled so our satellite offices servers (oversees) can receive the large files. However, if the git-lfs pointer file contains a "local" lfs-url endpoint, it will (presumably?) download the large file from our local Artifactory server and NOT the remote server at our satellite offices (thereby downloading the large files over the network, which is not desirable).
My question is; -how will GIT LFS know which Artifactory server to retrieve the large file from when a user performs a fetch or clone?
Our hope is for the remote servers to receive the large files (via Artifactory replication), AND for those files to be downloaded from the server at the remote (oversees) sites, and NOT from our local Artifactory server.

A: The git lfs pointer file does not include the lfs URL. It contains the object id and size, for example:
version https://git-lfs.github.com/spec/v1
oid sha256:ea824d6f0abeedf87be8951e4535c25d4d2955adfd435cfee956e72af6f258c9
size 4570923

When cloning the git project in your satellite sites, you can configure a lfs-url which points to the local Artifactory and lfs will pull the files from there.


text:
Q: Dúvidas sobre um problema de algoritmo
Eu não entendi o que a questão pede para fazer, alguém pode me dar uma luz?

A: Fala, Arashi!
Então, o exercício solicita que você escreva o retorno das 4 operações, concatenados com o texto "Resultado:" no início do texto.
Caso você tenha tido dúvida nas operações. O operador "\" representa a divisão inteira, então é uma divisão que pega só a parte inteira da resposta, descartando o que vem após a vírgula. E o operador "%" faz exatamente o contrário, ele faz a divisão mas fica com tudo que está após a vírgula.

A: O algoritmo essencialmente vai separar os dígitos do número que você entrou e exibir na tela. Como o tipo é inteiro, então ele irá truncar o valor das expressões. Exemplo: x = 5423

*

*x/1000 -> 5

*(x/100)%10 -> 4

*(x%100)/10 -> 2

*(x%10)%10 -> 3


text:
Q: What is this opamp circuit with diode? What is this circuit? It's from Yorkville powered sub nx720s input circuitry.

A: It's an acitve high pass filter (Sallen-Key topology), the diode is to clip large negative swings as Dave mentions.
Note for your circuit R1 = R124, R2 = R108, C1 = C69, C2 = C59 in the equations below.
The undamped natural frequency Fo is given by:

and the Q is given by:

So for this filter Fo is 27.43Hz, and the Q is 0.88.
This means the the output will be 20 * log10(0.88) = 1.1dB down at Fo.


text:
Q: UDP server not receiving data UDP server doesn't receive the data sent by UDP client program.I feel there is something wrong im doing in UDP Server program. Thanks.
   send_client_message = malloc(message_size);
  recv_client_message = malloc(message_size);
  sockaddr_in_length = sizeof(struct sockaddr_in);

  /* Create a datagram socket.*/
  server_sock = socket(AF_INET,SOCK_DGRAM,0);
  if (server_sock == return_error)
  {
    printf("Error in opening a datagram socket\n");
    exit(0);
  }
  printf("Host sock = %d\n",server_sock);

  /* Bind a local name to the socket.*/
  server_sockaddr_in.sin_family      = AF_INET;
  server_sockaddr_in.sin_port        = 4999;
  server_sockaddr_in.sin_addr.s_addr = INADDR_ANY;
  rc = bind(server_sock,(struct sockaddr *)&server_sockaddr_in,
            sockaddr_in_length);
  if (rc == return_error)
  {
    printf("Error in binding - \n");
    (void)close(server_sock);
    exit(0);
  }

  /* Get the server information, and print its data out.*/
  rc = getsockname(server_sock,(struct sockaddr *)&server_sockaddr_in,
                   &sockaddr_in_length);
  if (rc != return_error)
  {
    printf("Server Information\n");
    printf("--------------------------------\n");
    printf("Server sock       - %d\n",server_sock);
    printf("Server IP address - %x\n",
                                  server_sockaddr_in.sin_addr.s_addr);
    printf("Server port #     - %d\n\n",
                                  server_sockaddr_in.sin_port);
  }

  optval = message_size;
  optlen = sizeof(optval);
  rc = setsockopt(server_sock,SOL_SOCKET,SO_SNDBUF,(char *)&optval,
                  optlen);
  if (rc == return_error)
  {
    //printf("Error in setsockopt - %d\n",sock_errno());
    printf("Error in setsockopt - \n");
    (void)close(server_sock);
    exit(0);
  }

  printf(".... Ready for clients ....\n");

  /* Loop forever */
  for (;;)
  {
    /* Monitor incoming buffers.   */
    rc = recvfrom(server_sock,recv_client_message,message_size,0,
                  (struct sockaddr *)&client_sockaddr_in,
                  &sockaddr_in_length);

    printf("Recieved packet from %s: %d\nData: %s\n\n", inet_ntoa(client_sockaddr_in.sin_addr), ntohs(client_sockaddr_in.sin_port), recv_client_message);
   fflush(stdout);

    if (rc == return_error)
    {
      printf("Error in receiving message \n");
      break;
    }
   }  /* end of for(;;) */

  /* Return the socket back to the system and exit normally.  */
  rc = close(server_sock);
  if (rc == return_error)
  {
    printf("Error in closing the socket  \n");
    exit(0);
  }

  printf("Datagram server terminated\n");
  exit(0);
}

    for(i = 0; i < NPACK; i += 1) {
        printf("Sending packet %d\n", i);
        sprintf(buf, "This is packet %d\n", i);
        if(sendto(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, slen) == -1)
            diep("sendto()");
    }

    close(s);
    return 0;
}

A: server_sockaddr_in.sin_port        = 4999;

You likely want to htons that 4999.


text:
Q: How can I delete a folder with lots of subfolders fast? I have a folder with 266778 subfolders. How can I delete it?
I have tried
cd ~/.local/share/Trash/
sudo rm -rf *

but it takes much time. After 1 minute 25 seconds real time and 0.072 seconds user time it only deleted 2500 folders. This way, it will take over two hours to delete this folder.
Is there a faster way to delete this folder? Why is there such a big difference between user time and real time?
real    1m25.474s
user    0m0.072s
sys     0m28.142s

I use Linux 2.6.32 (Ubuntu 10.04.4 LTS).

A: It depends on your definition of fast. The answers already here give a good solution for actually removing the directories from the filesystem, but if what you really need is to free the directory name as fast as possible, a rename on the same filesystem is instantaneous:
{ mv directory directory.gone && rm -rf directory.gone; } &

Technically this is cheating since I haven't sped up the actual deletion, but practically it's very useful: I use this trick all the time so I don't have to wait for slow deletion operations.

A: rm -rf directory or rm -rf * of course is the fastest method unless your local rm implementation is broken.
Using find gives no advantages.
Whether this is fast or slow mainly depends on the filesystem and OS implementation. So the question seems to be inappropriate.
UFS and ZFS on Solaris are known to be very fast with this kind of task as both filesystem implementations include delayed background delete code that causes the unlink() and rmdir() calls to return fast even when the related object will take more time in total.
With the delayed background delete in the kernel, the directory updates can be done fast as well and this help to speed up the whole operation.

A: If your version of "find" implements the -delete sub-command, then you can try
find directory -delete

In this case:
find ~/.local/share/Trash/ -delete

Some commands, like rm, perform most of their work in the kernel.  In the file-system routines, to be exact.  Time spent performing system calls are accounted for in that way, so whilst your "rm" command runs for a long time, it doesn't do much work in user-land - the system calls performs most of the work.

A: This is only a partial answer, sheding light on the three values the command returns; quoted from the time(1) manpage:

(i) the elapsed real time between invocation and termination, (ii) the  user  CPU  time  (the  sum  of  the tms_utime and tms_cutime values in a struct tms as returned by times(2)), and (iii) the system CPU time (the sum of the tms_stime and tms_cstime values in a struct tms as returned by times(2))."

A: If you don't want to wait, and you want to avoid downtime, or you just need to get rid of the folder fast, queue the delete operation via mv on your next reboot. Also, the mv file operation is always faster than anything else, and no need to wait for blocking file-io operation, and continue what you are currently doing on that folder.
Just mv folder_to_be_deleted /tmp/folder_queue_for_deletion. Files in the /tmp directory will be deleted upon your next reboot.
Benchmark:
$ cat make_million_files.sh
#!/usr/bin/env bash

mkdir folder_to_be_deleted
for i in $(seq 0 1000000); do
  touch folder_to_be_deleted/$i;
done

$ ./make_million_files.sh
real    66m3.613s
user    5m47.507s
sys     61m15.432s

IO blocking operation
$ rm -rf folder_to_be_deleted
real    0m32.451s
user    0m2.086s
sys     0m25.094s

Non-IO blocking operation (Queue deletion on next reboot)
$ mv folder_to_be_deleted /tmp/folder_queue_for_deletion
real    0m0.012s
user    0m0.001s
sys     0m0.010s

In essence, the benefit is noticeable if you have multiple folders with lots of subfolders and you want to delete them fast, without downtime in your work, you might consider this solution, as it only takes 60 seconds to delete a million folders with lots of subfolders.
For 1000 folders with lots of subfolders, it would take ~1 hour of blocking IO using rm -rf, vs. 12 seconds via mv. And it would just take 60 seconds of boot time to delete everything. Finally, if you don't want to reboot, just mv the folder out of your way, and rm -rf it somewhere (other TTY session, etc.).


text:
Q: Secure key with PHP? I'm new to JS and PHP and currently have a key I need to use in JavaScript; but I don't want the user to be able to view the code and see it.
I tried putting the key in PHP and echoing it for the JS variable that holds the key, but that will just print it out anyways.
How can I use the key in JavaScript without allowing users to view the source?
EDIT: I'm using an API key to get data and use that data in functions.

A: Exactly what is it that you are trying to protect against?
Casual use of View Source?
A serious attack against your web app by a skilled user?
Packet sniffing at Starbucks?
Sorry, but I've deleted and rewritten this response a dozen times, with a dozen answers depending on your particular situation. Many different security concepts are at play here. The other posters are all correct, in that you can not conceal Javascript from the user. In fact, you cannot conceal anything that is sent to the user's browser. Obfuscation and sessions can help, but aren't perfect.
That does not mean you can't achieve your security goals.
But we all need to know what you are trying to achieve!


text:
Q: mocking the populate method using mockgoose for mongoose (mongodb library for node.js) is null Having trouble debugging an issue that mockgoose has for populating a property with fields set.  Yads mockgoose http://github.com/yads/Mockgoose fork solved the bug of making the populate option work, but if you specify fields it returns a null for the populated property.  I tried looking through the source code and stepping through with the debugger but not sure where to look.  I can see in the debugger that the populate option triggers a call to get the child element - and I see the call made returns the right child result with the correct fields, but when the parent element finally comes back it has the property to the child element set to null.
The query:
Posts.findById(foo).populate('createdBy', {fname:1, lname:1});

Incorrectly returns a post with post.createdBy = null.  Omitting the fields parameter of fame, lname, somehow makes it work again with post.createdBy returning the full object.
Following are some excerpts from the code - though I'm not sure those are the right places to look.
collections.js
this.find = function (conditions, options, callback) {
    var results;
    var models = db[name];
    if (!_.isEmpty(conditions)) {
        results = utils.findModelQuery(models, conditions);
    } else {
        results = utils.objectToArray(utils.cloneItems(models));
    }
    results = filter.applyOptions(options, results);

    if (results.name === 'MongoError') {
        callback(results);
    } else {
        var result = {
            toArray: function (callback) {
                callback(null, results);
            }
        };
        callback(null, result);
    }
};

util.js
function cloneItems(items) {
    var clones = {};
    for (var item in items) {
        clones[item] = cloneItem(items[item]);
    }
    return clones;
}

function cloneItem(item) {
    return _.cloneDeep(item, function(value) {
        // Do not clone items that are ObjectId objects as _.clone mangles them
        if (value instanceof ObjectId) {
            return new ObjectId(value.toString());
        }
    });
}

And here's a conversation about the issue
https://github.com/mccormicka/Mockgoose/pull/90


text:
Q: Why doesn't my custom Android permission work? My company develops two Android .apk files -- An app and a background service.  The app and service interact via Intents.  The service defines a new permission, which must be present in an app's manifest in order to use the service
<uses-permission android:name="com.mycompany.myservice.MY_PERMISSION"/>

This is a legacy app, built around API_10, and still using Eclipse. Everything seems to work fine except the service cannot be invoked (java runtime exception). The reason given for the exception, as shown in LogCat, is that the app doesn't have said permission -- but it's right there in the Manifest.
How can this be? What would cause such weird behavior? Is it perhaps something weird going on with Eclipse? All the other permission seem to work fine, it's this "custom" one.
I've read some places that install order is important, but I installed the service first, then the app, so this shouldn't be an issue.
Thanks.


text:
Q: dconf and terminal not showing the same information I am trying to install a very simple color Scheme into my terminal. This color scheme is coming from terminal.sexy.
Problem is, I can't list the profile in my terminal preferences, but it gets listed in dconf:
~/Downloads/debian-config$ dconf list /org/gnome/terminal/legacy/profiles:/
:terminal-dot-sexy/
list
:terminal-dot-sexy2/
:45e4f4be-47c4-427f-abb8-993a3935c560/
default

But when I go in my terminal preferences, I only get one profile, that is not even corresponding to one listed before:
b1dcc9dd-5262-4d8d-a863-c897e6d979b9

I am using Debian 8 Jessie with Gnome Terminal 3.14.1.
I tried to close terminal and reopen it, logout/login and to restart completely my computer but nothing changes.
PS:
When I try with gsettings, I get the default profile with the correct ID. But nothing else...
Where should I look to solve my problem?
Thank you very much for your help, and don't hesitate to ask me for more information on my configuration :)
EDIT: I tried to investigate a little bit more.
When I launch my bash script that is supposed to edit my configuration by himself, I can see both in dconf and gsettings my new profile. I still don't see it in my terminal preferences panel.
But as soon as I create a new profile in my preferences panel, it overrides every change in gsettings, but not in dconf.


text:
Q: O que são Assignment Expressions do Python 3.8? As assignment expressions estão definidas na PEP 572 que foi aprovada para ser implementada na versão 3.8 do Python.

*

*Mas o que são as assignment expressions e quando deverão ser utilizadas?

*Que tipo de problema sua implementação busca resolver?

*Por que sua implementação causou polêmica na comunidade Python? Ela vai contra os "princípios" da linguagem?

A: A resposta vai por níveis.

*

*Conceito simples:

*Conceito completo:

*Exemplo:

*Como usar:

*Referencias:

Conceito simples:
Podemos dizer de forma " "simples" " que é definir uma variável e passá-la como valor ao mesmo tempo.
Ex.:
# $ entrada do código
# > saída do código

$ a = 1
>
$ a
> 1

Então o que você pode passar a fazer é juntar as duas coisas em uma única linha. Ficando assim:
$ a := 1    # Você definiu a variável e ao mesmo tempo ela passa o valor adiante.
> 1

Conceito completo:
Abstract:
É uma proposta para definir variáveis como uma expressão.( NAME := expr )

*

*adicionada uma nova exceção "TargetScopeError".

Motivação:
Nomear o resultado de uma expressão é uma parte importante da programação, assim permitindo ser usado no lugar de uma longa expressão e permitindo o reúso.
...
a = foo(x)
baa(a)
cee(a)
...

Agora pode ser :
...
baa(a:=foo(x))
cee(a)
...

A real importância:
Não vou citar directamente aqui pois é grande e é bom que se leia tudo, o link está no fim da resposta. Se alguém quiser eu resumo e altero aqui.
E sim teve discussões se isso é pythônico.
Sintaxe:
Muitos contextos arbitrários em que expressões Python podem ser usadas. Isto é a forma de NAME := expr onde a expr é uma expressão Python válida como uma tupla sem parênteses e NAME é o identificador.
$ a = 3,1
$ type(a)
> <class 'tuple'>

regex
if (match := pattern.search(data)) is not None:
    # Do something with match

Loop não pode ser facilmente reescrito usando 2 argumentos iterativos.
while chunk := file.read(8192):
   process(chunk)

Analizar valor é caro computacionalmente
[y := f(x), y**2, y**3]

Compartilha a sub-expressão entre um filtro e uma "saída".
filtered_data = [y for x in data if (y := f(x)) is not None]

Casos excepcionais: (Inválidos e válidos porem não recomendados.)
Amanhã posto com calma, por causa do meu horário, porém tem no link  referencia do PEP 572 no final da resposta. :)
Se for usar recomendo a leitura.

Exemplo:
Caso alguém queira, crio um exemplo mais complexo, porém vou deixar um que achei bem simples porem demostrativo que está na própria PEP.
# Computar uma lista de somas parciais e retornar o total
total = 0
partial_sums = [total := total + v for v in values]
print("Total:", total)

# Legal né :)

Referência:
PEP 572 -- Assignment Expressions
Exemplo de uso - VIDEO - EN


text:
Q: Get Frame at half of video with opencv is there a way to get a frame form opencv, but around half of the video (for example if the video is 10 minutes I want to save a frame at 5:00 minutes). I have already seen something on the internet but everyone just goes ahead frame by frame. Thank you for your help

A: I believe you are looking for something like this:
import cv2

# Read the Video (Change the filename as per your file)
cap = cv2.VideoCapture("video.mp4")

# Get the total number of frames
length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
half_point = length//2 # Approximately half if number of frames are odd

# Set the reader to the given frame number (half_point)
cap.set(cv2.CAP_PROP_POS_FRAMES, half_point)

# Read the frame
ret, frame = cap.read()

# Release the file pointer
cap.release()

And you should get the half-point frame in the variable frame.


text:
Q: How to create custom calendar with event management? My Requirement:-
I am trying to make an app which have only calendar functionality, when user opens the app, calendar opens same like Google calendar. I receive events from web service and i have to show those events according to the date in calendar. Now if their is any event on any date than their should be a color block for event time, and if multiple events are there, than we have to show multiple color blocks each for one events.
I am here for a good piece of advice. Can i do this by default libraries or API's? because I have read android API's Calendar, CalendarView, calendar-provider, CalendarContract.  But no one tells that how can we show events in your own calendar.
So I am trying it with custom calendar. I am able to create custom calendar by using Gridview.
.
I want it to look like this with events
.
BTW My minimum Android support is android v4.0

A:
Can i do this by default libraries or API's?

No. CalendarView is more of an alternative date picker than DatePicker.
ExtendedCalendarView looks like it is more in line with what you are seeking.


text:
Q: Is it bad to do more than one story at a time in scrum? Scrum's definition says that it should be done one story at a time.
But, if the team is big enough (say 6+), there are some times where taking just one story is kind of questionable, and it is even more if there are several small stories.
So, sometimes in the team I'm currently working with, we might tackle two stories more often than not. Is this a bad thing?

A: No it is not bad. During planning meeting team commits to user stories which will be delivered in upcoming sprint. The sprint is safe zone for the team and team decides how to deliver user stories. If it is not possible for all team members to work on tasks from the most important user story (by business priority) it is obvious that they should work on another user story as well to take full advantage of their time capacity.
Btw. where did you find that team should not work on more then one user story at time? You can look on the problem as Scrum master. If team works only on one user story at time and somebody doesn't have any other task to do he is stuck = impediment. How do you solve it as Scrum master? You will remove the impediment by removing the rule so that developer is not stuck any more and can continue on another user story.
I think this rule was probably mentioned as team member should not work on more then one user story at time (except scenarios where work on current user story is blocked by another impediment). That makes sense because context switching in human brain is expensive and disruptive. Also it makes Scrum process much better controlled because you have limited set of user stories in progress. This corresponds with Work in progress limits in Kanban.

A: There is no such restriction. If the stories are independed of each other , or if the dependeny between them is minimal you can certainly do them in parallel. Of course one member will only work on one story at a time and ideally should only move to the next one after a story is finished. But in case you finish 80% of a story and the remaining 20% is waiting for someone else, you can definetly move on, as long as you can finish coding and testing within the same sprint.

A: There is no rule in Scrum that specifies how much work the team are allowed to take on at the same time. It's your job to figure out what suits your team best.
Scrum limits work in progress (WIP) over the whole sprint. This means you commit to deliver, for instance, 20 work items this sprint. It doesn't matter how many of them you are working on concurrently as long as you deliver on your commitment.
Compare this to Kanban which also limits WIP, but per workflow state. For instance, the WIP limit for "testing" is 3 for which means that no more than 3 items are allowed in the testing phase at the same time.


text:
Q: JQueryUI changing order of LIs not reflected in DOM on JQuery .each() I have a page with two asp:BulletedLists, an available items list and a selected items list, one is populated the other is not, and I can drag and drop LIs between them no problem. I am using two hidden fields to persist the contents of each list, when I do a postback, what is in each list (reading from the persisting hidden fields) is correct, however not in the order that is selected by the user, items are moved between each list and in the UI they do appear to be in the order that the user defines on the page, however this change of ordering is not reflected in the DOM when I am looping through the .each() method.
My code...
    $(function () {
        $("#<%= blAvailableDocuments.ClientID %>").sortable();
        $("#<%= blAvailableDocuments.ClientID %>").disableSelection();

        $("#<%= blSelectedDocuments.ClientID %>").sortable();
        $("#<%= blSelectedDocuments.ClientID %>").disableSelection();
    });

    $(function () {
        $("#<%= blAvailableDocuments.ClientID %>").draggable({
            drag: function (event, ui) {
                if (!ui.draggable[0].hasAttribute("ID")) {
                    return;
                }
            }
        });
        $("#<%= blAvailableDocuments.ClientID %>").droppable({
            drop: function (event, ui) {
                var source = ui.draggable[0].parentElement.id;
                var target = event.target.id;

                if (source != target) {
                    Move(ui.draggable[0], source, target);
                }
            }
        });

        $("#<%= blSelectedDocuments.ClientID %>").draggable({
            drag: function (event, ui) {
                if (!ui.draggable[0].hasAttribute("ID")) {
                    return;
                }
            }
        });
        $("#<%= blSelectedDocuments.ClientID %>").droppable({
            drop: function (event, ui) {
                var source = ui.draggable[0].parentElement.id;
                var target = event.target.id;

                if (source != target) {
                    Move(ui.draggable[0], source, target);
                }
            }
        });
    });

    function Move(element, source, target) {
        var newLI = document.createElement("li");
        var sourceBL = document.getElementById(source);
        var targetBL = document.getElementById(target);

        newLI.innerHTML = element.innerHTML;
        sourceBL.removeChild(element);
        targetBL.appendChild(newLI);

        PersistDocumentSelections();
    }

    function PersistDocumentSelections() {
        $("#<%= persistSelectedDocuments.ClientID %>").val("");
        $("#<%= blSelectedDocuments.ClientID %> li").each(function (index) {
            var value = $("#<%= persistSelectedDocuments.ClientID %>").val();
            value += $(this).text() + "|";
            $("#<%= persistSelectedDocuments.ClientID %>").val(value);
        });

        $("#<%= persistNonSelectedDocuments.ClientID %>").val("");
        $("#<%= blAvailableDocuments.ClientID %> li").each(function (index) {
            var value = $("#<%= persistNonSelectedDocuments.ClientID %>").val();
            value += $(this).text() + "|";
            $("#<%= persistNonSelectedDocuments.ClientID %>").val(value);
        });
    }

Is there a way to commit the changes to the DOM when items are being dragged/dropped/re-ordered, or to detect the order that they appear on page for the .each() loop ???

A: Peculiarly, The problem was that JQuery didnt recognise its own updates straight away. The solution was to delay the updating of the hidden fields by a few milliseconds.
    drop: function (event, ui) {
        var source = ui.draggable[0].parentElement.id;
        var target = event.target.id;

        if (source != target) {
            Move(ui.draggable[0], source, target);
        }

        setTimeout(function () { PersistDocumentSelections(); }, 100);
    }

Also, not sure if the execution of the drop: function continues past the setTimeout() call, so meaning that the problem was the drop: function required to complete before the changes are committed for the PersistDocumentSelections method to assess them


text:
Q: Unexpected value of __callee__ when including a module – is this a Ruby bug? When invoked via a method created by alias_method, __callee__ ignores the name of the old method (here xxx) and returns the name of the new method, as below:
class Foo
  def xxx() __callee__ end
  alias_method :foo, :xxx
end

Foo.new.foo # => :foo

This behavior holds even when xxx is inherited from a superclass:
class Sup
  def xxx() __callee__ end
end

class Bar < Sup
  alias_method :bar, :xxx
end

Bar.new.bar # => :bar

Given both of the above, I would expect that the same behavior would hold when xxx is included via a module. However, that is not the case:
module Mod
  def xxx() __callee__ end
end

class Baz
  include Mod
  alias_method :baz, :xxx
end

Baz.new.baz # => :xxx

I expect the return value to be :baz, not :xxx.

The above code was executed using Ruby 2.3.1p112. Is this a bug in the implementation of __callee__? Or maybe of alias_method? And if not, can anyone explain why module inclusion behaves differently?

UPDATE 1
I've posted this to the Ruby bug tracker to try to stir up an answer.

UPDATE 2
Apparently, I'm not the only one to be surprised by this issue. I wonder whether Revision 50728 (which was meant to solve Bug 11046: __callee__ returns incorrect method name in orphan proc) might be related.

A: You can see the difference between __callee__ and __method__ in Ruby's Kernel module.
The difference is the calls prev_frame_callee() and prev_frame_func(), respectively. I found these function definitions at http://rxr.whitequark.org/mri/source/eval.c
In short, Foo and Bar are immediately calling the aliased methods foo and bar (which are names for xxx), while Baz has to find Mod and call xxx from Mod. __method__ looks for the original called method's id, while __callee__ looks for the closest called method's id to the __callee__ call. This is better seen in eval.c at lines 848 to 906: look for the difference in the two methods on the return calls similar to <something> -> called_id vs <something> -> def->original_id.
Also, if you look at the Kernel from version 1.9.3, you will see that the two methods originally were the same. So, at some point, there was a purposeful change between the two.

A: This was a bug, and it was closed 3 days ago with this note:

Seems fixed by r56592.


text:
Q: Ubuntu Core V/S ROS What is the difference between ROS and UBUNTU CORE???
I am very much confused betwwen ROS and Ubuntu core.
Is ros an app for ubuntu core?

A: Straight from the ROS wesite:

The Robot Operating System (ROS) is a flexible framework for writing robot software. It is a collection of tools, libraries, and conventions that aim to simplify the task of creating complex and robust robot behavior across a wide variety of robotic platforms.

Uuntu Core:

Ubuntu Core is a tiny, transactional version of Ubuntu for IoT devices and large container deployments. It runs a new breed of super-secure, remotely upgradeable Linux app packages known as snaps ‐ and it's trusted by leading IoT players, from chipset vendors to device makers and system integrators.

__
ROS is a framework of applications for Linux to control external hardware, specifically robots. Ubuntu Core is just a lightweight version of Ubuntu that uses the Snap packaging system, meant to run on low-power devices.
ROS needs an OS to work. Ubuntu Core is just that: a core.

This comes from 2 minutes of using Google, by the way. It's usually less effort to just look something up than sign up for a website.


text:
Q: Refresh the page only once in react class component I have a react app with a page with a class component on it. What I want to do is to refresh that page only once when you first load it, but all that I have tried, with window.location.reload() for example, ends up in a infinite refresh loop. Does anyone know how to do this? I a functional component I do like this, and it works :
 useEffect(() => {
    if(reloadCount < 2) {
      sessionStorage.setItem('reloadCount', String(reloadCount + 1));
      window.location.reload();
    } else {
      sessionStorage.removeItem('reloadCount');
    }
  }, []);

but if I convert it for class component, like this, it doesn't work :
componentDidMount() {
    if(this.reloadCount < 2) {
      sessionStorage.setItem('reloadCount', String(this.reloadCount + 1));
      window.location.reload();
    } else {
      sessionStorage.removeItem('reloadCount');
    }
  }

Any idea how to do this in react class components ?
P.S. I want to do this because I use a mapbox component that saves the previously initialized map to the DOM, so when the user return to the page containing the map, there's no need to initialize the map again. But now I have this map on another page too, and if I navigate between the 2 pages  containing the map, it keeps the css from the previous page, and it's messed up. And the only way I can work around this is to force refresh the page.

A: Maybe this will fix your problem
componentDidMount() {
    const reloadCount = sessionStorage.getItem('reloadCount');
    if(reloadCount < 2) {
      sessionStorage.setItem('reloadCount', String(reloadCount + 1));
      window.location.reload();
    } else {
      sessionStorage.removeItem('reloadCount');
    }
  }


text:
Q: Highlight Ads for few seconds I got a list of ads in my WordPress website on a sidebar. Is it possible to highlight an ad, that is, make it bigger in size for few seconds? I want to make each ad highlighted one after the other. Right now I am using max ad banner to get the rotating ads, but I do not want to have the rotation anymore.
Thanks

A: Well if you want to increase size you need two images of that add and if your getting some ads from sites that give you revenue then it would be quite hard as you cant call the same ad twice from them to get a bigger image.
Please do not take this next statement as an attack it is just some preference/opinion i have learned from hosting sites.
One thing i will state is that making ad's cycle in an order to make them bigger is a big eye sore for viewers people will see the ads no matter what size if you place them in the right places, but to make them go bigger for a few seconds then return to normal and go to next ad is a little annoying even if you make it go around only once and not loop

A: Playing around with CSS transitions and transforms a bit. It only works in Webkit (Safari, Chrome) and it is not finished. You may like the idea, though.
http://jsfiddle.net/Jv3tm/1/
HTML:

CSS:
#ads li { margin:1em; text-align:center; }
#ads img { -webkit-transition:-webkit-transform 0.5s linear; }

JavaScript:
$(document).ready(function() {
    $('#ads img').each(function(i) {
        $(this).css({
            '-webkit-transition-delay': (i/2) + 's'
            ,'-webkit-transform': 'scale(1.2)'
        });
    });
});

@xLRDxREVENGEx: agreed on your point about this being annoying behavior.


text:
Q: Call functions synchronously in JS I want to call an API in React after a function has been executed.
    const [isVisible, setVisible] = useState(false);
    const [isValid, setValidation] = useState(true);
    const [validationMessage, setValidationMessage] = useState('');

const validate = (callback) => {
        if (code == null || code.trim().length === 0) {
            setValidation(false);
            setValidationMessage(translate.signIn.codeErrorMessage);
            setVisible(true);
        } else if (phoneNumber == null || phoneNumber.trim().length === 0) {
            setValidation(false);
            setValidationMessage(translate.signIn.phoneErrorMessage);
            setVisible(true);
        }
        callback();
    }

    const authenticate = async () => {
        try {
            return await (authenticateUser.get('/abc', {
                params: {
                    code,
                    phoneNumber,
                }
            }));
        }
        catch (e) {
            setValidationMessage(translate.signIn.exceptionMessage);
            setVisible(true);
        }
    }

    const validateUserCredentials = () => {
        if (isValid) {
            setActivitySpinner(true);
            authenticate().then(response => {
                setActivitySpinner(false);
                const responseData = response.data;
                console.log('responseData', responseData);
                if(responseData.status !== 200) {
                    setVisible(true);
                    setValidationMessage(responseData.message);
                }
                else if(responseData.status === 200) {
                    console.log('success');
                }
            });
        }
    }

  const onSubmit = () => {
        validate(validateUserCredentials);
    }

When I invoke 'onSubmit' function, even if the value of isValid is false. I can see the API is being called.
I want to call the function validateUserCredentials only after the function validate has done its task.
Can anyone please tell me what am I doing wrong here?

A: Ciao, for sure validateUserCredentials is called after validate, maybe you are confused because on validateUserCredentials you see that isValid stills true even if you setted as false.
Unfortunately with Hooks you cannot have callback as this.setState to have the certainty that isValid as been setted. What you can do is:
const validate = (callback) => {
    let isvalid_temp = isValid;
    if (code == null || code.trim().length === 0) {
        setValidation(false);
        isvalid_temp = false;
        setValidationMessage(translate.signIn.codeErrorMessage);
        setVisible(true);
    } else if (phoneNumber == null || phoneNumber.trim().length === 0) {
        setValidation(false);
        isvalid_temp = false;
        setValidationMessage(translate.signIn.phoneErrorMessage);
        setVisible(true);
    }
    callback(isvalid_temp);
}

const validateUserCredentials = (isvalid_temp) => {
    if (isvalid_temp) {
        setActivitySpinner(true);
        authenticate().then(response => {
            setActivitySpinner(false);
            const responseData = response.data;
            console.log('responseData', responseData);
            if(responseData.status !== 200) {
                setVisible(true);
                setValidationMessage(responseData.message);
            }
            else if(responseData.status === 200) {
                console.log('success');
            }
        });
    }
}


text:
Q: Caching data before presenting popover I have a main controller, and a popover that gets presented from the main controller.  My main controller passes an array to my popover.  In my viewDidLoad of my popover controller, I take that array, get the image and text data for that entry and put it into an NSDictionary.  I do this because I need to resize my pictures for my UITableView to be presented in the popover.  It works fine, however, since I now have an NSArray of NSDictionary in my popover, every time I bring up my popover, since this code is in the viewDidLoad, it gets created each time.  It seems like an expensive operation since there is a bit of lag in presenting the popover to begin with.  Is there a way I can cache the data somewhere once it's loaded once?  Thanks.

A: Couldn't you create it in your main controller and pass it as a parameter to your popover?


text:
Q: The count() method counts wrong Here is my task to solve.
For a list of integers, find and print the items that appear in the list
only once. Items must be printed in the order in which they are
are in the incoming list.
I wrote the code but it also counts two and three digit numbers as a single digits. What's the problem?
x = []
a = input()
a.split(" ")
for i in a:
    if a.count(i) == 1:
        x.append(i)
print(x)

A: User Mechanical Pig provides the answer, split does not work in-place, since you're discarding its result what you're looking at is the count of each character in the string, not each space-separated sub-string.
The standard library also contains a collection which is ready-made for this use-case: collections.Counter. You can just give it a sequence of items and it'll collate the counts, which you can then filter:
print([k for k, v in collections.Counter(a.split()).items() if v == 1])

A: a.split(" ") does not change the value of a, so it is still a string and not a list. Hence when you iterate over a, you only get single characters.
str.split is a method that returns a list, but does not magically turn the string into a list. So you need to assign the value it returns to a variable (for example, to a, if you don't want to hold on to the input string).

A: You can assign the variable as mentioned above or you can directly use the split function in the loop.
x = []
a = input()
for i in a.split(" "):
    if a.count(i) == 1:
        x.append(i)
print(x)

or split when you are reading the input.
x = []
a = input().split(" ")
for i in a:
    if a.count(i) == 1:
        x.append(i)
print(x)

A: Using the Counter class from the collections module is the right way to do this but here's another way without any imports where you effectively have your own limited implementation of a Counter:
a = '1 2 3 4 4 5 6 7 7 7'

d = {}

for n in a.split():
    d[n] = d.get(n, 0) + 1

for k, v in d.items():
    if v == 1:
        print(k)

Output:
1
2
3
5
6


text:
Q: How i can create a muti value filed without manytomany field in django? I have a model:
class People(models.Model):
   family = models.CharField(null=True)
   phone_numbers = ?

How i can implement phone_numbers for some phone numbers. I think ManyToManyField is not a good idea for doing this.
What is best practice for this?
admin.py
class PhonesInline(admin.TabularInline):
    model = models.Phones

class PeopleAdmin(admin.ModelAdmin):
    inlines = [
        PhonesInline,
    ]
admin.site.register(models.People, PeopleAdmin)

A: What you can do is create a Phone model and create a Many-to-one relationship between Phone and People using ForeignKey. With this you can associate various phone numbers to a single person.
class People(models.Model):
    family = models.CharField(null=True)

class Phone(models.Model):
    number = models.CharField(max_length=15, unique=True)
    person = models.ForeignKey(People, on_delete=models.CASCADE)

Now, for example, if you have a People instance in a variable called people, you can access its related phone numbers with values_list:
people.phone_set.values_list('number', flat=True)

As a note for your model, it's not recommended to use null=True to a CharField/TextField. The official Django documentation states the following:

Avoid using null on string-based fields such as CharField and TextField. If a string-based field has null=True, that means it has two possible values for "no data": NULL, and the empty string. In most cases, it's redundant to have two possible values for "no data;" the Django convention is to use the empty string, not NULL. One exception is when a CharField has both unique=True and blank=True set. In this situation, null=True is required to avoid unique constraint violations when saving multiple objects with blank values.

You can also take a look at this question, which tackles my last point.
Also I don't know which logic you want to apply to your project, but I think a better way to organize your models and their relationships is to create a Family class to deal with families like:
class Family(models.Model):
    name = models.CharField(max_length=100)

class People(models.Model):
    family = models.ForeignKey(Family, blank=True, null=True)

class Phone(models.Model):
    number = models.CharField(max_length=15, unique=True)
    person = models.ForeignKey(People, on_delete=models.CASCADE)

With this extra model you will be able to create another Many-to-one relationship between People and Family. Depending on your needs, you should adapt the arguments when creating the fields, the ones I provided are just an example.


text:
Q: Access UITableView section header label is there a way to customize the section header label without drawing my own view first?
I just want to change the alignment of the label.

A: If you are targeting iOS 6, you could use UITableViewHeaderFooterView. This has a property textLabel, which gives you access to the label that's being drawn. I haven't worked with it a whole lot, but you may have to configure a few other things before it looks 100% like a table header label.


text:
Q: QThreaded C++ daemon does not shutdown properly I have written a Qt5/C++ program which forks and runs in the background, and stops in response to a signal and shuts down normally.  All sounds great, but when I "ps ax | grep myprog" I see a bunch of my programs still running; eg:
29244 ?        Ss   149:47 /usr/local/myprog/myprog -q
30913 ?        Ss     8:37 /usr/local/myprog/myprog -q
32484 ?        Ss     0:11 /usr/local/myprog/myprog -q

If I run the program in the foreground then the process does NOT hang around on the process list - it dies off as expected.  This only happens when in the background.  Why?

Update: I found that my program is in futex_wait_queue_me state (queue_me and wait for wakeup, timeout, or signal).  I do have 3 seperate threads - and that may be related.  So I attached a debugger to one of the waiting processes and found this:
(gdb) bt
#0  0x000000372460b575 in pthread_cond_wait@@GLIBC_2.3.2 () from /lib64/libpthread.so.0
#1  0x00007f8990fb454b in QWaitCondition::wait(QMutex*, unsigned long) ()
   from /opt/Qt/5.1.1/gcc_64/lib/libQt5Core.so.5
#2  0x00007f8990fb3b3e in QThread::wait(unsigned long) () from /opt/Qt/5.1.1/gcc_64/lib/libQt5Core.so.5
#3  0x00007f8990fb0402 in QThreadPoolPrivate::reset() () from /opt/Qt/5.1.1/gcc_64/lib/libQt5Core.so.5
#4  0x00007f8990fb0561 in QThreadPool::waitForDone(int) () from /opt/Qt/5.1.1/gcc_64/lib/libQt5Core.so.5
#5  0x00007f89911a4261 in QMetaObject::activate(QObject*, int, int, void**) ()
   from /opt/Qt/5.1.1/gcc_64/lib/libQt5Core.so.5
#6  0x00007f89911a4d5f in QObject::destroyed(QObject*) () from /opt/Qt/5.1.1/gcc_64/lib/libQt5Core.so.5
#7  0x00007f89911aa3ee in QObject::~QObject() () from /opt/Qt/5.1.1/gcc_64/lib/libQt5Core.so.5
#8  0x0000000000409d8b in main (argc=1, argv=0x7fffba44c8f8) at ../../src/main.cpp:27
(gdb)

Update:
I commented out my 2 threads, so only the main thread runs now, and the problem is the same.
Is there a special way to cause a background process to exit?  Why won't the main thread shutdown?

Update:
Solved - Qt does not like Fork.  (See another StackExchane questoin).  I had to move my fork to the highest level (before Qt does anything), and then Qt doesn't hang on exit.

A: *

*http://man7.org/linux/man-pages/man1/ps.1.html#PROCESS_STATE%20CODES

PROCESS STATE CODES
Here are the different values that the s, stat and state output specifiers (header "STAT" or "S") will display to describe the state of a process:
  D    uninterruptible sleep (usually IO)
  R    running or runnable (on run queue)
  S    interruptible sleep (waiting for an event to complete)
  T    stopped, either by a job control signal or because it is being traced.
  W    paging (not valid since the 2.6.xx kernel)
  X    dead (should never be seen)
  Z    defunct ("zombie") process, terminated but not reaped by its parent.

For BSD formats and when the stat keyword is used, additional characters may be displayed:
  <    high-priority (not nice to other users)
  N    low-priority (nice to other users)
  L    has pages locked into memory (for real-time and custom IO)
  s    is a session leader
  l    is multi-threaded (using CLONE_THREAD, like NPTL pthreads do)
  +    is in the foreground process group.

So your processes are all in "S: interruptible sleep."  That is, they are all waiting for blocking syscalls.
You might have better hints on what your programs are waiting for from this command:
$ ps -o pid,stat,wchan `pidof zsh`
  PID STAT WCHAN
 4490 Ss   rt_sigsuspend
 4814 Ss   rt_sigsuspend
 4861 Ss   rt_sigsuspend
 4894 Ss+  n_tty_read
 5744 Ss+  n_tty_read
...

"wchan (waiting channel)" shows a kernel function (=~ syscall) which is blocking.
See also

*

*https://askubuntu.com/questions/19442/what-is-the-waiting-channel-of-a-process


text:
Q: PDOStatement::execute with parameters This page is really not clear for the function: http://www.php.net/manual/en/pdostatement.execute.php
I'm not exactly sure why I would bindParam as oppose to just passing in an array. With bindParam, I'll have to specify the type.
So my question would be, if I just do $stmt->execute(array("somevalue", b'somebinarydata', 10203, 201.3));, would the types be automatically recognized? Is there anything I have be aware of?
Thanks.

A:
So my question would be, if I just do $stmt->execute(array("somevalue", b'somebinarydata', 10203, 201.3));, would the types be automatically recognized?

The answer is No, The PHP manual states:

An array of values with as many elements as there are bound parameters in the SQL statement being executed. All values are treated as PDO::PARAM_STR.

the page stating the entity PDO::PARAM_STR states:

Represents the SQL CHAR, VARCHAR, or other string data type.

source: http://www.php.net/manual/en/pdo.constants.php

A: As it says in the doc, if you want to specify type you do that beforehand, for example:
$sth->bindParam(':calories', $calories, PDO::PARAM_INT);

Example


text:
Q: Assembly ID is getting appended when zip file is created by maven xml and pom.xml which creates jar file and then zip file with some artifacts including jar file. But when i run maven install zip file is getting created as GenerateMissingUsersReport-bin.zip instead I want it to create as GenerateMissingUsersReport.zip. I have set as false. But no difference.
Any pointers?
Here is dep.xml
<id>bin</id>
<baseDirectory>../</baseDirectory>
<formats>
<format>zip</format>
</formats>
<fileSets>
<fileSet>
<directory>${project.basedir}</directory>
<outputDirectory>/</outputDirectory>
<includes>
<include>README*</include>
<include>LICENSE*</include>
<include>NOTICE*</include>
</includes>
</fileSet>
<fileSet>
<directory>${project.build.directory}</directory>
<outputDirectory>/lib</outputDirectory>
<includes>
<include>*.jar</include>
</includes>
</fileSet>
<fileSet>
<directory>${project.build.directory}/classes</directory>
<includes>
<include>plugin.xml</include>
</includes>
<outputDirectory>/</outputDirectory>
</fileSet>
</fileSets>

Here is pom.xml
<finalName>GenerateMissingUsersReport</finalName>
    <plugins>
        <plugin>
            <artifactId>maven-assembly-plugin</artifactId>
            <version>2.4</version>
            <configuration>
                        <finalName>GenerateMissingUsersReport</finalName>
                        <appendAssemblyID>false</appendAssemblyID>
                        <descriptor>src/assembly/dep.xml</descriptor>
            </configuration>
            <executions>
                <execution>
                    <id>make-zip</id>
                    <phase>package</phase>
                    <goals>
                        <goal>single</goal>
                    </goals>
            </execution>
            </executions>
        </plugin>
        <plugin>
    <artifactId>maven-jar-plugin</artifactId>
    <version>2.4</version>
    <executions>
      <execution>
        <id>default-jar</id>
        <phase>package</phase>
        <goals>
          <goal>jar</goal>
        </goals>
      </execution>
    </executions>
    <configuration>
    <excludes>
    <exclude>plugin.xml</exclude>
    </excludes></configuration>
    </plugin>

A: Add the following line under configurations element of the pom
<appendAssemblyId>false</appendAssemblyId>

Also make sure you use the latest version of the assembly plugin
<artifactId>maven-assembly-plugin</artifactId>
<version>2.5.5</version>


text:
Q: Calling a C function in assembly Despite I searched everywhere I couldn't find any solution to my problem.The problem is that I I defined a function "hello_world() " in a C file "hello.c" and I want to call this function in an assembly file . "hello_assembly.asm" .Can anyone help me ?
Thank you.

A: You could check the below example which might give some idea.
\#include <stdio.h>
int main(void)
{
        signed int a, b;
        a=5,b=25;
        mymul(&a,&b);
        printf("\nresult=%d",b);
        return 0;
}

mymul is a function which is being written in assembly language in file called mymul.S

Below is the code for mymul.S
.globl mymul
mymul:
        pushl %ebp            # save the old base pointer register
        movl %esp, %ebp       #copy the stack pointer to base pointer register
        movl 8(%ebp), %eax    # get the address of a
        movl 12(%ebp), %ebx   # get the address of b
        xchg (%eax), %ecx     # we get the value of a and store it in ecx
        xchg (%ebx), %edx     # we get the value of b and stored it in edx
        imul %ecx,%edx        # do the multiplication
        xchg %ecx, (%eax)     #save the value back in a
        xchg %edx, (%ebx)     # save the value back in b
        movl %ebp, %esp       # get the stack pointer back to ebp
        popl %ebp             #restore old ebp
        ret                   #back to the main function

We use the command "cc" to compile our above programs
$ cc mymul.S mul.c -o mulprogram

In the mul.c when we call mymul, we are passing address of a and b , and these address    are getting pushed to the stack.  When the execution of program enters the mymul function, the stack looks like this: addressofb,addressofa, returnaddress, oldebp

we get the value stored in the address of a and address of b using xchg(we could use movl here) , do the multiplication and save the result in b.

I hope the above program helps you.

A: gcc calling conventions
The gcc documentation should spell this out in more detail.
If you couldn't find documentation for your compiler and environment, I'd suggest you  compile your C function to an assembler listing and look at how it expects arguments to be passed in and what it leaves on the stack when exiting.


text:
Q: Override specific docker-compose values with no value via file composition In my project I have a series of docker-compose yml files. I run my application as such docker-compose -f docker-compose.yml -f docker-compose.ci.yml up -d.
docker-compose.yml
db:
    container_name: db
    image: mysql
    ...
ui:
    container_name: ui
    image: flask

docker-compose.ci.yml
db:
    image: db:$BUILD_NUM
ui:
    image: ui:$BUILD_NUM

Is there a way for me to override the container name (or any service property) that is defined in the base file with a blank value? In my case, I want the ci container name to be randomly generated. I don't want to remove the container name from the base yml file.


text:
Q: Zabbix: Is it possible to show the uptime of all hosts in a single graph? I found no up to date information on this.
Background is that I want to see for all workstations (all or maybe also a group) when they are online and when they aren't.

A: It sounds like you don't want a graph (which will be unreadable) but some other visualisation.
For your needs network maps might be better. That will give you an area with each host represented by an icon or anything else you prefer. If you do not care about the topology, just arrange all the hosts in a grid.
If you have a lot of hosts, making each host a coloured rectangle might offer the highest density.


text:
Q: Devise Invitable is modifying existing users CONTEXT
I'm using devise_invitable to allow a user (with an admin role) to register another user in my app.
User objects have an email, password, token (random string), role (also string) and an associated HealthRecord object which has name, last name, dni (personal id) plus some extra info
PROBLEM
For some reason, when I input an existing email, I get an error (which is intended validation) but it also destroys the HealthRecord associated with the user who has that existing email.
CODE
This is what my console shows upon trying to create the user with existing email
Started POST "/users/invitation" for ::1 at 2021-11-26 10:04:15 -0300
Processing by Users::InvitationsController#create as HTML
  Parameters: {"authenticity_token"=>"[FILTERED]", "user"=>{"email"=>"paciente1@example.com", "role"=>"Paciente", "health_record_attributes"=>{"residencia"=>"Cementerio", "nombre"=>"overriding", "apellido"=>"test", "dni"=>"123456789", "risk"=>"0", "birth"=>"1999-02-12"}}, "commit"=>"Registrar"}
  User Load (0.1ms)  SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ?  [["id", 5], ["LIMIT", 1]]
  User Load (0.3ms)  SELECT "users".* FROM "users" WHERE "users"."email" = ? ORDER BY "users"."id" ASC LIMIT ?  [["email", "paciente1@example.com"], ["LIMIT", 1]]
  HealthRecord Load (0.1ms)  SELECT "health_records".* FROM "health_records" WHERE "health_records"."user_id" = ? LIMIT ?  [["user_id", 1], ["LIMIT", 1]]
  TRANSACTION (0.1ms)  begin transaction
  HealthRecord Destroy (0.5ms)  DELETE FROM "health_records" WHERE "health_records"."id" = ?  [["id", 1]]
  TRANSACTION (207.2ms)  commit transaction
  User Exists? (0.3ms)  SELECT 1 AS one FROM "users" WHERE "users"."email" = ? AND "users"."id" != ? LIMIT ?  [["email", "paciente1@example.com"], ["id", 1], ["LIMIT", 1]]
  HealthRecord Exists? (0.4ms)  SELECT 1 AS one FROM "health_records" WHERE "health_records"."dni" = ? LIMIT ?  [["dni", "123456789"], ["LIMIT", 1]]
  Rendering layout layouts/application.html.erb
  Rendering users/invitations/new.html.erb within layouts/application
  HealthRecord Load (0.1ms)  SELECT "health_records".* FROM "health_records" WHERE "health_records"."user_id" = ? LIMIT ?  [["user_id", 5], ["LIMIT", 1]]
  ↳ app/views/users/invitations/new.html.erb:18

The view to generate the new user

Registro excepcional

<%= form_for(setup_user(resource), as: resource_name, url: invitation_path(resource_name), html: { method: :post }) do |f| %>

  <% resource.class.invite_key_fields.each do |field| -%>

      <%= f.label field %>

      <%= f.text_field field, class: 'form-control'%>

  <% end %>

    <%= f.hidden_field :role, :value=>"Paciente"%>

  <%= f.fields_for :health_record do |ff| %>

      <%= ff.hidden_field :residencia, :value=>current_user.health_record.residencia%>

      <%= ff.label "Nombre" %>

      <%= ff.text_field :nombre, class: 'form-control',:required => true%>

      <%= ff.label "Apellido" %>

      <%= ff.text_field :apellido, class: 'form-control',:required => true%>

      <%= ff.label "DNI" %>

      <%= ff.text_field :dni, class: 'form-control',:required => true%>

      <%= ff.label "Es de riesgo:",:required => true %>
      <%= ff.check_box :risk  %>

        <%= ff.label "Fecha de nacimiento:"%>

        <%= ff.date_field :birth, class: 'form-control',:required => true%>

  <% end %>

    <%= f.submit "Registrar" %>

<% end %>

The user model which has validate_on_invite
class User < ApplicationRecord
  devise :invitable, :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable, :authentication_keys => [:token,:email], :validate_on_invite => true
  has_many :comprobantes, :dependent => :destroy
  has_one :health_record, :dependent => :destroy
  has_many :TurnoAsignado, :dependent => :destroy
  has_many :TurnoNoAsignado, :dependent => :destroy

  validates :email, uniqueness: true

  before_save :init

  accepts_nested_attributes_for :health_record

  def init()
    if self.token.nil?
      self.token = (rand()*1000000).to_i
    end
  end

end

The HealthRecord model
class HealthRecord < ApplicationRecord
  belongs_to :user
  validates :dni, presence: true
  validates :dni, uniqueness: true
  validates :nombre, presence: true
  validates :apellido, presence: true
  validates :birth, presence: true
  before_save :upcase_content

  def upcase_content
      self.nombre=self.nombre.downcase
      self.apellido=self.apellido.downcase
      self.nombre=self.nombre.split(/ |\_/).map(&:capitalize).join(" ")
      self.apellido=self.apellido.split(/ |\_/).map(&:capitalize).join(" ")
  end

end

The invitation controller (it's pretty much default I just added parameters and an after_path)
class Users::InvitationsController < Devise::InvitationsController

  before_action :configure_permitted_parameters

    #Permit the new params here.
  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:invite, keys: [
        :token,
        :role,
        health_record_attributes: [
            :apellido,
            :nombre,
            :dni,
            :risk,
            :birth,
            :residencia
          ]
        ])
  end

  def after_invite_path_for(resource)
    new_asignado_path(self.resource.id)
  end

end

A: I think the problem may have been this line
form_for(setup_user(resource),...

I am using a helper to set the HealthRecord of a user to an empty one (fields_for needed the user to have a HealthRecord to work)
module FormHelper
    def setup_user(user)
      user.health_record ||= HealthRecord.new # ||= means "assign this value unless it already has a value"
      user
    end
  end

Maybe what was happening is that the empty HealthRecord was assigned to the existing user, somehow?
I solved it by intercepting the flow of the create method in the invitations controller, by asking if the user email or dni exists
def create
    @correo = User.find_by(email:params[:user][:email])
    @dni = HealthRecord.find_by(dni:params[:user][:health_record_attributes][:dni])

    if (@correo.nil? && @dni.nil?) #si no existe mail ni dni
      super
    else
      mensaje="Los siguientes campos ya estan registrados:"
      if !(@correo.nil?)
        mensaje = mensaje + " email"
      end
      if !(@dni.nil?)
        mensaje = mensaje + " dni"
      end
      flash[:notice] = mensaje
      redirect_to new_user_invitation_path
    end
  end

Although this works, I'm not sure about the reason of the problem, any insight is welcome


text:
Q: compareTo() How to use three words instead of two Is there a way to use compareTo() to use three words instead of two
such as a1.compareTo(a2); which uses two, how do you use three?

A: No, there is no such method and anyway, the results of a tree-way comparison cannot be meaningfully expressed with a single integer quantity.
If you think you need such a method, what you really need is a way to sort three items. Put them into an array, or a List, and call Arrays.sort or Collections.sort, respectively.

A: Use a collection just like this:
    String n = "word";
    Collection<String> f = new ArrayList<String>();
    f.add("one");
    f.add("one");
    f.add("one");
    System.out.println(Collections.frequency(f, "one") == f.size());
    f.add("tow");
    System.out.println(Collections.frequency(f, "one") == f.size());


text:
Q: how to create pinterest layout? I'm trying to achieve Pinterest layout in my app, and i tried the tutorial from raywenderlich. my problem how to implement to UICollectionView cellForItemAt and heightForPhotoAtIndexPath
here my code:
   func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell  = collectionView.dequeueReusableCell(withReuseIdentifier: "GaleryCollection", for: indexPath) as! GaleryCollectionViewCell
    let imgGalery = self.galery![indexPath.row]
    if imgGalery.photo != nil {
        cell.imageGalery.af_setImage(withURL: URL(string: imgGalery.photo!)!)
    }
    return cell
}

A: I have used the same tutorial inside my project.  I am using this delegate function.  You'll need to import AVFoundation.  If you are pulling your images from a database it will be better for you to set the image's height and width inside your DB to easily recall them as I have below.
func collectionView(collectionView: UICollectionView, heightForPhotoAt indexPath: IndexPath, with width: CGFloat) -> CGFloat {

    let postHeight = posts[indexPath.item].postImageHeight
    let postWidth = posts[indexPath.item].postImageWidth
    let postSize = CGSize(width: postWidth, height: postHeight)
    let boundingRect = CGRect(x: 0, y: 0, width: width, height: CGFloat(MAXFLOAT))
    let rect = AVMakeRect(aspectRatio: postSize, insideRect: boundingRect)

    return rect.size.height
}

I am now facing an issue when appending objects though. :/


text:
Q: Why do I get this error with ggbetweenstats? I am trying to label outliers in a boxplot via ggbetweenstats, but I get this error:
enter image description here
My data is from here: https://travelsmartcampaign.org/wp-content/uploads/Travel-Smart-Ranking-2022.xlsx-Travel-Smart-Ranking-2022-8May.pdf. (I have added "_" to the variables Total Score and Company Name)
My code is:
enter image description here


text:
Q: Is there a way to init a WKWebView with a pre-loaded history? Everything is in the title : I'd like to init a WKWebVIew with a pre-loaded history.
Actually, my ultimate goal is to save the history of my WKWebView so when a user closes the app and re-opens it, he/she can get his/her web view back ( with the same history ).
Is there a way to do that ? At first, I wanted to save the backForwardList of my WKWebView but it's actually impossible to set it when initialising the web view, as it is a get-only property.
I also thought about saving all the URLs and then reloading them one by one but I'm pretty sure there's an easier way to accomplish that. I don't know how Google and Apple do with Chrome and Safari.


text:
Q: Hexahedron made with similar polygons The isohedra are made with congruent polygons. I wondered what could be built with similar polygons that are not congruent. Here is one where edgelengths are powers of $\sqrt{\psi}$, where $\psi$=supergolden ratio.

Unfortunately, it's a flat 2D object.  From my List of substitution tilings, this can be seen as part of my psi-quad tiling.

A similar 2D hexahedron can be made with a piece of my rho-quad tiling, where $\rho$=plastic constant

One goal is to find a polyhedron that sorta splits into 2 or more similar polyhedra where most of the vertices align, much like what is being done with polygons in the psi-quad and rho-quad tilings.
But for this post, a simpler question:

Are there 3D polyhedra where all polygons are similar but not congruent?  Is there a 3D hexahedron made with similar but not congruent polygons? Or a Herschel enneahedron?

EDIT:  That opening picture isn't a hexahedral graph. Silly me. I believe the only hexahedron that works has edges with powers $(a^{-1},0,0,a)\times4,(a^{-2},a^{-1},a^{-1},0)\times2$.
EDIT 2:  There are infinite solutions for the tetrahedron (rootbounds $1/\phi<a<\phi$) and octahedron (rootbounds $1/\sqrt2<a<\sqrt2$). Here are pictures with the power of the root labeling the edges.

EDIT3: For the triangulated polyhedra (A000109), it should almost always be possible to 3-color the edges so that each face has three colors: 0,1,2. Change some 0 to 3, then let these edges be powers for a similar triangle representation. How many of these triangulated polyhedra are representable with similar triangles?
EDIT4:  I've posted Tetrahedral and Octahedral Similarohedrons for those that would like to explore this class.

A: A hexahedron is possible with all faces similar, and some but not all congruent. But it is rather subtle.
A hexahedron with all faces similar must have either all faces quadrangular (a distorted parallelepiped) or all triangular (an irregular triangular bipyramid). I choose to work with the latter form because it is simpler and yields a solution by your own methodology.
We begin by assembling three similar triangles with sides in the ratio $1:r:r^3$ for some value of $r$ greater than $1$. The triangles are to share a common vertex $A$ and pairs will share edges $\overline{AB},\overline{AC},\overline{AD}$ so as to form the lateral surfaces of a pyramid with base $\triangle BCD$.
The edge lengths may then be rendered as follows:
Lateral: $AB=r^3, AC=r, AD=r^2$
Basal: $BC=1,CD=r^4, BD=r^5$
With these lengths, the pyramidal cap is formed provided that all four faces satisfy the strict triangle inequality and the Cayley-Menger determinant is positive to give a real volume for the tetrahedron. Intuitively we might expect the determinant to fail first as $r$ is increased, but in fact that does not happen for a reason we will shortly see.
The triangle inequalities require
Lateral: $r^3-r-1<0$
Basal: $r^5-r^4-1<0$
It happens that $r^5-r^4-1$ factors, equaling $(r^2-r+1)(r^3-r-1)$, so the two inequalities have a common bound and, geometrically, the cap collapses to a straight line rather than a flat triangular surface. This geometry prevents the Cayley-Menger determinant from changing sign, but it leaves the bound in place from the triangle inequalities. Carrying out the root calculation to three significant figures and rounding (the upper bound) down shows we can allow $1<r<1.32$.
We can also consider the case $r<1$ with the edge lengths as given above. In this case the triangle inequalities are rendered thusly:
Lateral: $r^3+r-1<0$
Basal: $r^5+r^4-1<0$
The Cayley-Menger determinant is more complicated, but as $r$ decreases from $1$ the determinant remains positive as long as a sixth-degree controlling factor does:
C-M determinant: $r^6+r^4-1>0$
Now, the Cayley-Menger determinant fails first as $r$ decreases; the tetrahedron goes flat (volume=0) with $0.86<r<0.87$ whereas the basal triangle would have degenerated with $0.85<r<0.86$! We accept the bound $0.87<r<1$ for this case.
Having formed our pyramidal cap, we simply combine it with its reflection through the base to form the bipyramid, eliminating the nonsimilar basal face by making it internal.


text:
Q: Why does IE8 add an extra element? I know, nobody likes to debug IE. If you check out this link below in IE8 or IE9(without compatibility view) it seems to be adding empty UL elements in the footer.

A: You do have a few validation errors on the page, including:

Heavy Haul Platform Trailers

This could be causing the issue you're seeing in IE 8.


text:
Q: Adjusted predictions running ANOVA in Stata I have an outcome variable x and three explanatory variables a, b, c which are categorical variables. In my example a has 8 levels, b has 4 levels and c has 35 levels, but not all combinations of the three variables has observations (this is probably unimportant).
If I run the following additive ANOVA model in Stata
anova x a b c
adjust, by(a b) gen(y)

then I obtain predictions of the variable x adjusted by the variables a and b. The adjust command outputs the following table in the Result window, and also it generates a variable y with adjusted predictions.

      |                 b
    a |       2        4        8       16
----------+-----------------------------------
   50 | .016655  .018487
   75 | .008286  .011237
  100 | .005937  .006677  .012467
  150 | .001905  .004038  .009454
  200 | .001774  .003107  .007592  .010081
  400 |          .004982  .006853  .009342
  800 |                   .002126   .00521
 1000 |                   .002732  .005221
----------------------------------------------
 Key:  Linear Prediction

My problem is that the variable y has a value for each combination of a, b and c while the table above only has values for each combination of a and b. How can I save the results from the table, so I'm able to work with these? What is the connection between the values in the table and the values in y?
Thanks in advance.
Update: I found this in help adjust:

Variables used in the estimation command but not included in either the by() variable list or the adjust variable list are left at their current values, observation by
      observation.  Here adjust displays the average estimated prediction (or the corresponding probability or exponentiated prediction), substituting the mean of these unspecified variables within each group defined by the variables
      in the by() option.

This is also true for my data. For example if a=75 and b=2, then c takes on the values 12,13,14,15,16. The value of y corresponding to c=14 (which is the average) is exactly what is displayed in the table. But what if the average of the values is not a value that it takes on?

A: This is a reply to Stefan Hansen's comment on adjust and margins.
In general, no; but everything depends on the model and whether there are covariates other than those named. But consider the results of
sysuse auto, clear
anova mpg foreign rep78
adjust, by(foreign rep78)
margins foreign#rep78

Here the results do coincide.
I am not fluent in margins beyond elementary uses, so any more complicated questions will need to be handled by someone else.


text:
Q: MQTT know if a client is subscribed The question is already posted, Mqtt How a client can get to know that another client is connected or not
and How to Find Connected MQTT Client Details
In my case, if client X is already subscribed in a channel A, client Y can't subcribe to the channel A, until X unsubcribes. I can only have one client subscribed in the channel
Can I also use the idea of retained messages and LWT?
If yes, I don't know exactly from where should I start. It would be good to start with a simple example to see how the retained messages and LWT work. So far, I just have experience in publishing and subscribing but no more.
Could you please, tell me some advises may be some links or examples or any useful information so I can have a starting point.

A: MQTT is all about having multiple clients subscribing to the same topics, it's part of the whole pub/sub pattern and sharing information. So there is nothing baked into the protocol that will do what you want.
You may be able to implement something like the following:
If have a topic say foo/bar and you only want one subscriber you could publish a retained message with a payload of the client-id of the subscriber to lock/foo/bar. You could then publish a "free"  to this lock topic when you disconnected and set up a LWT to do the same in case the client dies.
The problem with this is that everything is asynchronous so it opens up lots of timing windows for race conditions. e.g. say client-1 and client-2 both want to subscribe to foo/bar, they would both need to first subscribe to lock/foo/bar to check it's state. They both do this at very nearly the same time, they then have to wait for some time to see what message they get back ("free" or a client-id). They would both get "free" so would both assume that they can publish their client-ids. client-1 published first shortly followed by client-2 and then they both subscribe to foo/bar.


text:
Q: A Program to print the last n, (n+1), (n+2),....(n+31) number of digits of the number input by the user, where n = 1, otherwise print "0+error.extra"
#include <stdio.h>

int main()
{
    signed int x;
    int x1 = 0, x2 = 10, final, loop = 1, y = 10, c;
    printf("Enter the value of X.\n");
    scanf("%d", &x);
    printf("Value Scanned:%d\n", x);
again:
    if (loop <= 32)
    {
        if (x >= x1 && x < x2)
        {
            final = x - x1;
            printf("%d", final);
            y = y * 10;
            x1 = 0;
            x2 = 0;
            ++loop;
            goto again;
        }

        else
        {
            c = x2 - x1;
            if (x1 == x2)
            {
                x2 += y;
                goto again;
            }

            else if (c == y)
            {
                x1 += y;
                x2 += y;
                goto again;
            }
            else
            {
                printf("Error in Process");
                goto ending;
            }

        }
    }

    else
    {
        printf("0+error, extra long input");
    }
ending:
    return 0;
}

Flowchart:

I am a beginner in C-language and only know how to use If-else, Switch, Goto statements, with basic knowledge of how to integrate basic level loops. So please tell me what/where I am wrong instead of telling me how to use arrays because I don't know them, etc. This is my most complex code until now.
Now for Explanation of Coding,
I wrote X1 as the lower value and X2 as the upper value while first keeping a difference = Y(initially 10) between them.
Continuously increasing the value of X1 and X2 by Y(10) together simultaneously, I will arrive in between an intersection where my x(input) lies.
Eg-
x=568
then X1 and X2 will keep on increasing until they reach X1 = 560 and X2 = 570, then they will do Final = X(568) - X1(560) and print it.
since it can only happen for 32-digits long, so I wrote loop = 0 and only processing my main statement till loop is smaller than or equal to 32, otherwise printing "0+error".
then I put Y = Y * 10 every time the value was within my specified range.
It should give me the values like Last digit, then last 2 digits, then last 3 digits,etc. but after scanning the value, it isn't exciting at all.

A: Evaluating what you are attempting to do, I reworked your code to make it a bit more structured without utilizing arrays at that seemed to be something you wanted to avoid at this time.  However, these days, the use of the goto statement is usually avoided since functionality such as for loops, do/while loops, and while loops offer better clarity to coding.  With that in mind, following is a snippet of code that provides the functionality it looks like you want.
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int x, x1, x2, y = 10, counter = 0, last_digit;

    printf("Please enter a number: ");
    scanf("%d", &x);

    if (x < 0)          /* Just in case a negative integer is entered */
    {
        x = x * -1;
    }

    while (1)           /* Use a while loop with associated break statements to avoid goto and label statements */
    {
        x1 = 0;
        x2 = 10;
        counter += 1;

        while (1)
        {
            if (x >= x1 && x <= x2)
            {
                last_digit = x - x1;
                if (counter == 1)
                {
                    printf("The last digit is: %d\n", last_digit);
                }
                else
                {
                    printf("The next digit is: %d\n", last_digit);
                }
                break;
            }
            x1 += y;
            x2 += y;
        }

        x = x / 10;     /* Perform integer division by ten to get to the next digit in the entered number */

        if (x == 0)     /* Once all digits have been processed the outer while loop can be exited */
        {
            break;
        }

    }

    return 0;
}

Following are some key points.

*

*As noted, the loop process using goto statements is replaced by two while loops; one while loop nested inside another while loop.

*Utilizing integer division by ten, each digit can be ascertained and printed.

*Utilizing the nested while loops with break statements allows for a more compact program.

Utilizing this code snippet, following is a sample test from the terminal.
@Dev:~/C_Programs/Console/LastDigit/bin/Release$ ./LastDigit
Please enter a number: 479824385
The last digit is: 5
The next digit is: 8
The next digit is: 3
The next digit is: 4
The next digit is: 2
The next digit is: 8
The next digit is: 9
The next digit is: 7
The next digit is: 4

Back in the day, the goto statement had its place in coding, but today it is pretty much an artifact.
Give that a try and see if it meets the spirit of your project.


text:
Q: Unable to insert mutiple values to database I need help on this: I am trying to insert multiple values to database using a webpage as the interface. When I try to save I get the error

"Incorrect syntax near the keyword 'values'."

Below C# code for your reference.
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection("Data Source=INHRPSM1D7C;Initial Catalog=Controller_Forecast;Integrated Security=True;");

    protected void Page_Load(object sender, EventArgs e)
    {
    }

    public void refress()
    {
        TextBox1.Text = "";
        TextBox2.Text = "";
        TextBox3.Text = "";
        TextBox4.Text = "";
        TextBox5.Text = "";
        TextBox6.Text = "";
        TextBox7.Text = "";
        TextBox8.Text = "";
        TextBox9.Text = "";
        TextBox10.Text = "";
        TextBox11.Text = "";
        TextBox12.Text = "";
        DropDownList1.Text = "";
        DropDownList2.Text = "";
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        SqlCommand cmd = new SqlCommand("insert into Controller_Forecast(C1,C2,C3,C4,C5,C6,C7,C8,C9,C10,C11,C12,C13) values('" +
            TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text +
            "','" + TextBox4.Text + "','" + TextBox5.Text + "','" + TextBox6.Text +
            "','" + TextBox7.Text + "','" + TextBox8.Text + "','" + TextBox9.Text +
            "','" + TextBox10.Text + "','" + TextBox11.Text + "','" + TextBox12.Text +
            "','" + DropDownList1.Text + "','" + DropDownList2.Text + "','" +
            DropDownList3.Text + "'),values('" + TextBox13.Text + "','" +
            TextBox14.Text + "','" + TextBox15.Text + "','" +
            TextBox16.Text + "','" + TextBox17.Text + "','" +
            TextBox18.Text + "','" + TextBox19.Text + "','" +
            TextBox20.Text + "','" + TextBox21.Text + "','" +
            TextBox22.Text + "','" + TextBox23.Text + "','" +
            TextBox24.Text + "','" + DropDownList4.Text + "','" +
            DropDownList5.Text + "','" + DropDownList6.Text + "')",con);

        cmd.CommandType = CommandType.Text;
        try
        {
            con.Open();
            cmd.ExecuteNonQuery();
            Literal1.Text = "Data Updated Successfully!!!";
            con.Close();
            refress();
        }
        catch (Exception ex)
        {
            Literal1.Text = ex.Message;
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        refress();
        Literal1.Text = "";
    }
}

A: You can't do 2 sets of values like your trying to do with an INSERT statement. Your effectively doing:
INSERT INTO Controller_Forecast(C1,C2...)
VALUES(...loads of values...)
VALUES(...Loads of more values...)

This isn't valid. To insert 2 sets of data, which is what it looks like you're trying to do you can do 2 INSERT INTO statements or split the list of values with commas like so:
Multiple insert statements
INSERT INTO Controller_Forecast(C1,C2...)
VALUES(...your first set of values...)
INSERT INTO Controller_Forecast(C1,C2...)
VALUES(...your second set of values...)

Separating with commas
INSERT INTO Controller_Forecast(C1,C2...)
VALUES(...your first set of values...), (...second set of values...)

However, this seems inefficient and you'd be better off writing this in a store procedure and parameterising your values to avoid sql injection.

A: You have twice "values". Can you try this?

"insert into
  Controller_Forecast(C1,C2,C3,C4,C5,C6,C7,C8,C9,C10,C11,C12,C13)
  values('" +
              TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text +
              "','" + TextBox4.Text + "','" + TextBox5.Text + "','" + TextBox6.Text +
              "','" + TextBox7.Text + "','" + TextBox8.Text + "','" + TextBox9.Text +
              "','" + TextBox10.Text + "','" + TextBox11.Text + "','" + TextBox12.Text +
              "','" + DropDownList1.Text + "','" + DropDownList2.Text + "','" +
              DropDownList3.Text + "')",con);


text:
Q: Splitting a Java String return empty array? I have a String something like this
"myValue"."Folder"."FolderCentury";

I want to split from dot("."). I was trying with the below code:
String a = column.replace("\"", "");
String columnArray[] = a.split(".");

But columnArray is coming empty. What I am doing wrong here?
I will want to add one more thing here someone its possible String array object will contain spitted value like mentioned below only two object rather than three.?
columnArray[0]= "myValue"."Folder";
columnArray[1]= "FolderCentury";

A: Note that String#split takes a regex.
You need to escape the special char . (That means "any character"):
 String columnArray[] = a.split("\\.");

(Escaping a regex is done by \, but in Java, \ is written as \\).
You can also use Pattern#quote:

Returns a literal pattern String for the specified String.

String columnArray[] = a.split(Pattern.quote("."));
By escaping the regex, you tell the compiler to treat the . as the string . and not the special char ..

A: You must escape the dot.
String columnArray[] = a.split("\\.");

A: split() accepts an regular expression. So you need to skip '.' to not consider it as a regex meta character.
String[] columnArray = a.split("\\.");

A: While using special characters need to use the particular escape sequence with it.
'.' is a special character so need to use escape sequence before '.' like:
 String columnArray[] = a.split("\\.");

A: The next code:
   String input = "myValue.Folder.FolderCentury";
   String regex = "(?!(.+\\.))\\.";
   String[] result=input.split(regex);
   System.out.println(Arrays.toString(result));

Produces the required output:
[myValue.Folder, FolderCentury]

The regular Expression tweaks a little with negative look-ahead (this (?!) part), so it will only match the last dot on a String with more than one dot.


text:
Q: dropdown menu not fading away on mouseleave I would like to make the dropdown menu disappear on mouseleave. After I hover on the li, the drop down shows up and just stays there even if it isn't hovered. I had added mouseleave to #nav > li > a but it makes the dropdown disappear always not making it disappear only on mouseleave. so how can I fix this? I think the prob is on the jquery side.
Here is a fiddle http://jsfiddle.net/RXRBm/8/
JavaScript
$(document).ready(function () {
    $("#nav > li > a").on('mouseenter', function (e) {
        if ($(this).parent().has("ul")) {
            e.preventDefault();
        }
        if (!$(this).hasClass("open")) {
            // hide any open menus and remove all other classes
            $("#nav li ul").slideUp(350);
            $("#nav li a").removeClass("open");
            // open our new menu and add the open class
            $(this).next("ul").slideDown(350);
            $(this).addClass("open");
        } else if ($(this).hasClass("open")) {
            $(this).removeClass("open");
            $(this).next("ul").slideUp(350);
        }
    });
});

CSS
li {
    list-style:none;
 }
#nav {
    float: left;
    border-top: 1px solid #999;
    border-right: 1px solid #999;
    border-left: 1px solid #999;
}
#nav li {
    position:relative;
}
#nav li a {
    width: 200px;
    display: block;
    padding: 10.7px;
    background:#ccc;
    border-top: 1px solid #eee;
    border-bottom: 1px solid #999;
    border-width:0.2px;
    text-decoration: none;
    color: #000;
}
#nav li a:hover, #nav li a.active {
    background: #999;
    color: #fff;
}
#nav li ul {
    display: none;
    position:absolute;
    left:181px;
    top:-1px;
}
#nav li ul li a {
    padding: 10px;
    background:#C01F25;
    opacity:0.95;
    border-bottom: 0.1px solid red;
}

A: Demo
$("#nav>li").on('mouseleave',function(){
   $(this).children().eq(1).hide();
});