Linked List Head Dynamic Allocation -- C

Question: I am working on a small learning project in C but am having troubles implementing a head node that will hold the first data value of the data set. I am supposed to take an unsorted linked list and use it to implement a sorted linked list. It should be split into two functions like the example below.
My problem arises when allocating memory for the head pointer node on the heap. It always seems to make an extra head node with a data value of 0 (0 is not in the data set, but potentially could be) when using malloc.
    struct node* create_sorted_list(struct node *head)
    {
       struct node * curr = head;
       struct node * sorted_head = malloc(sizeof(struct node));

       while(curr != NULL){
          add_item_sorted(sorted_head, curr->data);
          curr=curr->next;
       }
       return sorted_head;
    }

    struct node* add_item_sorted(struct node *sorted_head, int data)
    {
       struct node * curr = sorted_head;
       struct node * newN;
       while(curr->next != NULL){

          if(data > curr->next->data){
             curr=curr->next;
          }
          else{
             newN = malloc(sizeof(struct node));
             newN->data = data;
             newN->next = curr->next;
             curr->next = newN;
             return sorted_head;
          }
       }
       newN = malloc(sizeof(struct node));
       curr->next = newN;
       newN->data = data;
       return sorted_head;
    }

    int main(int argc, char *argv[])
    {
        ......
        struct node * sorted_head = create_sorted_list(head);

        //head in this case comes from an unsorted linked list with the
        //same data values. Using head linked list to make sorted_head.
    }

My output is something like this : 0 -> 56 -> 35 -> 98 -> end
When it should be:                 56 -> 35 -> 98 -> end
I have reason to believe that the extra node is a result of one to many calls of malloc, however I cannot find the right solution.
Any help is appreciated. Thanks Guys.
Answer: I believe it is happening because in your add_item_sorted function, you are accessing the list as if there is a dummy head node (you are starting with checking cur->next->data, where you should be actually checking cur->data).
When you malloc a node, it might be holding a 0 or any other value in its data field. So, in your case, sorted_head is holding 0 in its data field. Now, according to your example, you try to insert the value 56. In add_item_sorted function, you first try to access cur->next->data, which is NULL. So, a new node is inserted after this sorted_head.
Answer: Function create_sorted_list is already wrong.
In general head can be equal to NULL. However there is created sorted_head in the function that is not equal to NULL.
struct node* create_sorted_list(struct node *head)
    {
       struct node * curr = head;
       struct node * sorted_head = malloc(sizeof(struct node));
       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
       while(curr != NULL){
           //...
       }
       return sorted_head;
    }

Moreover its data members are not initialized. So if function add_item_sorted will be called for such node then access to the data member next will result in undefined behavior of the program.
  struct node* add_item_sorted(struct node *sorted_head, int data)
    {
       struct node * curr = sorted_head;
       struct node * newN;
       while(curr->next != NULL){
             ^^^^^^^^^^^

And at least you have to write
  while(curr != NULL){
      sorted_head = add_item_sorted(sorted_head, curr->data);
      ^^^^^^^^^^^^^^^

The functions can be written as it is shown in the following demonstrative program
#include <stdio.h>
#include <stdlib.h>

struct node
{
    int data;
    struct node *next;
};

struct node* add_item( struct node *head, int data )
{
    struct node *tmp = malloc( sizeof( struct node ) );
    tmp->data = data;
    tmp->next = head;

    return tmp;
}

struct node* add_item_sorted( struct node *sorted_head, int data );

struct node * create_sorted_list( struct node *head )
{
    struct node *sorted_head = NULL;

    for ( ; head != NULL; head = head->next )
    {
        sorted_head = add_item_sorted( sorted_head, head->data );
    }

    return sorted_head;
}

struct node* add_item_sorted( struct node *sorted_head, int data )
{
    if ( sorted_head == NULL || !( sorted_head->data < data ) )
    {
        struct node *tmp = malloc( sizeof( struct node ) );

        tmp->data = data;
        tmp->next = sorted_head;
        sorted_head = tmp;
    }
    else
    {
       struct node *current = sorted_head;

        while ( current->next != NULL && current->data < data )
        {
            current = current->next;
        }

        struct node *tmp = malloc( sizeof( struct node ) );
        tmp->data = data;
        tmp->next = current->next;
        current->next = tmp;
    }

    return sorted_head;
}

void display( struct node *head )
{
    for ( ; head != NULL; head = head->next )
    {
        printf( "%d ", head->data );
    }
    printf( "\n" );
}

#define N   10

int main( void )
{
    struct node *head = NULL;

    for ( int i = 1; i <= N; i++ ) head = add_item( head, i );

    display( head );

    struct node *sorted_head = create_sorted_list( head );
    display( sorted_head );

    return 0;
}

Rge program output is
10 9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 10

Comment: Thanks much! I tried setting the sortedList head to NULL in create_sorted_list before posting this but found always ran into seg faults. Any chance you could elaborate on the "undefined behavior" that my example code was running into?
Comment: @Lamar As data member next is not initialized then the condition in the loop while(curr->next != NULL){ can have a random value.
Comment: I see! Thanks for the clarification


Find the Numbers which can be visited

Question: We have a number from 1 to N in a row.We chooses the first M numbers and moves them to the end of the queue. Now, we goes to the  at the first position in the row and mark it visited. we then notes this  index (say k) , and goes to the kth position in the row.If a number is visited we end our game.
We have to find the total number of numbers that are visited.
For Ex N= 5  m=2
3 4 5 1 2
we go to 1 number and from there 3rd Number i.e 5 and the 5th Number i.e 2 and then 2nd Number i.e  4 and i.e. 4 number i.e 1
Ex = 4 m=2
3 4 1 2
we go to 1 number i.e 3 and there to 3rd number i.e 1 and game stops.
Comment: Your grammar makes me read this is Smeagol's voice from LOTR.
Answer: The appropriate mathematical tool for analyzing this situation is permutation theory, and in the language of permutation theory the problem is:

On the set $\{1,2,\ldots,N\}$ iterate the $N$-cycle $(1\;2\,\cdots\, N)$ $M$ times. In the resulting permutation, what is the length of the cycle that contains $1$?

By symmetry, all cycles in the result must be equally long, so the answer must be a divisor of $N$, and it comes down to how many different cycles the result contains. It turns out that the number of cycles is the greatest common divisor of $N$ and $M$, so the number you're looking for is
$$ \frac{N}{\gcd(N,M)} $$
which agrees with your examples: $\frac{5}{\gcd(5,2)}=\frac51=5$ and $\frac{4}{\gcd(2,4)}=\frac42=2$.

Another (?) way to look at it is modular arithmetic: What is the smallest (positive) number $k$ of jumps by $M$ one can do such that the total distance jumped -- that is, $kM$ -- is a multiple of $N$? This $k$ must be one that contributes all of the prime factors in $N$ that are not already in $M$ (and nothing more, or it wouldn't be the smallest one). Since the prime factors that $N$ and $M$ have in common are exactly the content of $\gcd(N,M)$, we can get the rest of them by dividing the common factors out of $N$, and again the result is
$$ \frac{N}{\gcd(N,M)} $$
Comment: could you give me some more explanation or a link
Comment: just curious what if m varies i.e from `1<=Mi<=N` we find have  for all values i.e summation of  all Mi

Find the Numbers which can be visited


Google calendar php API all day events missing/invisible for some users

Question: Over the last few days some of our users (not all) have been unable to see all day calendar events that were created via the google api.
They CAN see them on either their phone calendar, or when viewing inbox and clicking the right hand calendar icon, or selecting to view 'Schedule' instead of 'Day' or 'Week'
Google has no explanation.
Edit:
Here is my answer..

The solution mentioned across this and other questions is as follows:
When creating and all day event - instead of having the same start and
  end date, you should now have the end date as the following day.
i.e. instead of Start Date :2019-06-05 and End Date: 2019-06-05, the
  end date should be 2019-06-06
This can be seen here: https://stackoverflow.com/a/55851521/901666
Answer: When creating and all day event - instead of having the same start and end date, you should now have the end date as the following day.
i.e. instead of Start Date :2019-06-05 and End Date: 2019-06-05, the end date should be 2019-06-06
This can be seen here: https://stackoverflow.com/a/55851521/901666


Can't install YugabyteDB in kubernetes cluster

Question: [Question posted by a user on YugabyteDB Community Slack]
I have tried setting up YugaByte in Kubernetes and it keeps erroring out during installation. Can someone help here?
I have a Digital Ocean Kubernetes cluster and I am trying to install YugaByteDB over there. I am using Helm
I tried deploying yugabyte into Minikube in my local and it worked.
But when I am trying to do similar at Kubernetes it goes unresponsive for a while and then error out
With this command:
helm install yb-demo yugabytedb/yugabyte --namespace yb-demo --wait

It gives me this error: Error: INSTALLATION FAILED: timed out waiting for the condition.
I am following this: https://docs.yugabyte.com/preview/deploy/kubernetes/single-zone/oss/helm-chart/
I can see the pods from the cluster but they are reporting sync issues. Running:
kubectl get svc -n yb-demo

kubectl get pods -n yb-demo

Answer: It looks like you hit a node count limit on your cluster, causing one master to go into pending status. That is why your helm deployment didn't complete.
You can customize the cores/mem allocated to each master at https://github.com/yugabyte/charts/blob/8ae394ed699bf55286dbe732b074023b7a3b55a5/stable/yugabyte/values.yaml#L21 if you are unable to increase resources on your k8s cluster.
All 3 masters need to start up for initialization of the cluster, though one of them can fail later.

Can’t install YugabyteDB in kubernetes cluster


$\frac{1}{x+1} + \frac{2}{x^2+1} + \frac{4}{x^4+1} + \cdots $ up to $n$ terms in terms of $x$ and $n$.

Question: There's a series which I can't seem to find a way to sum. Any help would be highly appreciated. It goes as follows      $$\frac{1}{x+1} + \frac{2}{x^2+1} + \frac{4}{x^4+1} + \cdots $$ up to $n+1$ terms.   The sum is to be expressed in terms of $x$ and $n$. I tried setting a formula for the $n$-th term and setting it into a difference but ran into a dead end.
Comment: Do you mean $\frac{1}{x+1} + \frac{2}{x^2+1}+\frac{4}{x^4+1}+\ldots$ or $\frac{1}{x} + 1 + \frac{2}{x^2} + 1 + \frac{4}{x^4}+1+\ldots$?
Comment: The first series is a bit difficult and the second series is just a geometric series.
Answer: Hint:
If $f(x)=\dfrac1{1+x}+\dfrac2{1+x^2}+\dfrac4{1+x^4}+\cdots+\text{ up to } n+1\text{ terms}$
$$\dfrac1{1-x}+f(x)=\dfrac1{1-x}+\dfrac1{1+x}+\left(\dfrac2{1+x^2}+\dfrac4{1+x^4}+\cdots+\text{ up to } n+1\text{ terms}\right)$$
$$=\dfrac2{1-x^2}+\dfrac2{1+x^2}+\left(\dfrac4{1+x^4}+\cdots+\text{ up to } n\text{ terms}\right)$$
$$=\dfrac4{1-x^4}+\dfrac4{1+x^4}+\left(\dfrac8{1+x^8}+\cdots+\text{ up to } n-1\text{ terms}\right)$$
Comment: But that would give me x^2 -1 in the denominator
Comment: @Abcd, Please find the updated answer
Comment: Thanks a lot @lab bhattacharjee
Comment: Nice ! How did you find the trick ?
Answer: By induction, it is pretty clear that
$$ x^{2^{n+1}}-1 = (x-1)\prod_{k=0}^{n} \left(x^{2^k}+1\right) \tag{A}$$
and by applying $x\cdot\frac{d}{dx}\log(\cdot)$ to both sides we have:
$$\frac{2^{n+1}x^{2^{n+1}} }{x^{2^{n+1}}-1}=\frac{x}{x-1}+\sum_{k=0}^{n}\frac{2^k x^{2^k}}{x^{2^k}+1} \tag{B}$$
and by replacing $x$ with $\frac{1}{z}$:
$$\frac{2^{n+1}}{1-z^{2^{n+1}}}=\frac{1}{1-z}+\sum_{k=0}^{n}\frac{2^k}{z^{2^k}+1}. \tag{C}$$
Answer: A supplement to the nice answer from @labbhattacharjee. We see an example of telescoping based upon
\begin{align*}
\color{blue}{\frac{2^k}{1-x^{2^k}}+\frac{2^k}{1+x^{2^k}}}
=\frac{2^k\left(1+x^{2^k}\right)+2^k\left(1-x^{2^k}\right)}{\left(1-x^{2^k}\right)\left(1+x^{2^k}\right)}
&\color{blue}{=\frac{2^{k+1}}{1-x^{2^{k+1}}}}\tag{1}
\end{align*}

We obtain according to (1)
  \begin{align*}
\color{blue}{\sum_{k=0}^n\frac{2^k}{1+x^{2^k}}}&=\sum_{k=0}^n\left(\frac{2^{k+1}}{1-x^{2^{k+1}}}-\frac{2^k}{1-x^{2^k}}\right)\\
&=\sum_{k=0}^n\frac{2^{k+1}}{1-x^{2^{k+1}}}-\sum_{k=0}^n\frac{2^k}{1-x^{2^k}}\\
&=\sum_{k=1}^{n+1}\frac{2^{k}}{1-x^{2^{k}}}-\sum_{k=0}^n\frac{2^k}{1-x^{2^k}}\tag{2}\\
&\color{blue}{=\frac{2^{n+1}}{1-x^{2^{n+1}}}-\frac{1}{1-x}}\tag{3}
\end{align*}
Comment:

In (2) we shift the index of the left-hand sum to start with $k=1$.
In (3) we do the telescoping.


Intersection of two hyperbolas in polar coordinates.

Question: I want to find the intersections of two hyperbolas in polar coordinates. One of their foci coincides, we use this as the pole. (The right focus of the left hyperbola is the same as the left focus of the right hyperbola, as shown on the picture).
I'm trying to solve the following equation to get their intesections:
$$r = \frac{p}{1\mp e \cos \varphi}$$
$$\frac{p_{0}}{1 -  e_{0} \cos \varphi} = \frac{p_{1}}{1 +  e_{1} \cos \varphi}$$
Hyperbolas can intersect in at most 4 points, but this equation only has two solutions. Where am I going wrong, what am I misunderstanding? How do I find the 4 possible intersections?
Answer: Indeed, there is an apparent paradox as can be seen on the following example (similar to yours) with two hyperbolas (featured with their asymptotes) :
$$r=\frac{p_0}{1 -  e_0 \cos \varphi} \ \text{and} \  r=\frac{p_1}{1 -  e_1 \cos \varphi}\tag{1}$$
with $$e_0=1.5, e_1=2, \ p_0=1, \ p_1=-0.5\tag{2}$$

They have four points of intersection whereas equation
$$\frac{p_0}{1 -  e_0 \cos \varphi} = \frac{p_1}{1 -  e_1 \cos \varphi}\tag{3}$$
which is equivalent to $6-11 \cos(\varphi)=0$
has only two solutions $\varphi \in (0,2\pi]$.
Remark : Had we chosen any other set of values for $e_0,e_1,p_0,p_1$, we get an equation $a \cos \varphi+b=0$ (similar to (3)) which has at most two solutions on $(0,2 \pi]$.
So why couldn't we get 4 solutions ? What hasn't been taken into account ?
It is due to the fact that, in polar coordinates, a same point can be represented in two ways : by $(r,\varphi)$ or by $\color{red}{(-r,\varphi+\pi)}.$
Therefore, to equation (3) we must add equation :
$$\frac{p_0}{1 -  e_0 \cos \varphi} = \color{red}{(-)}\frac{p_1}{1 -  e_1 \cos \color{red}{(\varphi+\pi)}}\tag{4}$$
which, in our case, will provide the 2 other solutions.
Remark : please note that the form of the second function in (1) is different from yours : it has $p_1<0$ and a minus sign in the denominator.
Comment: Oh, I get it, thank you so much!
Comment: This issue was also addressed [here](https://math.stackexchange.com/q/3245000/305862)
Answer: The equations have 4 solutions.
Radius vectors have to be considered separately.
Solving separately for the four polar angles we have symmetrical inverse cosine functions for each combination:
$$r_0=\frac{p_{0}}{1 -  e_{0} \cos \varphi} ,~ r_2=\frac{p_{1}}{1 -  e_{1} \cos \varphi},$$
$$ \cos \varphi_{0+1}=\frac{1-p_0/r_0}{e_0},~ \cos \varphi_{1+0}=\frac{1-p_1/r_1}{e_1}.$$


How do I un-tame a wolf through NBT?

Question: On any given server, the need to untame a wolf (without killing it) for whatever reason arises eventually.
However, upon attempting to do this on my own test server with the below command, nothing happened. The wolf was still tame to me, and would refuse to let go.
/entitydata @e[type=Wolf,r=5] {Owner:,OwnerUUID:}

What am  I missing or doing wrong here?
Answer: In order for a change in owner to be considered, the OwnerUUID tag must not have an empty value. However, providing it a correctly-formatted UUID will cause it to be tamed to whoever has that UUID (even if nonexistent). If you provide it with an invalid format, it will instead become wild as though it were never tamed:
/entitydata @e[type=Wolf,r=5] {OwnerUUID:"blah"}

The Owner tag is deprecated, and is ignored if OwnerUUID is specified.

How do I un-tame a wolf through NBT?


Redirect aspx to new page but with message and wait?

Question: I want to redirect to a new page, but I'd like to show a message and have a small waiting period so users can read it:
I know I can do this:

But How can I show the message and wait?
Thanks.
Answer: Instead of using server-side code, you can do it in html, with meta refresh:

  <title> Redirect </title>
  <meta http-equiv="refresh" content="60;URL='http://foo/new.aspx'"/>

You will be redirected in 60 seconds

You can change 60 in the content attribute of the meta tag into the seconds you want the user to wait.
Answer: You can use client-side technology, meta tag for example

<TITLE>redirect</TITLE>
<META HTTP-EQUIV="refresh"
CONTENT="10;URL=http://<URL>">

[Your message here]

Answer: Have you tried using a meta refresh tag?
Documentation can be found here: http://en.wikipedia.org/wiki/Meta_refresh
Basically, you put a meta refresh tag in the  section of your HTML and specify a wait time along with a URL.
e.g.
<meta http-equiv="refresh" content="15;URL='http://www.something.com/page2.html'">

In the above example, the page will wait 15 seconds, and then redirect to http://www.something.com/page2.html.
So, you could create a page with your message on it, and put a meta refresh in the header of it.  After the set period of time, it will "refresh" to new.aspx.
e.g.

    <title>Redirecting</title>
    <meta http-equiv="refresh" content="15;URL='new.aspx'">

Thanks for visiting our site, you're about to be redirect to our next page.  In the meantime, here's an interesting fact....

Answer: you can pass the message and the time to wait in query string
Response.Redirect("new.aspx?Message=Your_Message&Time=3000")

in the Page_Load of new.aspx you can catch the parameters
string msg = Request["Message"]
string time = Request["Time"]

You need the user wait x seconds to see the message?
if yes, you will need to do it by javascript.
First, create a javascript function to show the message
function ShowMessage(msg) {
        alert(msg);
    }

then, in code behind of the new.aspx, get the parameters and call the javascript function
protected void Page_Load(object sender, EventArgs e)
    {
        string msg = Request["Message"].ToString();
        string tempo = Request["Time"].ToString();
        string script = String.Format(@"setTimeout(""ShowMessage('{0}')"", {1})", msg, tempo);
        ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "key", script, true);
    }

It will show the message after 3 seconds.


Do I lose my BiA bonus if a crew member gets knocked out?

Question: In WoT, the Brothers-In-Arms crew perk gives all crew members in your tank a 5% skill bonus, but only if it is trained to 100% on all of them.
If a crew member is knocked out in a battle and I don't use a first aid kit to revive them, does the rest of the crew lose that 5% bonus for the rest of the battle?
 I know that when the Commander is knocked out, the rest of the crew loses their 10% Commander bonus, but does the same apply to the BiA perk?
Thanks!
Answer: No, Brother-In-Arms stays active, even when a crew member gets knocked out.
Source: Wargaming wiki
Comment: Does it stay active if only one crew member is not KOed, though? I know that's an extreme case, but I'm curious.
Comment: Yes, it doesstay active


How to list all cassandra tables

Question: There are many tables in cassandra database, which contain column titled user_id. The values user_id are referred to user stored in table users. As some users are deleted, I would like to delete orphan records in all tables that contain column titled user_id.
Is there a way to list all tables using CassandraSQLContext or any other built-in method or custom procedure in order to avoid explicitly defining the list of tables?
Answer: From cqlsh execute describe tables;
Comment: For the sake of completeness, run `use my_keyspace;` first.
Comment: This is the current and easiest way to list all tables
Comment: Is it possible to alphabetize the output?
Comment: worked for me, make sure to perform `use keyspace_name;` otherwise you will get result for All keyspaces.
Answer: There are system tables which can provide information about stored keyspaces, tables, columns.
Try run follows commands in cqlsh console:

Get keyspaces info
SELECT * FROM system.schema_keyspaces ;

Get tables info
SELECT columnfamily_name FROM system.schema_columnfamilies WHERE keyspace_name = 'keyspace name';

Get table info
SELECT column_name, type, validator FROM system.schema_columns WHERE keyspace_name = 'keyspace name' AND columnfamily_name = 'table name';

Since v 5.0.x
Docs

Get keyspaces info
SELECT * FROM system_schema.keyspaces;

Get tables info
SELECT * FROM system_schema.tables WHERE keyspace_name = 'keyspace name';

Get table info
SELECT * FROM system_schema.columns
WHERE keyspace_name = 'keyspace_name' AND table_name = 'table_name';

Since v 6.0
Docs

Get keyspaces info
SELECT * FROM system_schema.keyspaces

Get tables info
SELECT * FROM system_schema.tables WHERE keyspace_name = 'keyspace name';

Get table info
SELECT * FROM system_schema.columns
WHERE keyspace_name = 'keyspace_name' AND table_name = 'table_name';
Comment: For my version of cassandra `[cqlsh 5.0.1 | Cassandra 3.11.3 | CQL spec 3.4.4 | Native protocol v4]` getting keyspace info works with `SELECT * FROM system_schema.keyspaces`
Comment: And for getting tables info `SELECT * FROM system_schema.tables WHERE keyspace_name = 'keyspace name'`
Comment: Did it change from `system.schema_keyspaces` to `system_schema.keyspaces` at some point?  Otherwise you may have a typo in the first set of bullet points up there (I would edit it, but I don't have the background info to do so correctly I don't think).
Answer: desc keyspaces;  // list all databases/collections names
use anyKeyspace;  // select any database
desc tables;      // list all tables in collection/ database

Comment: Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes.
Answer: You can achieve what you want using datastax core driver and cluster metadata. Here is an example which will list all the tables in your keyspace and columns in each table:
 Cluster cluster= Cluster.builder().addContactPoint(clusterIp).build();
    Metadata metadata =cluster.getMetadata();

   Collection<TableMetadata> tablesMetadata= metadata.getKeyspace("mykeyspacename").getTables();
    for(TableMetadata tm:tablesMetadata){
        System.out.println("Table name:"+tm.getName());
        Collection<ColumnMetadata> columnsMetadata=tm.getColumns();
        for(ColumnMetadata cm:columnsMetadata){
            String columnName=cm.getName();
            System.out.println("Column name:"+columnName);
        }
    }

Answer: For DSE. If later release check for system_schema keyspace.
from
cqlsh > desc keyspaces;

spark_system  system_schema  "OpsCenter"  cfs_archive         "HiveMetaStore"
system_auth    cfs          demobeta            dsefs
dse_security  hypermedia     dse_leases   system_traces       dse_perf
solr_admin    system         system_distributed  dse_system

if you see 'system_schema' then the metadata for tables is in this keyspace.
cqlsh>use system_schema;

cqlsh>select keyspace_name,table_name from tables where keyspace_name = 'system';

Comment: `system` keyspace isn't DSE-specific - it's a core Cassandra functionality... The schema representation is different between Cassandra versions, so the best way is to either use `cqlsh`'s `DESCRIBE KEYSPACES`, or access via metadata as pointed by @zoran jeremic
Comment: alex, never meant to imply system keyspace is specific to DSE However some are . The schema tables were moved out of the 'system' keyspace so the tables  system keyspace are not in that keyspace any longer .. this is a specific answer for DSE not Open Source Cassandra. Was referring to the metadata for DSE only . desc tables; as posted is really easy way to get a table list . comment was around the metadata for DSE not Open Source . If you are looking for those system tables not in DSE . if trying to generate a table list in your application sometimes can not run a desc but need to run cql...
Comment: system keyspaces are specific for Cassandra. The difference that you describe is difference between Cassandra 2.x & 3.x (See https://dba.stackexchange.com/questions/134185/migration-from-cassandra-2-x-to-3-x-schema-keyspaces-table-is-gone-how-do-you). DSE specific keyspaces usually have the `dse` prefix, like, `dse_security`, `dse_leases`, etc. (although `cfs` & `solr_admin` don't follow this convention). Overall, if you need to access this data programmatically, then it's better to use drivers that support `Metadata` - it's then version agnostic.
Answer: To list all the tables (only the table names),
DESC tables;
To list all the tables and the schemas (CQL creation statements),
DESC {$KEYSPACE_NAME} whereas {$KEYSPACE_NAME} is the name of the keyspace.
I am using Apache Cassandra 3.11.4 binary package downloaded from the official site:
cql> show version;
[cqlsh 5.0.1 | Cassandra 3.11.4 | CQL spec 3.4.4 | Native protocol v4]

The Apache Cassandra's CQL reference is here: https://cassandra.apache.org/doc/cql3/CQL-3.0.html
Answer: try running the following query:
cqlsh> describe keyspace <keyspace_name>;

Comment: cqlsh: describe keyspace ;
Answer: Just connect CQLSH and try below commands
describe tables; or
DESC SCHEMA ;
Also you can 'desc keyspaces;' and 'use keyspace;' where you want to see the tables with 'describe tables;'
Comment: describe schema is not CQL command, but `cqlsh` command...
Comment: @AlexOtt  Yes, I meant after connecting cqlsh.

How to list all cassandra tables


.Net Forms Authentication

Question: I'm developing a website in mvc2, and i'm using the .net Authentication. How can i do to change my login authorization to use email and password.
thanks
Answer: Inside your controller action which emits the authentication cookie just check if the mail matches the password and use the email as username for the authentication cookie:
<code>[HttpPost]
public ActionResult Login(string email, string password)
{
    // TODO: query your membership provider and verify if the given email
    // matches the password and if they match emit the authentication cookie
    // using the email as username

}
</code>

.Net Forms Authentication


@GlideOption adding/extending RequestBuilder to customize listener and achieve functional approach in Java 8

Question: Glide Version: 4.9.0
I tried to customized the RequestBuilder class, to have a customized builder, in this case I want to customize RequestBuilder#addListener function to have a @FunctionalInterface or Function0<R> as argument and to be functional for Java 8.
I've tried to read documentation about @GlideExtensions here & the difference between:

@GlideOption: for adding customized RequestOptions as long first parameter is extended from BaseRequestOptions<*> in this case RequestBuilder<TranscodeType> extends BaseRequestOptions<RequestBuilder<TranscodeType>>
@GlideType: Definitely creating different type of drawable, not doing much of configuration, therefore I didn't try it.

Due to RequestListener doesn't have @FunctionalInterface annotation, I ended-up using both Kotlin & Java 8 to achieve the lambda-like parameter function.
I've created a SafeGlideApp class to handle context related problem using RequestManager inside onCreate & checking if the activity isFinishing
class SafeGlideApp {

    companion object {

        private lateinit var rm: RequestManager
        private lateinit var target: ViewTarget<ImageView, Drawable>

        /**
         * This is mandatory to setup inside onCreate() on any Activity/Fragment
         * @param Activity receive the current activity if not finishing
         */
        @JvmStatic
        fun init(activity: Activity) {
            rm = Glide.with(activity)
        }

        @JvmStatic
        fun destroy() {
            target.clearOnDetach()
            rm.pauseAllRequests()
            rm.clear(target)
        }

        @JvmStatic
        fun with(activity: Activity, safeAction: (RequestManager) -> ViewTarget<ImageView, Drawable>) {
            init(activity)
            activity.safeRunnable {
                check(::rm.isInitialized)
                target = safeAction(rm)
            }
        }
    }
}

Here's my desired functions to call custom listener on SafeGlideApp.
Activity.java
SafeGlideApp.with(this, requestManager -> requestManager
                        .load(url)
                        .listener(
                                Helpers.wrapper(() -> doSomething()),
                                Helpers.wrapper(() -> doSomething())
                        )
                        .into(imageView)
);

In order to have an interop between kotlin-java, I created this wrapper inspired by everyone in stackoverflow. So, in the invocation calls, cleaner and simplier.
Helpers.java
    /**
     * This lambda wrapper function takes nothing as argument and return Unit
     * E.g: f(wrapper(() -> doSomethingVoid()))
     *
     * @param callable
     * @return Unit
     */
    public static Function0<Unit> wrapper(Runnable callable) {
        return () -> {
            callable.run();
            return Unit.INSTANCE;
        };
    }

And here's my approach so far to customize the RequestBuilder.
My generic listener class
CustomListener.kt
fun <T : Any> makeLoadingRequestListener(
        failedAction: (() -> Unit)?,
        readyAction: (() -> Unit)?
): RequestListener<T> = object : RequestListener<T> {
    override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<T>?, isFirstResource: Boolean): Boolean {
        failedAction?.invoke()
        return false
    }

    override fun onResourceReady(resource: T, model: Any?, target: Target<T>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {
        readyAction?.invoke()
        return false
    }
}

Troubleshooting

Using explicit type Drawable will have a compile-error:

e: [kapt] An exception occurred: java.lang.IllegalArgumentException:
   @GlideOption methods must take a BaseRequestOptions<?> object as
   their first parameter, but the first parameter in
   MyAppGlideExtension#listener(RequestBuilder, Unit, Unit) is
   RequestBuilder<Drawable>

Here's my extension class MyGlideExtension.kt
@GlideExtension
open class MyAppGlideExtension private constructor() {

    companion object {

        @JvmStatic
        @GlideOption
        fun listener(
                options: RequestBuilder<Drawable>,
                failedAction: () -> Unit,
                readyAction: () -> Unit
        ): BaseRequestOptions<Drawable> {
            return options.addListener(makeLoadingRequestListener<Drawable>(
                    failedAction = failedAction,
                    readyAction = readyAction
            ))
        }
    }
}

As stated in this issue #3552 & #4030. FlickrGlideExtension example is using Java. Also, the author stated to use ? wildcard in Kotlin, in fact that's not supported in Kotlin.

I've also try the java approach like this, and also have a compile-error

@GlideExtension
public final class MyGlideExtension {

    private MyGlideExtension GlideExtension() {
        return this;
    }

    @GlideOption
    public static BaseRequestOptions<?> test(RequestBuilder<?> requestBuilder,
                                             Function0<Unit> failed,
                                             Function0<Unit> ready) {
        return requestBuilder.listener(new RequestListener<Object>() {
            @Override
            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Object> target, boolean isFirstResource) {
                return false;
            }

            @Override
            public boolean onResourceReady(Object resource, Object model, Target<Object> target, DataSource dataSource, boolean isFirstResource) {
                return false;
            }
        });
    }
}

Unfortunately, I didn't know how to use projection to solve this issue out-projected type prohibits for RequestBuilder#addListener function

@GlideExtension
open class MyAppGlideExtension private constructor() {

    companion object {

        @JvmStatic
        @GlideOption
        fun listener(
                options: RequestBuilder<*>,
                failedAction: () -> Unit,
                readyAction: () -> Unit
        ): BaseRequestOptions<*> {
            return options.addListener(makeLoadingRequestListener<Object>(
                    failedAction = failedAction,
                    readyAction = readyAction
            ))
        }
    }
}

Manually extending RequestManager & RequestBuilder

class CustomRequestManager(
        glide: Glide, lifecycle: Lifecycle,
        treeNode: RequestManagerTreeNode, context: Context
) : RequestManager(glide, lifecycle, treeNode, context) {

    override fun load(string: String?): CustomRequestBuilder<Drawable> {
        return super.load(string) as CustomRequestBuilder<Drawable>
    }
}

class CustomRequestBuilder<TranscodeType : Any>(
        glide: Glide,
        requestManager: RequestManager,
        transcodeClass: Class<TranscodeType>,
        context: Context
) : RequestBuilder<TranscodeType>(glide, requestManager, transcodeClass, context) {

    fun listener(failedAction: () -> Unit, readyAction: () -> Unit): RequestBuilder<TranscodeType> {
        return addListener(makeLoadingRequestListener<TranscodeType>(
                failedAction = failedAction,
                readyAction = readyAction
        ))
    }
}

but failed when casting GlideApp.with(this) as CustomRequestManager and throws compile-error: GlideRequest cannot be casted to CustomRequestManager
Last but not least.

Is there any approach possible to extends/customize RequestBuilder class?
Or is this possible creating a helper class without extending RequestBuilder to use
& wrap RequestListener<R> interface to be functional?
Comment: edited: I think, I don't have to go through all of this and thinks an alternative options:

1. fork the glide, and create different GlideExtensions features
2. just migrate to kotlin (this will definitely match my desired to be functional method)
3. creating a wrapper method (static) to receive a lambda that return a `RequestListener`
Comment: What is the error for? "I've also try the java approach like this, and also have a compile-error"
Comment: @TWiStErRob `addListener(RequestListener>) cannot be applied to (RequestListener)`
Comment: That's good, I think. It sounds like the annotation processor passed, but your code had an error in it because of wrong type.
Answer: I think you need to take the error message literally:
    @JvmStatic
    @GlideOption
    fun listener(
            options: RequestBuilder<Drawable>,
            failedAction: () -> Unit,
            readyAction: () -> Unit
    ): BaseRequestOptions<Drawable> {

to
    @JvmStatic
    @GlideOption
    fun listener(
            options: RequestBuilder<*>, // no explicit type, wildcard only (=== Java's <?>)
            failedAction: () -> Unit,
            readyAction: () -> Unit
    ): BaseRequestOptions<*> {

to
    @JvmStatic
    @GlideOption
    fun listener(
            options: BaseRequestOptions<*>, // not a subtype, exactly that type
            failedAction: () -> Unit,
            readyAction: () -> Unit
    ): BaseRequestOptions<*> {

and then you can probably cast the options parameter to RequestOptions or the generated class' type, if necessary.
Comment: yes, I've also tried using generic `BaseRequestOptions<*>` to `RequestBuilder` see this [image here](https://imgur.com/a/iB0pS0w)
Comment: hmm, based on https://stackoverflow.com/a/40139018/253468, you might need `@JvmSuppressWildcards`


Issue in Parcelable implementation in Android Studio 1.2.2 Upgrade

Question: My Parcelable Class :
public class Category  implements Parcelable{
    int id;
    String name;
    Department department;
    @Override
    public int describeContents() {
        return 0;
    }
    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(id);
        dest.writeString(name);
        dest.writeParcelable(department, 10);

    }

    public static final Parcelable.Creator<Category> CREATOR = new Parcelable.Creator<Category>() {
        public Category createFromParcel(Parcel in) {
            return new Category(in);
        }

        public Category[] newArray(int size) {
            return new Category[size];
        }
    };

    public Category(Parcel in){

        id=in.readInt();
        name=in.readString();
        department= in.readParcelable(department.getClass().getClassLoader());

    }

When i send object of category class to other activity, then writeToparcel() and createFromParcel() method got called, I observed NullPointerException at
department= in.readParcelable(department.getClass().getClassLoader());

But while debugging i had checked that in writeToParel() method department object is stored correct, but how that is not returned back, in createFromParcel() , Same code is running fine in Android Studio 1.1 .
Currently I had changed my implementation  code like that :
@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeInt(id);
    dest.writeString(name);
    dest.writeParcelable(department, Constants.PARCELABLE_DEPARTMENT);
    dest.writeInt(department.getId());
    dest.writeString(department.getName());
}

public Category(Parcel in){
    id=in.readInt();
    name=in.readString();
    department=new Department(in.readInt(),in.readString());

}

Now, the code is working fine , but now i need to create extra department object, which i think is not good way .
Does any one have any solution regarding the problem ?
Comment: Does department implement the parcelable interface?
Answer: department.getClass().getClassLoader()

This is what throws the error. department == null and you're trying to fetch it's class. Therefore it throws an NPE.
Instead, fetch the class loader via the class object:
Department.class.getClassLoader()

Comment: department is not null, i had debugged during writingToparcle() call.
Comment: @user4886956 how can `department` be not null in a constructor? :)
Comment: You are right. it will be null unless it's been assigned some memory reference .


what is the dimension of the image of linear mapping $L(u,v,w)=(u-v,v-w,w-u)$?

Question: let $U,V,W$ be subspace of finite dimensional vectorspace P.
and define linear map $L$ like this.
$$L : U \times V \times W \rightarrow P^3$$
more specifically, $$L(u,v,w)=(u-v,v-w,w-u)$$
obviously, $$Im(L)=(U+V)\times (V+W)\times (W+U)$$
(when
$Im(L)=\{p\in P^3 : ~\exists$ $(u,v,w)$$\in U\times V\times W$  such that $L(u,v,w)=p\}$
$U+V=\{u+v : u\in U, v\in V\}$
$U\times V = \{(u,v) : u\in U, v\in V\}$)
so i thought following equation is true: $$\dim\text{Im}(L)= \dim(U+V)+\dim(V+W) +\dim(W+U)$$
simply using $dim(V\times W)=dim(V)+dim(W)$ two times.. however, it meets contradiction if i try to use the following relation.  $$dim(U \times V \times W)=dimkerL + dimImL$$
applying $dimkerL=dim(U\cap V  \cap W$), i get $$dim(U)+dim(V)+dim(W)-dim(U\cap V)-dim(V\cap W)-dim(W\cap U)+dim(U\cap V\cap W)=0$$
which doesn't make a sense at all.
i guess the problem is from dimension of the image. (thanks for your help)
Comment: I don't think your set-theoretic description of the image is correct (the "obviously" part). For instance, if $(x,y,z)\in L(U\times V\times W)$, then $x+y+z=0$.
Comment: @MrTanorus: you seem to have missed G. Sassatelli's point. all you have done in your edit is define the meaning of "image." that is not the point. the point is that you are wrong when you claim the image is the set $(U+V)\times(V+W)\times(U+W)$.
Comment: i just edited what you said
Comment: @G.Sassatelli thank you for your answer!
Comment: @symplectomorphic thank you.
Comment: @MrTanorus More an observation than an answer.
Answer: Obviously $$\text{Im}(L) \subseteq (U+V)\times (V+W)\times (W+U)$$ holds, but not necessarily
$$\text{Im}(L)=(U+V)\times (V+W)\times (W+U)$$
e.g: $U=V=W=P$ then $\text{Im(L)} \ne P^3$, because $(0,0,1)$ not in $\text{Im}(L)$.
Comment: ahh..... i got what was the problem. can you give me an idea to get the dimension of the image?
Comment: oh, wait i got it. thank you for your help!


NVidia GF 555 and HDMI monitor on 12.04

Question: I know there are issues with this, but I haven't heard of a resolution. And some of the suggestions just confuse me.
I have a Dell XPS with a NVIDIA GeForce GT 555M with Optimus running Precise Pangolin.
I've installed bumblebee and the everything works pretty well, EXCEPT for my HDMI port to my external monitor. I use this for a dual monitor with the laptop screen as my primary. The external monitor is basically just non-functional when running Ubuntu. At best, if I run bumblebee I can get it to see that it's connected, but the best I've ever gotten is a black screen with a mouse cursor on it.
My questions:

Should I be running NVidia's drivers? I've read some posts that say I should and some posts that say I absolutely can't without breaking everything. I had installed them previously and ended up messing things up so badly, I had to start over. But are they better now?
Is there some trick to getting bumblebee to see the external monitor?

It just fries me that Winders can do this, but Ubuntu can't. I know NVidia supports windows better, but ... I just hate having to admit that it won't work with Ubuntu.
thanks for any ideas.
Comment: Are you still experiencing this problem?
Answer: Try the new version of bumblebee comes with a new primus system with better performance than optirun:
http://raw.github.com/Bumblebee-Project/Bumblebee/master/doc/RELEASE_NOTES_3_1
There are still issues to work out, like what David Airlie calls "reverse optimus" to make HDMI and other video outputs work straight from the nVidia card:
http://airlied.livejournal.com/76723.html
Please join this team if you are new by clicking on the "Join Team"
link at the right of the Launchpad page. It's important to have as
many users in the community as possible to request for appropriate
support, even if you found a non-obvious way to make it work for you.

NVidia GF 555 and HDMI monitor on 12.04


Pass id from HTML email to landing page, then use that to populate SQL query

Question: I have, let's say 5 email threads (a, b, c, d, e), each email is different. Each email contains a link to a landing page.
Then I have a php landing page wire frame that pulls data from a SQL database (currently mysql, but may change so using PDO) to populate different content depending on which email thread the viewer comes from. So 1 php landing page, but 5 rows in the database to populate 5 different versions of that landing page depending on which email viewer links from.
My current query in my landing page looks like this:
<?php
       $result = "SELECT body_copy FROM low_engagement WHERE thread_segment = 'a3'";
       $stmt = $connection->prepare($result);
       $stmt->execute();
       $body_copy = "";
       while($row = $stmt->fetch()) {
       $bodyCopy = $row['body_copy'];
       }
?>

If I manually change the WHERE clause entitled thread_segment across the values of 'a1', 'a2', 'a3', 'a4', and 'a5' my landing page updates with the appropriate content in accordance with each of the 5 threads.
My question, is it possible to perhaps mark the href in the HTML email so when that link links to the landing page it could some how interact with the landing page telling it which of the 5 email/email links it is coming from and dynamically alter the thread_segment value appropriately?
I am fairly new to PHP/PDO so I am open to suggestions and/or direction. My current research on the matter has me still researching possibly passing a variable via one of several means, but most of the content I find is in regards to forms.
Any insight is greatly appreciated!
Answer: Yep, just pass the thread_segment in the href of the email, like:
some.url.com/page.php?s=a3
and change your pdo to something like:
<?php
   $result = "SELECT body_copy FROM low_engagement WHERE thread_segment = :s";
   $stmt = $connection->prepare($result);
   $stmt->bind_param(':s', $_GET['s']);
   $stmt->execute();
   $body_copy = "";
   while($row = $stmt->fetch()) {
       $bodyCopy = $row['body_copy'];
   }
?>

Comment: Initially I got a Fatal error that said "Call to undefined method PDOStatement::bind_param() in..." However I googled that and saw similar code using $stmt->bindParam() and it worked. I don't know enough about php/pdo to know why, but that worked! Thanks so much!
Comment: Sorry, typed that out from memory and forgot it was camelCase.  Glad it worked out!
Answer: You can use HTTP GET Variables to pass information using a URL.
e.g. the Link: http://yourlink.org?segment=a1
The ?segment=a1 associates segment with the value a1, you can add more parameters by seperating with & like so: ?segment=a1&language=en
I am being very explicit with the variable names here, generally you would try to keep the url as short as possible.
You can then access this variable in PHP using $_GET:
$_GET["segment"]

Check out the PHP Docs for further information
 http://www.php.net/manual/en/reserved.variables.get.php
Comment: Great! thanks for the insight and documentation. It is much appreciated.


Read n bytes from file and get integer value

Question: I'm working on a coding challenge where I have to read n bytes from an encoded file and perform some operations with them. I am trying to get the integer value of the bytes to use as a seed for srand().
I'm not sure I'm doing this properly. I am passing in 4 and file pointer to read_n_bytes() in which I am reading 4 bytes from the file and writing them to a location in memory set aside with malloc(). Then returning the malloc() address as a char pointer as seed and attempting to access the bytes with &seed.
The rest of my operation isn't working here.
Am I going about this the right way?
char* seed;

int main() {
    FILE * fp;

    fp = fopen("flag.enc", "rb");

    // extract seed from flag
    seed = read_n_bytes(4, fp);

    srand(&seed);
}

char* read_n_bytes(int b, FILE * fp) {
    char * buffer;
    buffer = malloc(b);
    fread(buffer, 1, b, fp);
    return buffer;
}

Comment: The argument to `srand()` must be an integer, `seed` is a pointer.
Comment: Is it a binary file, or a text file that you're supposed to parse as an integer?
Comment: `&seed` doesn't access the bytes. It's the address of the pointer variable, which is the same no matter what its value is.
Comment: For  calling `srand` it won't matter, but for just about any other purpose, when reading a "binary" integer from a file like this, you'll need to worry about [endianness](https://en.wikipedia.org/wiki/Endianness).
Comment: @SteveSummit "worry"??? Too much stress in the world... How about "account for" or "consider"? `:-)`
Answer: srand() wants an integer, not a char** pointer that you are trying to give it.  You would have to typecast and dereference the pointer to access the integer value, eg:
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

char* read_n_bytes(size_t b, FILE *fp);

int main() {
    FILE *fp = fopen("flag.enc", "rb");
    if (fp == NULL) {
        // error handling...
    }

    // extract seed from flag
    uint32_t *seed = (uint32_t*) read_n_bytes(sizeof(uint32_t), fp);
    if (seed == NULL) {
        // error handling...
    }

    srand(*seed);

    free(seed);
    fclose(fp);
}

char* read_n_bytes(size_t b, FILE *fp) {
    char *buffer = malloc(b);
    if (buffer) {
        if (fread(buffer, b, 1, fp) != 1) {
            free(buffer);
            buffer = NULL;
        }
    }
    return buffer;
}

Alternatively, get rid of malloc() and let fread() read directly into an integer variable, eg:
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

int read_n_bytes(void *buf, size_t b, FILE *fp);

int main() {
    FILE *fp = fopen("flag.enc", "rb");
    if (fp == NULL) {
        // error handling...
    }

    // extract seed from flag
    uint32_t seed;
    if (read_n_bytes(&seed, sizeof(seed), fp) < 0) {
        // error handling...
    }

    srand(seed);

    fclose(fp);
}

int read_n_bytes(void *buf, size_t b, FILE *fp) {
    return (fread(buf, b, 1, fp) != 1) ? -1 : 0;
}

Answer: Below, I presume that the exercise involves a lot of integer values in the file, and the int values returned from calls to rand(). (Else, why worry about seeding with a constant value loaded from a file???)
Use main() to "set up" and "tear down" the information you will work with. "Contain" the exercise to a separate function.
#include <stdio.h>
#include <stdlib.h>

// A function defined (before use) is a function declared!
exercise( int arr[], size_t nElem ) {
    // whatever is the rest of the challenge
    // arr[0] is first int (seed is not included )
    // work with arr[0] to arr[ nElem - 1 ]
}

int main() {
    char *fname = "flag.enc"; // prominent and re-usable

    // attempt to open to read (binary mode)
    FILE *fp = fopen( fname, "rb" );
    if( fp == NULL ) {
        fprintf( stderr, "Cannot open '%s'\n", fname ); // see?
        exit( EXIT_FAILURE );
    }

    // measure the file (presuming reasonable size)
    fseek( fp, 0, SEEK_END );
    size_t fsize = ftell( fp );
    fseek( fp, 0, SEEK_SET ); // rewind

    /* Make BIG presumption that the data in the file is all integers */
    /* 'seed' is unsigned, but 'rand()' will return signed integers */
    size_t nInts = fsize / sizeof( int );

    int *buf = malloc( nInts * sizeof *buf );
    if( buf == NULL ) {
        fprintf( stderr, "malloc failed. wanted %zu bytes\n", fsize );
        fclose( fp );
        exit( EXIT_FAILURE );
    }

    size_t nread = fread( buf, sizeof *buf, nInts, fp );
    fclose(fp); // no longer needed

    if( nread != nInts ) {
        fprintf( stderr, "read %zu ints, not %zu (full file)\n", nread, nInts );
        exit( EXIT_FAILURE );
    }

    srand( (unsigned int)buf[0] );

    exercise( buf + 1, nInts - 1 ); // work with data that is loaded

    free( buf );

    return 0;
}


Does $30$ always divide $n^5-n$ where $n \in \mathbb{Z^+}$?

Question: Does $30$ always divide  $n^5-n$ where $n \in \mathbb{Z^+}$ ?
Comment: Yes, that's true.
Comment: rIn particular, you only have to test $n=0,1,2,3,4$. Or, to lighten your load further, $-2,-1,0,1,2$. Since $n^5-n$ is an odd function, this actually means you only need to check $0,1,2$.
Comment: It's also more widely true for $n \in \mathbb Z$ :).
Comment: Being divisible by $30$ means being divisible by $2,3$ and $5$ simultaneously. Test those separately.
Comment: Factorisation as $(n^2+1)(n-1)(n+1)n$ shows divisibility by $3$. Fermat's Little Thm shows $n^5\equiv n\pmod{5}$, and hence divisibility by $5$.
Answer: For a proof, try factoring:
$$
n^5 - n = n(n^4 - 1) = n(n^2 + 1) (n-1) (n + 1) = (n-1)(n)(n+1) (n^2 + 1)
$$
The product of three successive integers is always divisible by 6, so all you need to show is that either one of the three integers is divisible by 5, or that $n^2 + 1$ is divisible by 5. If none are divisible by $5$, then the middle one must be of the form $n = 5k+2$ or $n = 5k+3$.
Take the first case and look at
$$
n^2 + 1 = (5k+2)^2 + 1 = 25k^2 + 20k + 4 + 1 = 25k^2 + 20k + 5 = 5(5k^2 + 4k + 1).
$$
That's clearly divisible by 5.
Now.,..work out something similar for the last case, and you're done.
Answer: The way I like to do it is try to prove and if it doesn't work, try to find a counter example:
Let's try for small $n$: $1^5-1=0$; $2^5-2=30$; $3^5-3=243-3=240$, and these are all divisible by $30$.
For general $n$, write $n=30r+p$, $0\leq p<30$. Then
$$n^5-n=(30r+p)^5-(30r+p)=(30r)^5+5(30r)^4p+10(30r)^3p^2+10(30r)^2p^3+5(30r)p^4+p^5-30r-p$$
The only term which is possibly non divisible by 30 is $p^5-p$. This is what we had begun with, but $p<30$. So now you "simply"have to check that $p^5-p$ is divisible by 30 for $0\leq p\leq 29$. The first three cases are done above, and the rest is an exercise for a rainy day.
Answer: We have $n^5-n=n(n^4-1)=n(n^2+1)(n^2-1)=(n-1)n(n+1)(n^2+1)$, so a product of three consecutive integers always divides $n^5-n$, so it is always divisible by $2$ and by $3$. Now it suffices to show that it's always divisible by $5$. Use induction on $n$. If $n=0$, it's obvious. Assume it's true for $n=k$, so $k^5-k=5m$ ($m\in\mathbb{Z}$). We prove the result for $n=k+1$:
\begin{eqnarray*}
(k+1)^5-(k+1)&=&k^5 + 5k^4 + 10k^3 +10k^2 + 5k +1 -k -1 \\
&=& k^5+5k^4+10k^3+10k^2+4k\\
&=& (k^5-k)+5(k^4+2k^3+2k^2+k)\\
&=& 5(m+k^4+2k^3+2k^2+k)\\
\end{eqnarray*}
So $n^5-n$ is always divisible by $5$ too by induction. This completes the proof.


Count array by parse value of array

Question: How can We count array element inside array.
$course = array(
            array(
                'course_name'=> 'HTML',
                'trainee'=> array(
                                array('trainee_name'=>'Hong Va'),
                                array('trainee_name'=>'Reaksmey SE')
                            )
            ),array(
                'course_name'=> 'Java',
                'trainee'=> array(
                                array('trainee_name'=>'Hong Va'),
                                array('trainee_name'=>'Reaksmey SE'),
                                array('trainee_name'=>'Sok Panha'),
                                array('trainee_name'=>'MAO Vannakpanha')
                            )
              )
);

I want the result like this:
HTML (2 trainees)
Java (3 trainees)
Comment: Okay, you want it. That's good! What do you want from us?
Comment: First you try and then you'll get help.
Comment: @Lazy Developer: if you cannot solve such a trivial task - there is a chance that you need to learn php once again from the scratch. Otherwise instead of coding you will spend more time googling and waiting for answers.
Comment: Hint #1: `foreach` + `count`. This is basically all what you need to solve it.
Comment: possible duplicate of [Count an array php](http://stackoverflow.com/questions/6373880/count-an-array-php)
Answer: foreach($course as $c){
    echo $c['course_name']."(".count($c['trainee'])." trainees)";
    echo "
";
}

Answer: HTML
$course[0]['trainee'][0]['trainee_name'] // Hong Va
$course[0]['trainee'][1]['trainee_name'] // Reaksmey SE

JAVA
$course[1]['trainee'][0]['trainee_name'] // Hong Va
$course[1]['trainee'][1]['trainee_name'] // Reaksmey SE
$course[1]['trainee'][2]['trainee_name'] // Sok Panha

Answer: Just use foreach and count
  <?php
       $result = array(); // to handle with data later
       foreach($course as $arr) {
          $result[$arr['course_name']] = count($arr['trainee']);
          // for output here
          echo $arr['course_name'].' ('.count($arr['trainee']).' trainees)
';
       }

Answer: Try this - it'll also use the correct plural or singular depending on the number of trainees.
foreach ($course as $item)
{
    $count = count($item['trainee']);
    $word = ($count == 1) ? 'trainee' : 'trainees';
    echo $item['course_name'] . " ($count $word)";
    echo "
";
}

Count array by parse value of array


How to generate random number between 1 to 9 in c program, then assign that number to one of three things and it shouldn't be same each time?

Question: srand(time(NULL));
int nRandonNumber = rand()%9+1;
printf("%d\n",nRandonNumber);

How to generate random numbers between 1 to 9 in the c program, then assign that number to one of three things, and it shouldn't be the same each time?
Comment: *shouldn't be the same* - means it is not a random number you are looking for but some random permutation.
Comment: For the "random swapping" @WeatherVane have mentioned you might want to use the [Fisher-Yates](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle) algorithm
Comment: *What* shouldn't "be the same each time"? The random number you generated? The "three things" (whatever they are)? Something else?
Comment: What is the problem with your code? Looks like you already solved the given task yourself!?
Comment: Put the values 1 thru 9 in an array. Randomly swap the elements around. Use the first three elements.
Comment: *three things* is not a type.
Comment: You shouldn't use a seed that is dependent on the seconds on the clock. You should probably use the system PRNG, and that will be different per platform.
Comment: You could create an array of random numbers using a decimal expansion of the square root of a numbers such as 15 or 2.015 - after the decimal point; C will do this to 48-54 decimal places. Or create random numbers in the real world and create an array. Both these methods mean you can start extracting array elements at a different place each time.  Functions like rand() are not truly random, although I realise I'm being pedantic.
Answer: Instead of generating 3 numbers bewteen 1 and 9, shuffle an array with the numbers 1 to 9... then select the first 3, obviously different, elements.
int arr[9] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
shuffle(arr, sizeof arr / sizeof *arr); // implementing shuffle left as an exercise
printf("%d %d %d\n", arr[0], arr[1], arr[2]);

Suggestion for shuffle(): Fisher-Yates shuffle
Comment: I tried  your code but it gave me an error
Comment: There will be no error if you properly define the `shuffle()` function.


What is the equivalent to XmlArrayItem when using DataContractSerializer?

Question: I'm using DataContractSerializer to serialize an object that has a property of type List and I want to control how the strings are emitted.
[DataContract(Name = "ReportData", Namespace = "")]
public class Foo
{
    [DataMember]
    public List<string> TrackingNumbers { get; set; }
}

When I serialize this object I get this XML:
<ReportData xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <TrackingNumbers xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
    14735ec8-81c4-44e4-9bbe-6c661eb74e54
  </TrackingNumbers>
</ReportData>

What I would like is:
<ReportData xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <TrackingNumbers xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
    <TrackingNumber>14735ec8-81c4-44e4-9bbe-6c661eb74e54</TrackingNumber>
  </TrackingNumbers>
</ReportData>

Is this possible with DataContractSerializer? It was trivial with XmlSerializer and XmlArrayItem but I cannot figure it out.
Also, is it possible to generate XML that does not contain any namespace declarations?
Thanks very much.
Comment: You can subclass `List` and apply `[CollectionDataContract(ItemName="TrackingNumber", Namespace = "")]`.  See: [Custom Element Names using the DataContractSerializer on a List of primitives](https://stackoverflow.com/q/5516907/3744182) and [How to Deserialize XML using DataContractSerializer](https://stackoverflow.com/q/16943176/3744182).
Comment: Thanks very much @dbc, that did the trick
Answer: This works for me. It's more or less exactly what @dbc suggested :)
[CollectionDataContract(Namespace = "", ItemName = "TrackingNumber")]
internal class TrackingNumbersList : List<string>
{ }

[DataContract(Name = "ReportData", Namespace = "")]
public class Foo
{
    [DataMember]
    public TrackingNumbersList  TrackingNumbers { get; set; }
}


Why is xlrd reading the wrong number of columns?

Question: When I read an .xls file, xlrd acts as if there was an empty column at position 0, and the last column (number 58, if counting from 0) is never read; the first column is skipped and the last one disappears.
The issue goes away when I save the file (either as an .xls or .xlsx) and do the whole process again. When saving, Excel tells me that there may be compatibility issues. I need to automate this process, which is why I'd like to avoid manually having to save the file.
# Loading the 'converted' file
wb = xlrd.open_workbook(converted_file_path)
sheet = wb.sheet_by_index(0)

print('Row',len(sheet.row(3)),sheet.row(3))
# Prints: Row 59 [text:'Client Number', ...

# Loading the original file
wb = xlrd.open_workbook(original_file_path)
print('Row',len(sheet.row(3)),sheet.row(3))
# Prints: Row 58 [empty:'', text:'Client Number', ...

print(sheet.cell_value(0,5))
# Prints nothing, while there is a number at cell (0,5)

Comment: Are you able use something like pastebin to give us a link to a file that doesn't work?
Comment: I'd love to, but I can't; it contains very sensible data for the company I work for. And I can't edit it out because then the file would work.
Comment: If you are on Windows, you could automate the loading and saving to `.xlsx` format using Python `win32com` by using Excel itself. Then it should be able to be read normally using `xlrd`
Answer: If you are on Windows, and you finding that by loading / saving the file using Excel is somehow repairing your file, then you could use Excel itself to perform this initial conversion. This then should load correctly using your existing code using xlrd. For example:
import win32com.client as win32
import xlrd

excel = win32.gencache.EnsureDispatch('Excel.Application')

wb = excel.Workbooks.Open(r'input.xls')
excel.DisplayAlerts = False
wb.DoNotPromptForConvert = True
wb.CheckCompatibility = False
wb.SaveAs(r"output.xlsx", FileFormat=51, ConflictResolution=2)
excel.Application.Quit()

# Loading the 'converted' file
wb = xlrd.open_workbook('output.xlsx')
sheet = wb.sheet_by_index(0)

print('Row',len(sheet.row(3)),sheet.row(3))
# Prints: Row 59 [text:'Client Number', ...

Comment: Didn't work. I'll try to tweak the settings and see if that helps.
Comment: Ok, NOW it works and I have no clue why. I'll try to figure it out and post an update
Answer: Thanks to Martin for suggesting the win32com fix, but I found the actual problem. It has something to do with how xlrd has Python load up sheets in memory. Perhaps messing around with the on_demand parameter while loading the workbook does something, but anyhow, here's what was happening:
I needed the sheet named "Report X" where X is some number, so I looked for it like this:
for sheet in wb.sheets():
    if 'Report' in sheet.name:
        report_sheet = sheet
        break

Then, I changed it to
for sheet in wb.sheets():
    if 'Report' in sheet.name:
        report_sheet = sheet
        # removed the break

And now it works.


Fabric: Answers: purchase flow tracking of `success` bool doesn't work as expected

Question: I'm tracking purchase-related events in an iOS app with Answers (part of Fabric). The Answers docs for purchase flow tracking are very straightforward:
Answers.logPurchaseWithPrice(13.50,
                  currency: "USD",
                  success: true,
                  itemName: "Answers Shirt",
                  itemType: "Apparel",
                  itemId: "sku-350",
                  customAttributes: nil)

The success bool is documented as:

When a Purchase Event has the success attribute set to NO (Objective-C) or false (Swift), it is excluded from revenue charts but included in all other charts and calculations.

I've submitted one full flow of events, through Add Cart, Start Checkout, and Purchase, and for Purchase (logPurchase…) I set success to false, because I took the cancellation route, rather than completing the payment.
However, when I look at Answers' Purchase Funnel, I see a 100% purchase success rate:

That's not quite right! What's the proper Answers tracking call for a user tapping Cancel in my Purchase flow? It doesn't seem to be logPurchaseWithPrice(… success: false…
Answer: Mike from Fabric here. Definitely understand the confusion on this, but will aim to clarify it.
If a user hits the event on each step of the funnel, then it would be considered a success regardless of the success attribute. The funnels are intended to function as a what % of your users hit the event triggers that were set within the app to send the data to Answers. If a user hits cancel, then you shouldn't trigger the logPurchase event. I recommend setting the event after the purchase has been confirmed - so on a successful tap or trigger of the final purchase button.
As you mentioned from the documentation, the success attribute only affects the revenue chart and the funnel does not take it into consideration.
Comment: Gotcha, thanks! I was hesitant to remove the call to `logPurchase` for cancelled/failed purchases.


How do I remove this connector from a solid electrical wire?

Question: I'm trying to replace the light above my kitchen table. The junction box seems to have a solid electrical wire. It was connected to the light's stranded wire with this connector here and also wrapped in what looked like sticky black rubber. I peeled off as much of the rubber as possible and then I cut the stranded electrical wire to remove the old light. I tried to pry the connector open by the stranded wires and it looks like it could be gold inside? How do I remove the solid junction box electrical wire from this connector now?
I need to connect the solid wire to my new light fixture which also has a stranded electrical wire. My new light fixture includes the simple plastic wire twist connectors which I know how to use.
Comment: Can cut solid as easy as stranded, find solid easier to cut since you don't miss cutting the fine strands.  They are crimp connectors and cutting is only way.  Strip the insulation back from cut(about 1/2 inch) and use wire nuts.
Comment: Sticky black rubber sounds like electrical tape.  Most connectors are of the screw type.  You screw them on, you screw them off.  Can also in most cases just cut the wire near them and strip the wire and put new connector on.
Comment: Hi @crip659. I was finally able to include some pictures. These look like crimp connectors possibly and not the screw ones? The original light is probably at least 20 years old (previous owner had it installed). Am I able to cut a solid wire? I thought I could only cut stranded wires. Thanks.
Comment: Thank you!! Simple enough!
Answer: These don't get "removed", they get cut off. Snip the copper solid wire at the end of those connectors, strip off the insulation and then use wire nuts or some other approved connector to connect the wires for your new light.
Comment: Yep, let's not over think this, great answer!  +
Comment: Thanks! I should have posted here from the get go. I seriously thought solid wires couldn't be cut because of something I read on the internet. You wouldn't believe how much time I wasted. Lol.
Comment: @GeorgeAnderson  I added the "or some other approved connector" because I've never seen crimped connections like that for a light and thought it might be in a different country, one that doesn't allow wire nuts......  I'm finally thinking globally... lol  stay safe.


concat two columns in pyspark & add a text in between

Question: Hi I'm using pyspark in 3.0.1 in Databricks. My pyspark dataframe ,df, contains a column Year with value like 2012 & another Column Quarter with number 1,2,3 & 4. I want to join Year & quarter & create another column year_qtr & it should contain value like 2012 Quarter-1
I tried following code
import pyspark.sql.functions as f
col_list = ['Year'," Quarter-",'Quarter']
df.withColumn("year_qtr", f.format_string('Year',' Quarter-','Quarter')).show()

But I'm getting error message
AnalysisException: cannot resolve '` Quarter-`'

Can you help me to resolve the issue?
Answer: You need to specify a format string in the first argument, just like how you would do it in Python. The subsequent arguments would correspond to the arguments inside the format string.
import pyspark.sql.functions as F

df2 = df.withColumn("year_qtr", F.format_string('%d Quarter-%d', 'Year', 'Quarter'))

Use %s if the columns are of string type. %d is only suitable for int type columns.

Alternatively, you can use concat:
import pyspark.sql.functions as F

df2 = df.withColumn("year_qtr", F.concat('Year', F.lit(' Quarter-'), 'Quarter'))


Understanding Hearthstone World Championship match format and decks

Question: As I understand, the match format for the Hearthstone World Championship is Conquest, where each player uses a number of predefined decks specified by tournament rules.
Where are these decks predefined and who makes them? Are players allowed to make changes to these decks?
If the tournament is played with predefined decks, what makes a player better than another?
thanks
Answer: The decks being predefined means they are created by the players before the event and cannot be changed between or during matches. Players use whatever cards they wish (subject to the usual deckbuilding and format rules).


Can I use a tankless and tanked hot water heater at the same time this way?

Question: I am designing a house for myself and want to use a tankless hot water heater. The issue is I am going to be on LP gas and I want to have a recirculating loop. Id rather not consistently use gas to keep the loop hot all the time. and to put a wrench into things I also plan to use the Return loop to warm my hydronic towel loop in the master bathroom shower.
So this is my idea, I use a gas tankless water heater to feed the home during water consumption and use a electric tanked water heater to feed the recirculating loop using a pump when water is not being consumed. The pump will be set on a timer and use check valves to keep the flow of the water in the correct direction. I also plan to have all of my hot water lines insulated to keep the water hot as long as possible.
Im looking for input on this design and if it will work properly. any input is greatly appreciated.
Comment: A) You don't need a recirc loop with tankless if the heater is located properly. It should be close enough to points of use that the delay shouldn't be an issue. B) Plumb a small heating loop through the towel warmer - you only need the towel warmed when you're actually using the shower, right? It doesn't need to be warm when you're in the office or sleeping...
Comment: @FreeMan you wouldn't need a recirc loop with a tanked heater if it is located properly either. tankless vs. tanks is a meaningless difference for that.
Comment: Energy to keep the recirc loop hot has to come from somewhere - are you saying you'd prefer the "heat maintenance" energy be electric, while the "bulk heating" of fresh, cold water be gas? Or do you intend instead that the electric tank would not be powered at all and is just a heat reservoir to be expended over time in heating the towel rack? (In the latter case, there's a problem around how the tank will be re-heated.)
Comment: @FreeMan =I don't disagree with either of those statements but the only place to properly center the heater isn't possible and the reasonable place to set them is upwards of 75 feet from the furthest fixture. Also I would like the towel warmer to stay hot longer than the shower to help dry the towel.
Comment: @GregHill that's exactly what I am saying. I want the loop to be heated electric and the bulk heating to be gas. I could use a tankless only for the loop (I've looked at a tankless with a built in recirculating pump) and it wouldn't be a big deal but I don't want the consistent gas consumption from maintaining the loop temp.
Comment: three is nothing stopping this from working
Comment: You didn't ask about this specifically but you may want to consider - if your towel bar is part of your domestic hot water circuit you will need to verify that the towel bar, and the valves and fittings connecting the towel bar, are all appropriate for use with domestic hot water. I have seen towel bars that are definitely not rated for domestic hot water.
Answer: You have tankless injecting into the wrong water pipe.  It should be adding to the input water of the tanked heater, not the output water.
The reason is, in a tankless, the water isn't already hot.  So the water in the tankless and on the supply leg from tankless to loop will be icy cold, and will show up in your pipe as a slug of ice cold water.  If you feed tankless output into the output line of the tanked heater, it'll show up at the showerhead as a slug of 5 seconds of ice cold water in the middle of your shower.  If you inject the tankless water into the input of your tanked heater, it will diffuse into the 30 gallons or whatever of water, and will be easily reheated by the thermostat in the heater by the time it rises to the top.
Also, this will solve a stagnation problem you'll have in the tanked heater.  Imagine all the water in the tank and circulation loop is green.   When you take a shower in your current diagram, you get this high flow of fresh blue water from tankless via that little bit of pipe to the shower head, displacing the green water in that pipe section... and that's it.  A little bit gets pushed through by the recirc pump, but you're not flowing gallons per minute there. Since the green water isn't moving, the chlorination will decay and bacteria will grow.  This, plus keeping the water temperature below 140F, is what breeds dangerous bacteria, such as legionella.
Whereas if you feed the tankless into the tanked inlet, you finish with the bottom half of the tank being full of blue water, ensuring near total water change-out every day or two.
And here's a Technology Connections on how water tanks work.
Comment: @Fresh the problem is the stagnation would bleed the chlorine out of it, the 140F assumes normal chlorination.
Comment: The slug of cold water will heat while it travels the pipe which is at tank temp but you are right it would be noticeably colder.  As far as the stagnation goes it shouldn't be a problem if the tank is set to 140F?
Answer: Energy in = energy out
It really doesn't matter whether you use tankless (large amounts of energy at one time) or tanked (small amounts of energy for a longer period of time). It really doesn't matter whether you use electric (except heat pump - those are far more efficient, but I don't think that's really an option being considered here) vs. gas (LP or natural gas) - in the end it is all BTUs (or another unit of your choice).
This seems to be a really complicated plan based on a few premises that really don't hold up in practical real terms:

Tankless is somehow better than tanked - because that's what you want to use for most of your water heating
Tanked is somehow better than tankless - because that's what you want to use for your towel bar
Recirculation pumps and long lines when you are building a house and can therefore put your hot water source closer to point of use

I am not a big fan of tankless. Absolutely not (except in very limited circumstances) for electric. Potentially OK for gas - but they have minimum flow rates/temperatures which make them not so great for a minimal use application such as a towel warmer.
Altogether, this seems to me to be an exercise in making things more complicated than they need to be.
My recommendations:

If you can, design your house so that your primary water heater is near the bathrooms. Typically (but not always) there is one or two locations with most of the plumbing. I have the water heater in the laundry room and the kitchen is directly above the laundry room. On the other side of the house are the bathrooms (two on one floor back-to-back above a third bathroom right below one of them). So I have effectively instant hot water in the kitchen but not in the bathrooms. Prioritize design for planned use by putting the water heater close to the bathrooms.
If you can't put a gas water heater (tanked or tankless - the issues of location are basically the same - where can you safely put it for air in and exhaust on) near the bathrooms then install a large tanked electric water heater as close as possible to the bathroom. You are designing a house, so you can design the space needed to make it fit. With electric it is super-easy - you just need a small closet - no fresh air or exhaust issues. And then there is no need for recirculation pumps. Two electric water heaters (or one electric, one gas depending on what can go where) is possible as well. The big cost is running all the plumbing, but that is easy when designed in.
Install an electric towel bar. But that isn't as efficient as the water heater, you say? Well, actually it is the exact same 100% efficient as an electric water heater. And in fact more efficient because it runs exactly and only when you need it and only heats the towels.

If this were a retrofit situation then recirculation, second water heater, etc. might make sense. But at the design phase you can do much better.
Comment: well everyone has helped me a lot on bouncing ideas. I actually did some digging and found a wet rated kit for a electric towel rack. so that solves that problem. also I do think going to two water heaters separate from each other is the smart move but I will probably go with the navien tankless and still do the instant hot water loop with a return line. these tankless have the recirc pump built into them. ill also probably still insulate all my hot water lines under the home for efficiency reasons. thanks so much for the input and help.
Comment: This is what I was getting at in my <500 character comment. +100%
Comment: Two gas-fired tankless water heaters, one at each end of the house, would be a great choice. Save on pipe, save on recirc, still get endless hot water. Some tankless heaters have very minimal clearance requirements and might be designed into a closet or cabinet to make them "disappear" very near the point of use.
Comment: As for undersizing tankless: the result depends on the model and its use. If I set my Rinnai for 106 °F and turn on only the hot water tap in the shower then I get a comfortable shower. If somebody else turns on another shower or sink, _we both still get 106 °F water and I stay comfortable, although the shower head spray is much weaker_ -- this particular model, operated this way, restricts the flow as necessary to maintain its set temperature.
Comment: not a huge fan of recirc as it wastes a lot of heat.  i like to homerun 1/2 hot lines to showers so you only have to dump the water in the 1/2" pipe back to source before you get hot water ( hot in sink and hot in shower can be off same pipe since you only use one at a time typically ).  crazy how much longer truck/branch/twig plumbing takes to get hot water to show up but does save on pipe.
Comment: I agree with that entire statement. There are factors that make some of that difficult. 1)the electric towel warmer is not an option because it is going inside of a wet room. cant have live high voltage inside the shower. Also the tankless favorable because I want the endless hot water. the home is 100 feet wide with bathrooms on opposite ends. unless I use two water heaters and separate loops the only other option is to put in a return loop and recirculate if I want pretty much instant hot water. and only a pump fixes the towel heater issue. or pipe it inline with the shower hot water line.
Comment: Bathrooms at ends of 100' house - use two water heaters. As far as "endless hot water", that's your choice. But don't undersize - an undersized tankless is far worse than an undersized tank - with undersized tankless, two people shower at the same time and they both get lukewarm water. With undersized tank, they both have hot water for a while, just not forever.


Dropbox won't start on ubuntu 14.04; overwrites autostart entry

Question: I noticed recently that my dropbox was no longer running on startup (the icon no longer appeared in the tray at top right, and nothing was syncing.)
In Startup Applications, dropbox is selected, with command dropbox start -i.  Based on Dropbox doesn't autostart in 12.04 I changed the command to sh -c  ~/.dropbox-dist/dropboxd.  This works:  if I restart my machine, the dropbox daemon starts running, the usual icon appears up in the tray, and files sync correctly.
However, when I go look at Startup Applications (after the change and restart described above), the command has reverted to dropbox start -i!  That means dropbox will not work next time I restart.  Why does it do that and how can I fix it?
I'm on Ubuntu 14.04 LTS, with dropbox version 3.6.7.
Edit, was too long as a comment:
@Jacob I haven't been able to get this to work.  I'm having trouble with "In Startup Applications (Dash > Startup Applications) remove the Dropbox entry (but not the newly created start_dropbox.desktop)."  The newly created start_dropbox.desktop does not appear in Startup Applications, but there's a Dropbox entry with the dropbox logo, whose command is /bin/bash -c "sleep 10&&dropbox start -i" -- seems to be reading the newly created start_dropbox.desktop.  The original dropbox.desktop no longer present in ~/.config/autostart.  Dropox does not start on reboot:  it does ask for my password, but it doesn't actually start running.
Edit, got this to work by following @Jakob's suggestion, with a twist:
$ ls .config/autostart/
start_dropbox.desktop  start_dropbox.desktop~
$ cat .config/autostart/start_dropbox.desktop
[Desktop Entry]
Name=Dropbox
GenericName=File Synchronizer
Comment=Sync your files across computers and to the web
Exec=sh -c ~/.dropbox-dist/dropboxd
Terminal=false
Type=Application
Icon=dropbox
Categories=Network;FileTransfer;
StartupNotify=false
X-GNOME-Autostart-enabled=true
$

Note the Exec=sh -c ~/.dropbox-dist/dropboxd line. This is similar to the setup I had when I asked the question, but now the Exec line doesn't get overwritten on reboot.
Comment: Hi Adrian, did you manage?
Comment: @Jakob not quite, please see my edit above
Comment: I'll look into it if I am at home (could be a few days). If the command works after startup, we will make it work anyway. Maybe the sleep needs to be a bit longer.
Comment: @Jakob I got it to work, will add an edit
Answer: Although the cause is most likely the same as here, I posted an almost similar answer, since both the question and the symptoms are different:
Dropbox timing issues in 14.04
In some cases, in 14.04 Dropbox has some timing issues, and the command to startup Dropbox syncing starts too early and breaks for some reason. It seems to be a bug, because starting Dropbox manually fixes it temporarily, but only until the next restart. To fix it permanently, we need to edit and rename the dropbox.desktop file in ~/.config/autostart/
The fix:

rename the file ~/.config/autostart/dropbox.desktop into: start_dropbox.desktop
[You need to rename it because Dropbox overwrites the file dropbox.desktop on every startup]
Open the (renamed) file with gedit (drag it over an open gedit window).
Replace the line, starting with Exec=, change it into:
Exec=/bin/bash -c "sleep 10&&dropbox start -i"

This delays the startup of Dropbox with 10 seconds after log-in, which does the trick.
in Dropbox preferences, untick "Start Dropbox on startup" (else we would have two .desktop files representing Dropbox in the autostart folder):

In Startup Applications (Dash > Startup Applications) remove the Dropbox entry (but not the newly created start_dropbox.desktop).

In the folder ~/.config/autostart, remove the original dropbox.desktop if it is still there.

Now on restart, it should run fine.
Explanation
The bug seems to be related to the timing of the Dropbox startup. The workaround above replaces the "real" Dropbox starter with one that delays the startup 10 seconds, until the desktop is ready.
Answer: I installed dropbox, I didn't make any change and everything works correctly...
Try to remove it with dpkg -P dropbox and reinstall the last .deb package from the web page


What is the difference between this two derivatives

Question: Why I must use the quotient rule to find the derivative of $\dfrac{2}{x^2}$ and in the case of $\dfrac{x^3}{2} + \dfrac{3x}{2}$  I should use the product rule?
Answer: No you dont need the quotient rule since 2/x^2=2x^(-2). Can you take it from here?
The other question is not answered by the Product rule. Take D(f+g) = Df + Dg
Answer: Hint:
$$
\dfrac{2}{x^2}=2x^{-2}
$$
and you can use the product rule.
More general:
The quotient rule for $\dfrac{f(x)}{g(x)}$ ghives the same result as the product rule for $f(x)[g(x)]^{-1}$ ( can you prove this result?)
Comment: The quotient rule can be derived from the product rule if you have the patients for negative exponents. I also use this method so i don't have to memorize the stupid thing.
Comment: The right answer to the first one is -4/x^3
Comment: Yes, with the product rule with negative exponent it's easy. In general this is the more efficent when the numerator is a constant.


Is this quantifier is true?

Question: "Every mail message larger than one megabyte will be compressed".
Let $M(x) = x$ mail message
$L(x) = x$ larger than one megabyte will be compressed
$ \forall x \space (M(x) \rightarrow  L(x))$
Comment: Thanks, @GitGud, I will edit appropriately.
Comment: What you wrote says that every mail message is larger than one megabyte and will be compressed, which is different from what you want. Also you probably want e-mail instead of mail.
Answer: You will need three predicate letters, not two.
Let:

$M(x)$ stands for 'x is a mail message'
$L(x)$ stands for 'x is larger than one megabyte'
$C(x)$ stands for 'x will be compressed'

Then we have that the sentence:

"Every mail message larger than one megabyte will be compressed"

means that

It holds generally that if x is a mail message and larger than one megabyte, then it will be compressed.

Now how to put it in adequate symbolism?

Is this quantifier is true?


What is the strongest weapon in Skyrim without enchantments or DLC, and with maxed out Dovahkiin?

Question: I love Bethesda games and have been wondering who would win the fight between Dovahkiin or The Lone Wanderer. I am trying to put aside my love for Skyrim to decide who would win a fight using hit points and defense points.
I have been reading through other questions but none have really answered mine. Assuming max perks for everything, what is the strongest weapon in Skyrim, not including DLCs or enchantments?
Answer: If DLCs aren't allowed, the strongest weapons are Daedric weapons. The Daedric warhammer has the highest damage per swing or all melee weapons, and with the right perk can ignore armour.
Comment: Would help to have some more specifics, like a source or how much damage that is.
Comment: Studoku How much damage is that with Level 100 Two Handed Skill? The base damage is 27
Answer: Studoku's answer is correct, without considering anything but base damage, 100 skill and perks the base damage of a Daedric Warhammer is the highest:
27 (base) * 1.5 (skill) * 2 (perks) = 81 damage
However, warhammers are also the slowest weapons - due likely to a bug, greatswords and battleaxes both swing at .7 attacks per second while warhammers swing at .6 (the bug being that greatswords should swing faster, which is fixed by the unofficial patch to put them at .75).  Considering weapon speed, battleaxes and a few unique weapons do more damage per second than a Daedric Warhammer (it's notable that with Limbsplitter, Daedric greataxes also do an extra 3 dps bleed for 6 seconds after each hit, but since we're not considering the armor ignoring perk for warhammers or the extra critical damage perk for greatswords I'm not adding it):
Daedric Warhammer: 81 damage * .6 APS = 48.6 DPS
Daedric Battleaxe: 25 * 1.5 * 2 = 75, 75 * .7 APS = 52.5 DPS
Volendrung and The Longhammer are both unique warhammers that swing faster than normal warhammers.  Volendrung swings as fast as a greatsword (.7 in the base game, .75 with the USKP) and The Longhammer swings at .8 aps, giving them the following DPS values:
Volendrung: Same as Daedric Battleaxe, 52.5 DPS
The Longhammer: 21 * 1.5 * 2 = 63, 63 * .8 = 50.4 DPS
Answer: Keep sharpening with blacksmith potions to increase damage. There is no single strongest weapon in Skyrim.
Answer: Dragonsbane is the strongest one handed sword I have come across, it is in the sky haven temple.


The Better Banner Battle - When to use each Soldier Banner

Question: The solider has three different types of 'banner' items that, when charged by dealing damage, allow him to 'buff' himself and his nearby teammates in different ways.

The Buff Banner - Bestows all weapons with mini-crits
The Batallion Backup - Reduces damage for all buff targets
The Concheror - Provides healing for all buff targets per damage dealt

My question is, when is it best to use each of these different banners?
Answer: Each banner has a different situation in which it shines.  Using it effectively provides the greatest bonus, both to your team and to yourself.
Buff Banner
The Buff Banner can, in the right situation, act as a mini-Kritzkreig for your entire team, helping them punch through an enemy front, take a capture point, or push back an attacking team entirely.  It also chargest faster than any other Banner, which makes it easier to utilize in most situations, and is ideal for a defensive front since it allows your team to break apart a push.
But it won't be of much help if you don't have teammates that can deal that damage.  Buff Banner is best used when you have multiple splash-damage allies on your team, such as other soldiers or demomen.  Pyros can help too, as can Heavies.  Basically any ally that can deal a lot of damage will help.
The Buff Banner also pairs well with an Uber medic, allowing you the benefit of both mini-crits and invulnerability at the same time.
Batallion's Backup
If the Buff Banner is like a mini-Kritzkreig, the Batallion's Backup is like a mini-Uber.  The reduced damage can help lead your team into a push, and the added health will help you survive that push as well.  If you have a lot of allies pushing together all at once, the defense bonus this item provides can prove devestating in a push.  It can even help take down that pesky Sentry Nest.
Like the Buff Banner, this item pairs well in conjunction with its opposite in Medigun-technology.  A kritzkreig with the Batallion's Backup will keep the Kritz target alive while they tear through your opponents.
The Concheror
The Conch is a little more difficult to place in terms of usefulness - it sort-of acts like the Quickfix, in that it will keep all of your allies topped up on health while in effect.  If you have a lot of high-health allies (Soldiers, Demomen, Heavies ect), it can help them stay alive while pushing forward.
The Concheror, like the Batallion's Backup, pairs best with a non-Uber medic, like the Kritzkreig, since it allows the target to deal damage and heal equal ammounts from it at the same time.  But it can also be beneficial if your team is lacking medics or other forms of healing, giving your team a much-needed healing boost.
Update The Concheror has an additional effect now: It acts as a Disciplinary Action effect to all in its area of effect, speeding up everyone's movement including the soldier.  This adds some utility to the Concheror, allowing for a rapid push that can be very effective as an attacking team, when trying to capture a point, or when trying to claim and return with enemy intelligence.

In addition, both the Concheror and the Batallion's Backup have bonus effects.  See Austin Mohr's answer for details.
Comment: @OrwellHindenberg The Buff Banner specifically is a good defense banner, since it acts like a Kritzkreig and effectively counters another team's push.
Comment: The banners are useful in all of those situations, but they seem focused solely on push aka offense. Are there any where they would be better for defense rather than offense?
Comment: Concheror also adds the speed perk for you and teammates closeby - makes a lot of difference on certain maps, rushing to a point, escaping with a flag or catching up an enemy.
Comment: @Konerak Very true.  Answer updated.
Answer: The Battalion's Backup and Concheror both have passive effects, as well.
The Battalion's Backup provides +20 health for the wearer. A fully overhealed Soldier with the Backup has 330 health versus 300 without. The extra 30 health cushion can be very useful if you have an attentive Medic.
The Concheror provides +2 health per second for the wearer. In contrast to the Backup, the healing over time benefit is very nice for a Soldier that is roaming or otherwise has limited Medic access. (For even more self-healing, consider pairing the Concheror with the Black Box.)


Is there a single SQL (or its variations) function to check not equals for multiple columns at once?

Question: Just as I can check if a column does not equal one of the strings given in a set.
SELECT * FROM table1 WHERE column1 NOT IN ('string1','string2','string3');

Is there a single function that I can make sure that multiple columns does not equal a single string? Maybe like this.
SELECT * FROM table1 WHERE EACH(column1,column2,column3) <> 'string1';

Such that it gives the same effect as:
SELECT * FROM table1 WHERE column1 <> 'string1'
                       AND column2 <> 'string1'
                       AND column3 <> 'string1';

If not, what's the most concise way to do so?
Comment: don't worry about making the code look fancy, or require less typing, your goal in SQL is to get index usage and fast performance.  The need for a query like this suggests a possible design issue.
Comment: Could you provide your table spec?
Comment: +1 @KM, while i don't see anything wrong with making your code more concise this does look a little fishy.  You would be wise to take a look at your design and see if there is a better solution to this.
Comment: Thanks KM (+1). This is an existing database and I'm looking for "junk" records to get rid of. I might need to show my code to some people so that's why I'm aiming at conciseness.
Answer: I believe you can just reverse the columns and constants in your first example:
SELECT * FROM table1 WHERE 'string1' NOT IN (column1, column2, column3);

This assumes you are using SQL Server.
UPDATE:
A few people have pointed out potential null comparison problems (even though your desired query would have the same potential problem).  This could be worked around by using COALESCE in the following way:
SELECT * FROM table1 WHERE 'string1' NOT IN (
     COALESCE(column1,'NA'),
     COALESCE(column2,'NA'),
     COALESCE(column3,'NA')
);

You should replace 'NA' with a value that will not match whatever 'string1' is.  If you do not allow nulls for columns 1,2 and 3 this is not even an issue.
Comment: If the columns are nullable this won't return the right results.
Comment: try this (in SQL Server), which uses this solution, yet does not return the proper results (because of NULLs): `declare @X table (id int, column1 varchar(3), column2 varchar(3), column3 varchar(3));INSERT @X VALUES (1,null,null,null);INSERT @X VALUES (2,null,'ABC','ABC');INSERT @X VALUES (3,'ABC','X','ABC');INSERT @X VALUES (4,'ABC','X',null);INSERT @X VALUES (4,'ABC','ABC','ABC');SELECT * FROM @X WHERE 'x' NOT IN (column1, column2, column3);` any row that has at least 1 null in column1 or column2 or column3 will not be returned even if the target string is not in any of the columns.
Comment: Are you sure.  Wouldn't this return the same as his last example?  I see your point about null comparisons, but his last example would have the same issue wouldn't it?
Comment: At least some databases (the one I'm working on this moment, in fact) treat unquoted text in an IN list as string literals (as if they were quoted) and not as identifiers.
Comment: @Larry, this response `assumes you are using SQL Server` and it seems to work alright in there.  What are you using?
Comment: I'm using R:Base (not that I expect the OP is).
Comment: @KM, what is the proper result?  if you run the following sql (which is the same as what he said he wanted to reproduce) it returns the same as mine: `SELECT * FROM @X WHERE column1 <> 'x' AND column2 <> 'x' AND column3 <>'x'`
Comment: To handle NULLS in SQL Server could do `SELECT * FROM @X WHERE 'X' NOT IN (SELECT C FROM (SELECT column1 AS C UNION ALL SELECT column2 UNION ALL SELECT column3) D WHERE C IS NOT NULL)` (Not suggesting **should** though!)
Comment: Abe Miessler, the OP's code you refer to is flawed as well, as it misses rows that have any NULL values.  I would think a solution to  `Is there a single SQL (or its variations) function to check not equals for multiple columns at once` would be general enough to handle NULLs
Comment: @Martin Smith, this would be better to use a "magic number" approach: `select * from @X WHERE 'x' NOT IN (ISNULL(column1,''), ISNULL(column2,''), ISNULL(column3,''));` but nothing is going to use an index unless there is a redesign.
Comment: @KM, I see your point but you are still assuming that columns 1,2 and 3 are nullable which is not mentioned anywhere in the OP.  I have added a workaround that will allow for nulls. @Martin, what do you think about my updated work around?
Comment: @KM, updated version of the query for your testing pleasure: `SELECT * FROM @X WHERE 'x' NOT IN (coalesce(column1,'NA'), coalesce(column2,'NA'), coalesce(column3,'NA'));`
Answer: No, there is no standard SQL way to do this.  Barring any special constraints on what the string fields contain there's no more concise way to do it than you've already hit upon (col1 <> 'String1' AND col2 <> 'String2').
Additionally, this kind of requirement is often an indication that you have a flaw in your database design and that you're storing the same information in several different columns.  If that is true in your case then consider refactoring if possible into a separate table where each column becomes its own row.
Comment: +1, I agree 100% `Additionally, this kind of requirement is often an indication that you have a flaw in your database design`
Comment: +1. I'm glad you pointed out that he may not have a normalized database.
Answer: The most concise way to do this is
SELECT * FROM table1 WHERE column1 <> 'string1'
                       AND column2 <> 'string1'
                       AND column3 <> 'string1';

Yes, I cut & pasted that from your original question. :-)
I'm more concerned why you're wanting to compare against all three columns.  It sounds like you might have a table that needs normalization.  What are the actual columns of column1, column2 and column3.  Are they something like phone1, phone2, and phone3?  Perhaps those three columns should actually be in a subtable.
Comment: Lately we've figured that our database had a lot of junk records, in which there are a lot of columns that are just empty strings. I'm looking for those records to delete. I have no control over the database design. Thanks for your response.