Q&A and generalisation: On fractions and square roots

Question:
What is the value of $$\frac{294395}{294393}-\left(\frac{588789}{588787}\right)^2?$$

Motivation
Have you ever tried pressing the square root button repeatedly on your scientific calculator to see how quickly (or slowly) a number reached $1$? If you were lucky, you may have seen that during this process, fractions come up on the screen of your calculator. It is famously known that the square root of any non-square positive integer is irrational, so it must be strange to see that rational values appear. The reason: most scientific calculators only evaluate arithmetically up to $12$ decimal places.
I came across the integer $1539929$ when trying out the RanInt#( function on my CASIO, with limits at $1$ and $10$ million. I then decided to perform the process described above. The first few iterations are as follows: $$1240.93..., 35.22, ..., 5.93..., ..., 1.003484..., ..., 1.000217..., 1.000108..., \frac{147201}{147193}, \frac{147199}{147195}, \frac{73599}{73598}, \frac{294395}{294393}, \frac{588789}{588787},...$$
Using the last two fractions as an example, I tried to find out by how much the calculator was out. That is, does $$\frac{294395}{294393}-\left(\frac{588789}{588787}\right)^2=0?\tag{1}$$
Proof that $(1)$ is false
If you insert the LHS of $(1)$ into your calculator, it would return the value $0$. This is not actually the case.
Suppose that $(1)$ is true. Then $294395(588787^2)=294393(588789^2)$.
Now $588787^2$ ends in $9$, so LHS ends in $5$, and $588789^2$ ends in $1$, so RHS ends in $3$.
We have reached a contradiction, since no integer ending in $5$ can end in $3$. This disproves $(1)$.
What is the value of the LHS of $(1)$?
Let $x=588789$ and $y=294395$. Then we can write the LHS as $$\frac{y}{y-2}-\left(\frac{x}{x-2}\right)^2$$ Call this $z$. Furthermore, $x=2y-1$, so $$z=\frac{y}{y-2}-\left(\frac{2y-1}{2y-3}\right)^2=\frac{y(2y-3)^2-(y-2)(2y-1)^2}{(y-2)(2y-3)^2}=\frac2{(y-2)(2y-3)^2}$$ Now use your calculator to plug in the value of $y$. You get $$\frac{294395}{294393}-\left(\frac{588789}{588787}\right)^2=1.959...\times 10^{-17}=1.96\times 10^{-17}$$ to $3$.s.f.
Generalisation
Consider the expression $$z=\frac{y}{y-a}-\left(\frac{cy-d}{cy-d-b}\right)^2$$ where $a,b,c,d$ are positive integers. The calculations above are very useful when $ac=2b$ and $b=2d$ (check!) What is $z$ in this case? Surprisingly, it turns out that it is independent of $b,c$ and $d$: $$z=\frac{a^3}{(y-a)(4y-3a)^2}$$
Example of generalisation
When $x=1120416$ and $y=373473$. This can 't be done using a calculator. But using the above method, we find that $$z=7.69\times 10^{-17}$$ to $3$.s.f.
There are of course many more generalisations that could be made (for instance, cube roots instead fo square roots). But I'll leave these for you to think about. :)
Answer: You've got a pair of numbers around $3\times10^5$ and a pair of numbers around $6\times10^5$. At a glance, you can see that $(3\times10^5)\times2=(6\times10^5)$ so we can simplify the problem somewhat.
Let $x=294395$. Then $2x=588790$ and the problem becomes:
$$\frac{294395}{294393}-\left(\frac{588789}{588787}\right)^2
\\
=\frac{x}{x-2}-\left(\frac{2x-1}{2x-3}\right)^2
\\
=\frac{x(2x-3)^2-(x-2)(2x-1)^2}{(x-2)(2x-3)^2}
\\
=\frac{2}{(x-2)(2x-3)^2}
$$
Can you take it from here?
Comment: That's what I've got in my answer (with $y$ instead of $x$)
Comment: @TheSimpliFire So you do. It makes it a bit easier to just use one variable, instead of two. The next step could be finding the value of $(x-2)(2x-3)^2$, for $x=294395$. If you wanted an approximate value, it could be $(x-2)(2x-3)^2\approx 4x^3$, which has a percentage error of just $0.0017\%$.
Answer: The exact value is
$$\frac{2}{102057259984114017}.$$
I computed this using my class Fraction.py.
Answer: Hint:  for the inequality alone, show that $\displaystyle 1+\frac{4}{n-1} \gt \left(1 + \frac{2}{n}\right)^2\,$ for $\,n \gt 1\,$, then:
$$\;\displaystyle \frac{294395}{294393} = \frac{588790}{588786} = 1 + \frac{4}{588786}\gt \left(1+\frac{2}{588787}\right)^2 = \left(\frac{588789}{588787}\right)^2$$


Derivative of an integral variable confusion?

Question: If $f(x)$ is continuous and differentiable from $[-\infty,+\infty]$ and we have the function,
$$g(x) = \int_{a}^{x}f(t)dt$$
Then apparently the derivative of the above function is equal to $f(x)$, that is $g'(x) = f(x)$
I am just curious how this is possible mathematically? If we take the derivative of the above function shouldn't it be equal to $f(t)$ and not $f(x)$?
This is what is confusing me.  Or is this one of those things that I should just memorize and not bother understanding? Because lately there have been a lot of similar confusions that I've been having with Calculus.
Comment: Be carefull with your use of variables. It doesn't, strictly speaking, make sense to call $f(x)$ or $f(t)$ or $f(whatever)$ the derivative of anything - $f(x)$ is a *value*, not a function. The function is $f$, *without* an argument applied to it. Note that is *does* make sense to say $g'(x) = f(x)$ to indicate that the functions are identical, because free variables (like $x$ here) are often assumed to be all-quantified, i.e. one reads that as: For all $x$, $g'(x) = f(x)$.
Comment: The upper limit of integration is the independent variable. The "dummy variable" is $t$.
Comment: The notation $\int \limits _a^xf\color{red}{(t)}\mathrm d\color{red}t$ is bad. The integral takes as inputs functions, it doesn't take functions evaluated at points as the notation suggests. A proper notation is $\int \limits_a^x f$ and where's your $t$ now?
Comment: Thanks for the correction of notation.  It now makes more sense considering the limit of integration is the independent variable.
Answer: $g(x)$ is a function of $x$ so when you differentiate it you should get a function of $x$. The variable used inside the integral sign "t" is the variable of integration. You see
$\sum_{i=1}^{n} a_i$ and $\sum_{p=1}^{n} a_p$ represent the same sum.
Answer: Since t is a dummy variable it drops out when we integrate over the range
$$\int^{x}_{a}f(t).dt=[g(t)]^{x}_{a}=g(x)-g(a)$$
Differentiating this with respect to we get $g'(x)$ as required (since $g(a)$ is independent of x so we treat it as constant).
Answer: Strictly speaking $f(x)$ is not a function but a real number. The function is $f$. Hence if you define the function $g$ by:
$$
g(x) = \int_0^x f(t)\, dt
$$
you could say that the derivative of $g$ is $f$ without need to choose a variable name. This means that for all $x$ you have
$$
g'(x) = f(x).
$$
But you can also say that for all $t$ you have $g'(t) = f(t)$. However this sounds wrong because $t$ is a scoped variable already used inside the integral.


No ground on door bell transformer

Question: I replaced my doorbell transformer last night with a higher power one in preparation for a video doorbell. When I took the old transformer out (it was attached to my main panel via knockout and piggy backed onto the office circuit) I noticed the ground wire was clipped. I assume it was being grounded by being secured to the metal panel.
The new transformer has a plastic knockout connection. When I installed the new one I didn't cut the ground but I did put the ground with the neutral wire under the neutral wire nut. The wire was short so there is a jumper from the bonded neutral bar up to the transformer. I assumed this would be okay as both wires would land on the bonded neutral bar on the panel anyways. Is this okay? Or should I separate the white and green wire and run a separate green wire to the neutral bar?
Comment: Don't land ground and neutral together. The bars in the panel are a special case. Did this transformer come with any installation instructions?
Comment: Okay I will separate the neutral and ground. Yes the instructions were straightforward and said to connect each of the wires. I just assumed since the ground and neutral were bonded at the panel that I could be lazy and not put another wire in for the ground. My bad. Thank you!
Answer: Assuming I understand this correctly, that you connected neutral and ground together in a wire nut inside the main panel, What you did was almost certainly safe but not according to code. According to code, the only place neutrals and grounds can be mixed together is on the neutral bar of a true main panel. Which gives you two choices:

Extend neutral and ground separately to the neutral bar
Extend neutral to the neutral bar and ground to the ground bar (assuming there is a separate ground bar).

The concern is that while right now this is a true main panel, in the future it could become a subpanel to either a bigger main panel or to a "meter main" to satisfy newer code to provide an outside disconnect. The more of a mess your panel is, the harder it will be to separate grounds and neutrals if you ever need to. During my heavy-up, my electrician avoided putting grounds on the neutral bar as much as possible, though there were a few old cables where putting the ground on the neutral bar avoided having to extend the ground wire, so he put those on the neutral bar.
Or just trade it in for a transformer with metal.
Comment: Yes that's exactly what I did. I have some bare copper wire I can run to extend the ground down to the bar. I'll keep the neutral on the existing white wire. I will do that when I install the doorbell tomorrow. Thank you.

No ground on door bell transformer


Proper way to kill all the open connections in Realm

Question: It is very difficult to find where the connection is open. Is there any way I can force kill all the open connections to realm ?
Comment: Don't know why this question was downgraded, it's quite valid. It's as if Realm DB, by its design, is forcing a specific app design as well as business logic on the application. Rather unfortunate and quite frustrating at times. I just wish the example link provided in the answer below were more helpful.
Answer: No there isn't. You will need to close the Realm on all threads you have open. Note that Realm uses a internal cache that is reference counted, so every call to getInstance() has to be matched by a close() call in order to fully close the Realm.
You can see this answer for a good pattern on how to achieve this: Android, using Realm singleton in Application


How to get total workers by button?

Question: my requirement like this
when i adding workers in select workers tree view, then need to add total of them right side bottom total workers field.its ok its show when i'm going to save or when i clicked the (update) button.
i refer the purchase module but i can't find what function exaclty called when that button clicked.
my whole code uploaded to here@GitHub
refer line 397 in bpl_view.xml and line 335 in bpl.py
as per purchase module i wrote function.but its have only return statement.thats also confused to me.
def button_total(self, cr, uid, ids, context=None):
    return True

please advice me on this issue & please tell me why when clicked the button records save automatically.?its have only return True statement. ? ?
Answer: Write this code:
def button_total(self, cr, uid, ids, context=None):
    tea_worker_line_ids = self.browse(cr, uid, ids[0], context=context).selected_tea_workers_line_ids or []
    total_tea_worker = len(tea_worker_line_ids)
    self.write(cr, uid, ids, {'total_workers': total_tea_worker}, context=context)
    return True

How to get total workers by button?


How can I remove wax from a wooden counter so I can resurface it with Danish oil?

Question: A wooden (beech) kitchen counter has been treated with cheap wax in the past, and is now discolouring because of food preparation and constant splashing. I've decided to make a better job using Danish Oil but first need to remove the wax from the beech.
I have performed this routine 4 or 5 times:

Soak with White Spirit.
Sand with 120 grade along the grain.
Wash with hot soapy water.

The reason I've done this so many times is because there always seems to be more wax coming out of the wood.
My question: Do I have to continue sanding and washing the wood to remove any trace of wax, or have I done enough already to apply the Danish Oil?
I'm planning to rub the Danish Oil in to the wood with a cloth, leave overnight, then buff it up in the morning, possibly applying more the following night depending on the colour.
If anyone has any advice for producing a really nice water resistant finish, that will be greatly appreciated.
The worktop is as pictured below, to help understand what type of wood I am working with (not my photograph, but same product) :
Comment: Is the counter made such that the surface is the end-grain of the wood?
Comment: @JayL does the photograph answer that?
Comment: In the picture the surface of the counter is the edge grain of the wood, and the left edge shows the end grain.  End grain is sometimes used as the surface of butcher blocks and wood countertops but it can really absorb (and sometimes weep back out) liquids.  Doesn't sound like the problem you're having though.
Answer: If the surface is edge grain and the previous finish was only wax, wiping down with mineral spirits and then sanding using progressively finer grits up to 220 or so should be pretty good preparation to refinish.  Skip the soap and water treatment as it won't dissolve any wax and only complicates finishing.  Before applying any finish the wood should be smooth and dry.  Any staining or blotching you can see is not going to be hidden too much by a clear finish - it's sometimes possible to bleach out stains but this is tricky to do well.
If you are still getting something soaking back up after sanding down to the raw wood, it could be a prior mineral oil treatment.  Mineral oil never hardens and is often used on wooden butcher blocks and countertops.  Simply reapplying more would be one refinishing option.  It's easy (you just apply until it is no longer absorbed) but you have to reapply it frequently.  Inexpensive pure mineral oil can be found in a pharmacy (it's sold as a laxative).
Another option would be a pure tung oil finish.  It would be slightly more expensive but a little more water resistant.  You can get it from a woodworking or finishing supplier.  Most "tung oil finishes" sold by hardware stores are not actually tung oil so check the labels carefully if you go this route.  It would be applied and reapplied similarly to mineral oil.
Some "Danish oil" finishes are a blend of varnish, oil, and thinner, and others contain only thinned varnish.  Generally one applies "Danish oil" in light coats such that a film is not really built up on the surface of the wood.  Often wax is then applied over it.  This feels nice on furniture but it is going to be less durable that a slightly thicker application of regular varnish applied with a brush or thinned and then wiped on in several coats.
The mineral oil or tung oil would be my choices for a counter that you are actually going to cut on.  On the other hand if you don't plan to cut with knives directly on the counter, and if you are able to prepare the counter down to a clean, dry, smooth surface, a wiping varnish is probably the most durable and best looking option.
Answer: I would use Tung-oil instead. It offers very good protection and is easy/forgiving to apply. I like the Waterlox brand but any will do. It doesn't really like wax though and will soften in areas that still have it but it will not peal or become harmful. If soft or sticky spots do come up they can be removed with a little food safe mineral spirits and a rag then more tung-oil applied. There's a good chance that your wood did get a lot of wax deep into the grain so it will be very difficult to get it all out without some extensive sanding. Use acetone to remove as much as possible. It is better than mineral spirits. Let the wood soak it up and it will desolve deeply imbedded wax. Be careful not to get it on your floor or cabinets or it could damage their finish.


Globbaly Host a webservice of C#

Question: I have created a webservice in c# which I want to call in my Android application. I want to host this webservice globally*(free, as this is only for testing purpose)*, so that it can be easily call. I have done some google and I found this link usefull:
http://www.windowsazure.com/en-us/documentation/
But I am not sure if the WindowsAzure will provide me free hosting or not.
I want some more options.
Might be this is some off-topic question, but I am new in hosting and this is some how important for me. Please help.
Update
I want free web hosting sites, not paid as I already mentioned above.
2nd Update
https://cloud.google.com/products/?utm_source=google&utm_medium=cpc&utm_campaign=appengine-search-global
Found one more link but also not sure about that it will provide free web hosting!!!!
Answer: I tried a lot and atlast I find a site:
http://www.aspspider.com/
This is very easy for the new users. I have just succesfully host my webservice here.

Globbaly Host a webservice of C#


How to find number of specific column in csv using pandas?

Question: This is my csv file.

Iam uploading this data to db using python pandas.How to find the number of fee columns are there(fee_1,fee_2,fee_3)?. Because the start,end,fee columns are dynamic. I need to upload based on the number of fee columns.
If number of fee columns is 2 means i need to upload this,
"slot_fee":[{"start": i['Start_1'],"end": i['End_1'],"fee": i['Fee_1']},{"start": i['Start_2'],"end": i['End_2'],"fee": i['Fee_2']}]
If it is 3 means i need to upload this,and so on.
"slot_fee":[{"start": i['Start_1'],"end": i['End_1'],"fee": i['Fee_1']},{"start": i['Start_2'],"end": i['End_2'],"fee": i['Fee_2']},{"start": i['Start_3'],"end": i['End_3']]
Can anyone help me with the python pandas code for this?
Comment: You may want to look at formatting your question better for clarity:
https://stackoverflow.com/editing-help#tables
Answer: If I understand your question correctly this might help :
df.columns[df.columns.str.startswith('Fee_')]

it gives you the list of columns that start with Fee_, if you want the last one you can add
df.columns[df.columns.str.startswith('Fee_')][-1]

Comment: It is giving only  this output. Index([], dtype='object')
Comment: can you upload an example of the dataframe i can reproduce ? @rovoda
Comment: I have added the dataframe above. Need the number of  fee columns.


how to install g77 on ubuntu 12.04

Question: I want a workin g77 compiler on my Ubuntu 12.04 64 bit laptop.
so did the following:

I change the sources.list by adding the following lines:

deb http...hu.archive.ubuntu.com/ubuntu/ hardy universe
  deb-src ..//hu.archive.ubuntu.com/ubuntu/ hardy universe
  deb http:...hu.archive.ubuntu.com/ubuntu/ hardy-updates universe
  deb-src ..//hu.archive.ubuntu.com/ubuntu/ hardy-updates universe

2. then I on a terminal i did the following:
<code>sudo apt-get update
sudo apt-get install g77
</code>
Things looked very nice then. But when I tried to compile with g77 on my Fortran77 program. I got the following errors:
<code>/usr/bin/ld: cannot find crt1.o: No such file or directory
/usr/bin/ld: cannot find crti.o: No such file or directory
/usr/bin/ld: cannot find -lgcc_s
collect2: ld returned 1 exit status
</code>

3. Why doesn't the g77 work properly. Many people need g77 why cannot Ubuntu offer a workable g77?

4. Please Help me !
Thanks from a ubuntu-beginner
Answer: I had the same problem, with SAME SYSTEM today and SOLVED. It may serve for you.
If you are an expert, you can jump to the end for a 3 line solution or follow my way,
that was:
1)
$ locate crt1.o
/usr/lib/x86_64-linux-gnu/Mcrt1.o
/usr/lib/x86_64-linux-gnu/Scrt1.o
/usr/lib/x86_64-linux-gnu/crt1.o
/usr/lib/x86_64-linux-gnu/gcrt1.o
/usr/lib32/Mcrt1.o
/usr/lib32/Scrt1.o
/usr/lib32/crt1.o
/usr/lib32/gcrt1.o
As I'm using x86_64, just copied "/usr/lib/x86_64-linux-gnu/"
2)
$ locate crti.o
/usr/lib/x86_64-linux-gnu/crti.o
/usr/lib32/crti.o
It was the same as above, so, nothing new.
3a)
$ locate lgcc_s
NOTHING
panic...
But, I tried:
3b)
$ locate gcc_s
/lib/i386-linux-gnu/libgcc_s.so.1
/lib/x86_64-linux-gnu/libgcc_s.so.1
/usr/lib/gcc/x86_64-linux-gnu/4.4/libgcc_s.so
/usr/lib/gcc/x86_64-linux-gnu/4.6/libgcc_s.so
/usr/lib/gcc/x86_64-linux-gnu/4.6/libgcc_s_32.so
/usr/lib/gcc/x86_64-linux-gnu/4.6/32/libgcc_s.so
/usr/lib32/libgcc_s.so.1
/usr/libexec/autopackage/libgcc_s.so.1
Now, I just choose the older version, 4.4, so just copied "/usr/lib/gcc/x86_64-linux-gnu/4.4/"
The software in question was in a makefile. Openned the one and changed:
(from)
FFLAGS=-g -O2
(to)
FFLAGS=-g -O2 -B/usr/lib/x86_64-linux-gnu/ -B/usr/lib/gcc/x86_64-linux-gnu/4.4/
To be simple: I just add -B for each path I copied
If you are using the g77 direct in terminal, may be:
$ g77 (...) -B/usr/lib/x86_64-linux-gnu/ -B/usr/lib/gcc/x86_64-linux-gnu/4.4/ (...)
Expert:
1) Use the locate to find the path of crt1.o, crti.o and-lgcc_s (search for gcc_s);
2) Copy the paths for your distro/bits;
3) Add a "-B path_1" "-B path_2" (where path_i are the paths above) in your g77 compile call.
EDIT
cogitoergosum,  In my case, the software is VERY old and fort77, gfortran and f77 gave tons of problems. I first successfully compiled with ifort (Intel Fortran compiler). But I tried g77 for an opensource alternative. And it works!
Answer: Try installing fort77 (sudo apt-get install fort77) which also installs f2c. Use f77 which invokes f2c translator to compile/link. Good luck.

how to install g77 on ubuntu 12.04


Redirecting from ane action to another controller action in mvc

Question: This is my code where I want to post some data(date of calendar here) to "index" action of "home" controller and want to save this data in the database and at the same time I want to redirect to another action of another controller i.e "Index" action of "Home" controller
here is my jquery code below,
  function getDate() {

            $('.cal_daybox').on('click', function () {

           var timestamp = parseInt($(this).attr('id'));

                var day = new Date(timestamp);

                alert("You clicked " + day.toDateString());

                var url = '@Url.Content("~/Home/Index")';
                var date = day.toDateString();
                $.ajax({
                    type: "POST",
                    url: url,
                    data: { date: day.toDateString() },
                    dataType:"json"
                });
             return false;
            });

EventsController.cs
  public ActionResult Index()
    {
        return View(db.Events.ToList());
    }

HomeController.cs
[HttpPost]
    public ActionResult Index(DateTime date)
    {

            Date dt = new Date();
            dt.StartDate = date;
            db.Dates.Add(dt);
            db.SaveChanges();
            return RedirectToAction("Index", "Events", new { id = dt.DateID });
    }

Comment: index action of events:: public ActionResult Index()
        {
            return View(db.Events.ToList());
        }
Comment: the issue is I am not able to post data and redirect to another page at the same time,Because in debugger it is showing me redirection but in actual  it is not getting redirected.
Comment: Ther is a lot missing here .you should not be posting a DateTime firstoff.it has to be some viewmodel.is your view strongly typed to a ViewModel class
Comment: I have tried by taking dateId as int but still it is not working.
Comment: is your post happening atleast?
Comment: yes.I am able to save dt.StartDate into database but only problem that it is not redirecting to the index action of Events controller
Comment: can u check my edited answer i have modified the param now for index
Comment: I had also tried it.but I think it is not redirecting because of the ajax post method that I used in the Index view of Home controller(You can check it in the first code block) to post the date.am I write?
Comment: I had also tried it.but I think it is not redirecting because of the ajax post method that I used in the Index view of Home controller(You can check it in the first code block) to post the date.am I write?
Answer: Your Index Action of Events Controller does not have a parameter to recieve the Dateid value.It is unable to Find a Action that could recieve a DateId val.
You need to either modify your existing Action or add an Action Overload like this
public ActionResult Index(DateTime dateId)
{
    //Do something with the val
}

public ActionResult Index()
{
    return View(db.Events.ToList());
}

Answer: you are calling controller action using ajax so in this case you have to change you action method and jquery call like this:

         [HttpPost]
         public ActionResult Index(DateTime date)
         {

            Date dt = new Date();
            dt.StartDate = date;
            db.Dates.Add(dt);
            db.SaveChanges();
            return Json(dt.DateID,JsonAllowBehaviour.AllowGet);
          // return RedirectToAction("Index", "Events", new { id = dt.DateID });
         }
    function getDate() {

            $('.cal_daybox').on('click', function () {

           var timestamp = parseInt($(this).attr('id'));

                var day = new Date(timestamp);

                alert("You clicked " + day.toDateString());

                var url = '@Url.Content("~/Home/Index")';
                var date = day.toDateString();
                $.ajax({
                    type: "POST",
                    url: url,
                    data: { date: day.toDateString() },
                    dataType:"json",
                    onsuccess:function(id)
                                 {
window.location='/Events/Index?Id='+id;
                                  }
                });
             return false;
            });

And also please change your index action of Events Controller like below:
public ActionResult Index(int Id=0)
{
    return View(db.Events.ToList());
}


android forensic

Question: I would like to retrieve the browser history from the com.android.browser and save it into a file in sdcard. I am able to do soo for the contacts but not the browser history.Don't know what went wrong. They only prompt the error bind or column index out of range: handle 0x27a6d0.
What would be the best format for the file to be xml, txt or??
These are my codes
package fypj.ReadContacts;

import android.app.Activity;
import android.os.Bundle;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Browser;
import android.provider.Browser.BookmarkColumns;
import android.provider.ContactsContract;
import android.util.Log;
import android.widget.TextView;
import android.provider.ContactsContract.CommonDataKinds.StructuredPostal;

public class ReadContacts extends Activity {

   // To suppress notational clutter and make structure clearer, define some shorthand constants.

   private static final Uri URI = ContactsContract.Contacts.CONTENT_URI;
   private static final Uri PURI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
   private static final Uri EURI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
   private static final Uri AURI = ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI;
   private static final String ID = ContactsContract.Contacts._ID;
   private static final String DNAME = ContactsContract.Contacts.DISPLAY_NAME;
   private static final String HPN = ContactsContract.Contacts.HAS_PHONE_NUMBER;
   private static final String LOOKY = ContactsContract.Contacts.LOOKUP_KEY;
   private static final String CID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;

   private static final String EID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
   private static final String AID = ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID;
   private static final String PNUM = ContactsContract.CommonDataKinds.Phone.NUMBER;
   private static final String PHONETYPE = ContactsContract.CommonDataKinds.Phone.TYPE;
   private static final String EMAIL = ContactsContract.CommonDataKinds.Email.DATA;
   private static final String EMAILTYPE = ContactsContract.CommonDataKinds.Email.TYPE;
   private static final String STREET = ContactsContract.CommonDataKinds.StructuredPostal.STREET;
   private static final String CITY = ContactsContract.CommonDataKinds.StructuredPostal.CITY;
   private static final String STATE = ContactsContract.CommonDataKinds.StructuredPostal.REGION;
   private static final String POSTCODE = ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE;
   private static final String COUNTRY = ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY;

   private static final Uri URI1 = android.provider.Browser.BOOKMARKS_URI;
   private static final String bHistoryTITLE = Browser.BookmarkColumns.TITLE;
   private static final String bHistoryURL = Browser.BookmarkColumns.URL;
   private static final String bHistoryBOOKMARK = Browser.BookmarkColumns.BOOKMARK;
   private static final String bHistoryVISITS = Browser.BookmarkColumns.VISITS;
   private static final String ID1 = Browser.BookmarkColumns._ID    ;
   //private static final String BID = Browser.BookmarkColumns.
   //private static final String DNAME = Browser.BookmarkColumns.DISPLAY_NAME;
   //private static final String HPN = ContactsContract.Contacts.HAS_PHONE_NUMBER;
   //private static final String LOOKY = Browser.BookmarkColumns.LOOKUP_KEY;

   private String id;
   private String lookupKey;
   private String name;
   private String street;
   private String city;
   private String state;
   private String postcode;
   private String country;
   private String ph[];
   private String phType[];
   private String em[];
   private String emType[];

   private String id1;
   private String URL;
   private String BTitle;
   private String BURL;
   private String BBOOKMARK;
   private String BVISITS;
   private String browserTITLE[];
   private String browserURL[];
   private String browserBOOKMARK[];
   private String browserVISITS[];

   private File root;
   private int emcounter;
   private int phcounter;
   private int addcounter;

   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {

      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);

      // Check that external media available and writable
      checkExternalMedia();
      Contacts();
      browser();

   }

   /**  Method to check whether external media available and writable and to find the
      root of the external file system. */

   private void checkExternalMedia () {
      // Check external media availability.  This is adapted from
      // http://developer.android.com/guide/topics/data/data-storage.html#filesExternal
      boolean mExternalStorageAvailable = false;
      boolean mExternalStorageWriteable = false;
      String state = Environment.getExternalStorageState();

      if (Environment.MEDIA_MOUNTED.equals(state)) {
         // We can read and write the media
         mExternalStorageAvailable = mExternalStorageWriteable = true;
      } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
         // We can only read the media
         mExternalStorageAvailable = true;
         mExternalStorageWriteable = false;
      } else {
         // Can't read or write
         mExternalStorageAvailable = mExternalStorageWriteable = false;
      }

      // Find the root of the external storage and output external storage info to screen
      root = android.os.Environment.getExternalStorageDirectory();

   }
   public void Contacts(){
    // Allow for up to 5 email and phone entries for a contact
          em = new String[5];
          emType = new String[5];
          ph = new String[5];
          phType = new String[5];

          /** Open a PrintWriter wrapping a FileOutputStream so that we can send output from a
          query of the Contacts database to a file on the SD card.  Must wrap the whole thing
          in a try-catch to catch file not found and i/o exceptions. Note that since we are writing
          to external media we must add a WRITE_EXTERNAL_STORAGE permission to the
          manifest file.  Otherwise  a FileNotFoundException will be thrown. */

          // This will set up output to /sdcard/download/phoneData.txt if /sdcard is the root of
          // the external storage.  See the project WriteSDCard for more information about
          // writing to a file on the SD card.

          File dir = new File (root.getAbsolutePath() + "/download");
          dir.mkdirs();
          //File file = new File(dir, "phoneData.rtf");
          File file = new File(dir, "phoneData.accdb");

          try{
             FileOutputStream f = new FileOutputStream(file);
             PrintWriter pw = new PrintWriter(f);

             // Main loop to query the contacts database, extracting the information.  See
             // http://www.higherpass.com/Android/Tutorials/Working-With-Android-Contacts/

             ContentResolver cr = getContentResolver();
             Cursor cu = cr.query(URI, null, null, null, null);
             if (cu.getCount() > 0) {

                // Loop over all contacts
                while (cu.moveToNext()) {

                   // Initialize storage variables for the new contact
                   street = "";
                   city = "";
                   state = "";
                   postcode = "";
                   country = "";

                   // Get ID information (id, name and lookup key) for this contact. id is an identifier
                   // number, name is the name associated with this row in the database, and
                   // lookupKey is an opaque value that contains hints on how to find the contact
                   // if its row id changed as a result of a sync or aggregation.

                   id = cu.getString(cu.getColumnIndex(ID));
                   name = cu.getString(cu.getColumnIndex(DNAME));
                   lookupKey = cu.getString(cu.getColumnIndex(LOOKY));
                   // Append list of contacts to the scrollable TextView on the screen.

                   // Query phone numbers for this contact (may be more than one), so use a
                   // while-loop to move the cursor to the next row until moveToNext() returns
                   // false, indicating no more rows. Store the results in arrays since there may
                   // be more than one phone number stored per contact. The if-statement
                   // enclosing everything ensures that the contact has at least one phone
                   // number stored in the Contacts database.

                   phcounter = 0;
                   if (Integer.parseInt(cu.getString(cu.getColumnIndex(HPN))) > 0) {
                      Cursor pCur = cr.query(PURI,  null, CID + " = ?",  new String[]{id}, null);
                      while (pCur.moveToNext()) {
                         ph[phcounter] = pCur.getString(pCur.getColumnIndex(PNUM));
                         phType[phcounter]  = pCur.getString(pCur.getColumnIndex(PHONETYPE));
                         phcounter ++;
                      }
                      pCur.close();
                   }

                   // Query email addresses for this contact (may be more than one), so use a
                   // while-loop to move the cursor to the next row until moveToNext() returns
                   // false, indicating no more rows. Store the results in arrays since there may
                   // be more than one email address stored per contact.

                   emcounter = 0;
                   Cursor emailCur = cr.query(EURI, null, EID + " = ?",  new String[]{id}, null);
                   while (emailCur.moveToNext()) {
                      em[emcounter] =  emailCur.getString(emailCur.getColumnIndex(EMAIL));
                      emType[emcounter] =  emailCur.getString(emailCur.getColumnIndex(EMAILTYPE));
                      emcounter ++;
                   }
                   emailCur.close();

                   // Query Address (assume only one address stored for simplicity). If there is
                   // more than one address we loop through all with the while-loop but keep
                   // only the last one.

                   addcounter = 0;
                   Cursor addCur = cr.query(AURI, null, AID + " = ?",  new String[]{id}, null);
                   while (addCur.moveToNext()) {
                      street = addCur.getString(addCur.getColumnIndex(STREET));
                      city = addCur.getString(addCur.getColumnIndex(CITY));
                      state = addCur.getString(addCur.getColumnIndex(STATE));
                      postcode = addCur.getString(addCur.getColumnIndex(POSTCODE));
                      country = addCur.getString(addCur.getColumnIndex(COUNTRY));
                      addcounter ++;
                   }
                   addCur.close();

                   // Write identifiers for this contact to the SD card file
                        //pw.println(name+" ID="+id+" LOOKUP_KEY="+lookupKey);
                   pw.println(name);
                   // Write list of phone numbers for this contact to SD card file
                   for(int i=0; i<phcounter; i++){
                      //pw.println("   phone="+ ph[i]+" type="+phType[i] + " ("
                         //+ getPhoneType(phType[i]) + ") ");
                       pw.println("   phone="+ ph[i]+" ("
                               + getPhoneType(phType[i]) + ") ");
                   }
                   // Write list of email addresses for this contact to SD card file
                   for(int i=0; i<emcounter; i++){
                      pw.println("   email="+ em[i]+" type="+emType[i] + " ("
                         + getEmailType(emType[i]) + ") ");
                   }
                   // If street address is stored for contact, write it to SD card file
                   if(addcounter > 0){
                      if(street != null) pw.println("   street="+street);
                      if(city != null) pw.println("   city="+city);
                      if(state != null) pw.println("   state/region="+state);
                      if(postcode != null) pw.println("   postcode="+postcode);
                      if(country != null) pw.println("   country="+country);
                   }
                }
             }
             // Flush the PrintWriter to ensure everything pending is output before closing
             pw.flush();
             pw.close();
             f.close();
          } catch (FileNotFoundException e) {
             e.printStackTrace();
             Log.i("MEDIA", "*************** File not found. Did you" +
                " add a WRITE_EXTERNAL_STORAGE permission to the manifest file? ");
          } catch (IOException e) {
                e.printStackTrace();
          }
   }

   /** Method to return label corresponding to phone type code. Data for correspondence from
      http://developer.android.com/reference/android/provider/ContactsContract.CommonDataKinds.Phone.html */

   private String getPhoneType(String index){
      if(index.trim().equals( "1")){
         return "home";
      } else if (index.trim().equals("2")){
         return "mobile";
      } else if (index.trim().equals("3")){
         return "work";
      } else if (index.trim().equals("7")){
         return "other";
      } else {
         return "?";
      }
   }

   /** Method to return label corresponding to email type code. Data for correspondence from
      http://developer.android.com/reference/android/provider/ContactsContract.
      CommonDataKinds.Email.html  */

   private String getEmailType(String index){
      if(index.trim().equals( "1")){
         return "home";
      } else if (index.trim().equals("2")){
         return "work";
      } else if (index.trim().equals("3")){
         return "other";
      } else if (index.trim().equals("4")){
         return "mobile";
      } else {
         return "?";
      }
   }

   public void browser(){
       //create file
       File dir = new File (root.getAbsolutePath() + "/DATASTOREAGE");
          dir.mkdirs();
          File file = new File(dir, "browserHistory.rtf");

          try{
             FileOutputStream f = new FileOutputStream(file);
             PrintWriter pw = new PrintWriter(f);

             // Main loop to query the contacts database, extracting the information.  See
             // http://www.higherpass.com/Android/Tutorials/Working-With-Android-Contacts/

             ContentResolver cr = getContentResolver();
             Cursor cu = cr.query(URI1, null, null, null, null);
             if (cu.getCount() > 0) {

                // Loop over all contacts
                while (cu.moveToNext()) {

                   // Initialize storage variables for the new contact
                   BTitle = "";
                   BURL = "";
                   BBOOKMARK = "";
                   BVISITS = "";

                   // Get ID information (id, name and lookup key) for this contact. id is an identifier
                   // number, name is the name associated with this row in the database, and
                   // lookupKey is an opaque value that contains hints on how to find the contact
                   // if its row id changed as a result of a sync or aggregation.

                   id1 = cu.getString(cu.getColumnIndex(ID1));
                   URL = cu.getString(cu.getColumnIndex(BookmarkColumns.TITLE));
                   //lookupKey = cu.getString(cu.getColumnIndex(LOOKY));
                   // Append list of contacts to the scrollable TextView on the screen.

                   // Query phone numbers for this contact (may be more than one), so use a
                   // while-loop to move the cursor to the next row until moveToNext() returns
                   // false, indicating no more rows. Store the results in arrays since there may
                   // be more than one phone number stored per contact. The if-statement
                   // enclosing everything ensures that the contact has at least one phone
                   // number stored in the Contacts database.

                   phcounter = 0;

                      Cursor bCur = cr.query(URI1,  null, ID1,  new String[]{id1}, null);
                      while (bCur.moveToNext()) {
                         browserTITLE[phcounter] = bCur.getString(bCur.getColumnIndex(bHistoryTITLE));
                         browserURL[phcounter]  = bCur.getString(bCur.getColumnIndex(bHistoryURL));
                         browserBOOKMARK[phcounter]  = bCur.getString(bCur.getColumnIndex(bHistoryBOOKMARK));
                         browserVISITS[phcounter]  = bCur.getString(bCur.getColumnIndex(bHistoryVISITS));
                         phcounter ++;
                      }
                      bCur.close();
                   }

                   // Write identifiers for this contact to the SD card file
                        //pw.println(name+" ID="+id+" LOOKUP_KEY="+lookupKey);
                   pw.println(BTitle+" ID="+id1+" LOOKUP_KEY="+lookupKey);
                   pw.println(BURL);
                   pw.println(BBOOKMARK);
                   pw.println(BVISITS);
                }

             // Flush the PrintWriter to ensure everything pending is output before closing
             pw.flush();
             pw.close();
             f.close();
          } catch (FileNotFoundException e) {
             e.printStackTrace();
             Log.i("MEDIA", "*************** File not found. Did you" +
                " add a WRITE_EXTERNAL_STORAGE permission to the manifest file? ");
          } catch (IOException e) {
                e.printStackTrace();
          }
   }

}

Answer: Your selection column is wrong in the second query of URI1 the line should read:
Cursor bCur = cr.query(URI1,  null, ID1+"=?",  new String[]{id1}, null);

The second query isn't needed though. You are first quering all columns, extracting the ID from all columns. And then doing a nest query on the all columns for a particular id.
You don't need the nest query, the first query will have all the data you need.
The question of the best file format. That would depend on what is going to consume the data you are creating.
Comment: what do you mean by what is going to consume the data??
Comment: When you generate the file with the bookmarks, contracts etc. What are you going to do with it? If it is going to be read by a person then txt, csv makes sense. If a computer is going to read the file then xml or json make more sense.
Comment: oh, the file is to be read by the user. The problem is if i use .txt the data are show are in a mess.Is there anyway to organise it or something like that??
Comment: Not automatically, perhaps use something like a CSV file, then at least the can open it in a spreadsheet app.
Comment: oh, i have change to cvc format instead. I realise that i am only able to retrieve the first url.

android forensic


is it possible to pass argument to a function in this way?

Question: I am trying to pass argument to a function in this fashion
GroupGeneralConfig(selectedGroup = "Group1")

and the function looks like this...
def GroupGeneralConfig(self, *args)
     img = str(args[0]) + "abc"

whenever i execute this program it is throwing like this...
TypeError: GroupGeneralConfig() got an unexpected keyword argument
'selectedGroup'
whats wrong here
Answer: You'll want the double star:
def GroupGeneralConfig(self, **kwargs):
    img = str(kwargs[selectedStreamGroup]) + "abc"

Answer: If you want to use kwargs you should define it first:
def GroupGeneralConfig(self, **kwargs):

Answer: What you are passing in is a keyword argument, change your method to accept keyword arguments first. Like this
def GroupGeneralConfig(self, *args, **kwargs)
     img = str(args[0]) + "abc"

Then you can pass the arguments first and then the keyword arguments, like:
GroupGeneralConfig(arg_x, arg_y, kwarg_x=1, kwarg_y=2)


What are steam gems?

Question: After reading this post on Arqade, I wondered what Steam gems were. I've never heard of Steam gems before.

What are the uses of Steam gems?
Are they some kind of currency?
What do Steam gems do?
How does one get Steam gems?
Answer: Steam Gems - Auction Holiday Event - from Dec 15th to the 18th.
Gems were first created on the 11th for the auction. The auction hosts 2000 games with 100 copies each = 200,000 copies of games to bid for.
Is steam gems a new currency?
Every 1000 gems you can make a bag to trade in the market. You can buy them from the market.
Note: The gems can be made during or after the event and will not disappear.
How does one get steam gems?
Steam gems are earned by converting the items in your steam inventory.
(10-100 range per item)

Cards
Backgrounds
Emoticons

One purpose of steam gems is to convert items normally worthless (3 cents items) into something you can use to bid.
What can I use steam gems for?
They are used for only three things.

One: Bid for games in the auction
Two: Use gems to craft booster packs
Three: Trade in Market

Note: If you place a bid and do not win, the gems will be refunded back to you.
How does the auction work?
Once the auction starts on Dec 15th 10:00, every 45 minutes the next highest bid will be displayed and if the person is still highest they get the copy. So every 45 minutes is a copy given away to highest bider.
Note: It says first auction ends at 10:45.
Auction Rules for Bidding?
"Steam will automatically increase your bid up to this amount to keep yours the highest bid. Your bid will never exceed that max (unless you increase it later)."
"You can increase your bid at any time. You can cancel the bid to return the Gems to your inventory as long as you are not the top bidder."
Why was it up on the 11th and taken down after a few hours?
The reason its not up yet, even though it was last night on the 11th was because of a huge issue with people duplicating the gem bags and selling them for dirt low prices.
They will likely have to back-roll the servers or reverse transactions to redeem this issue.
Is this the steam winter sales?
No, that will take place right after the auction ends on the 18th.
Is there badges for the auction event?
Yes there is about 3 badges.

To create gems
To bid on a game
To win a bid.

(Added questions and answers I think would help clear up any additional questions)
Comment: *"They are exclusive to this event, and are not tradeable"* - if you read the FAQ, you'd see both of these assumptions are incorrect.
Comment: I apologize for the inaccuracy, I assumed that they would change their policy based on the duplication incident that occurred, however I changed my answer to be more accurate with the FAQ.
Comment: I wouldn't assume they'll simply roll back the servers, like they do in a MMO, as that will erase every market transaction, even ones not  related to the auction. It would also erase every transaction where someone used a credit card or other form of payment without any sort of refund. It's possible they might undo everything by creating new transactions that reverse the effect of every auction related transaction, but this won't be easy. Alternatively they could just confiscate the gems and other ill-gotten items of anyone they identify as a cheater.
Comment: Looks like Valve has gone with the reversing the transactions. It looks like the 30,000 gems I bought have gone back the people I bought them from and my Steam balance is back to where it was before the start of the auction.
Comment: Just what: It's now fixed :) | You can buy gems from the market once again.
Comment: @Arperum "Two: Use gems to craft booster packs"
Comment: @GodEmperorDune I completely missed that.
Comment: any changes since then?
Answer: The author was referring to the steam holiday gems.
They are a new feature (released yesterday) in which a steam user can turn their extra junk cards/backgrounds/emotes into "gems."  These gems can be used to buy more cards; or, during the upcoming holiday event only, to bid on games.

Gems themselves are not tradable, but they can be packed/unpacked into "gem sacks" which represent 1000 gems, and are both tradable and marketable.
According to the FAQ, you will keep your remaining gems after the holiday event, and can continue to use them to create more cards.
Answer:
How does the auction work?
Once the auction starts every 45 minutes the next highest bid will be
  displayed and if the person is still highest they get the copy. So
  every 45 minutes is a copy given away to highest bider.

The first auction lasts until December 15th (about 2 days). And not 45 minutes. Steam even says so on the auction-front-page.
Then each auction after that lasts only 45 minutes each. And after each 45 minutes the highest bidder in line gets the game (eliminating the highest that won it in the previous 45 minutes).
Gem auctions = expensive:
With the increase in emoticon/card/etc. prices it's no longer worth it buying them to turn them into gems. Instead hunt for the game cheaper on the humble bundle (has winter sales right now) and other sites that sell Steam Keys which sell them for 50-90% cheaper than you can do with gems. For some reason most games got overpriced (at least for the first auction).
Perhaps the next auctions will make more sense after all the rich people get their copies, the people who had too many useless stuff in their inventory and the traders are gone. I saw some games (converted to gem value) going for over 300% of the regular price, which is just nuts.
Example:
Rogue Legacy costs 1,99 on Humble Bundle right now. But on Steam it costs 11000+ gems. One emoticon is roughly 8 cent and is worth 80 gems. (11000/80)x8/100=11,- bucks. So it's more than 500% more expensive when buying through gems (unless you want to get rid of your useless gems).
I also noticed that Steam secretly increased the gem value over night. Those same emoticons were worth 6-20 gems last night. Now they are 80. I suppose they attempted to deflate the economy a bit because a lot of traders inflated the prices from 2 cent to 8 overnight and attempted to buy the games really cheap.
Alternatively they just randomize the prices for emoticons every day (not sure) to prevent certain trading schemes.
Creating Gems:
Anyway, once it does start (already started now). Just go to your inventory. Click on a card/emoticon/etc. And on the bottom right it will tell you how many gems this is worth along with a button to convert them.
Comment: Just to clear things up the first line I put auction event 15-18th, in that sentence I say "ONCE" the auction starts. So there was a misunderstanding here, other than that nice post.

What are steam gems?


UX/UI implications of user working under stress/time pressure

Question: In UCD, it is often mentioned that the context of usage of the app is very important for designer to keep in mind. I am designing a decision support system application for field healthcare workers that don't have a lot of time for every session, and on the hand need to be precise with what they mark on the app. Of course, I understand that in terms of usability, that means I need to set efficiency goals and benchmarks and verify them through usability tests. I wonder, though, what are additional measures I should consider when designing the UI/UX. This is what I came up with so far:

Clear spatial orientation of the app - every element has its place, consistent through the screens.
Big fonts; big clickable areas for radio buttons/checkboxes;
Clear emphasis on the important things (symptoms/warnings)

Anything else that I'm missing here?
Comment: Immediate feedback (audible, visual) to the operator that an action took place.
Answer: Well, I don't know if this is within your app's scope, but I did something that while not entirely your user case, has some relation because users are people with tremors (Parkinson, Huntington, Alzheimer). Hitting a target is very difficult and frustrating for them, so I recommended (and it was implemented) aural support, which proved to be quite effective since now users can use the app with just voice commands. I think something like this could help in your case.
Some additional reading on the subject:

Semi-aural Interfaces: Investigating Voice-controlled Aural Flows
The Future of Aural Interfaces is Clear in 2017
EYES-FREE INTERACTION WITH AURAL USER INTERFACES
Answer: A couple other things to consider.
Because your users are likely to be interrupted, I'd also auto-save their entries so they don't lose everything if they don't get the chance to finish and hit the Save button.
If they're using different machines through the day, save their state and open to the last page they were on when they sign in, including on a different computer.
Answer: I would also place high importance on some additional areas
1) Performance - Set a performance budget for the development team, mark specific animations/visual flair that can be cut to meet this performance budget, have money earmarked for additional system infrastructure and dynamic scaling plans.
2) Accessibility - What good are the UI elements if they are invisible to the user or inaccessible to certain input devices?
3) Immediate User Feedback - as @Lior specified above.
I highly recommend watching the talk by Eric Meyer Designing for Crisis
Answer: Being tired and stressed is remarkably similar to being drunk. So you could pay someone to get drunk and try to use your app.
There's a guy who actually makes a living doing this, and he has compiled a list of recommendations for websites; several of his guidelines apply to apps as well.

Don't present users with a wall of text
Tell users what the app is for / have a clear purpose for each page
Solve a need (have a clear user story for each feature)
Don't repeat yourself
Hide anything non-essential (progressive disclosure)

to which I would add:

Have a clear workflow. If your app is designed to perform specific tasks frequently (e.g. record a diagnosis), then it needs to be nice and simple to do the task and save the data recorded.

And I totally agree that immediate user feedback is necessary, and auto-saving of input in case they get interrupted.


Adjust the width of the header bar in dashboardHeader in shiny dashboard

Question: Below I have adjusted the height of the whole header bar but I would like to know how to adjust the width as well in order to match the sidebar width which I increased. The toggle button should be where the sidebar ends.
library(shiny)
library(shinydashboard)

ui <- dashboardPage(
  dashboardHeader(title = "saddasda",
    # Set height of dashboardHeader
    tags$li(class = "dropdown",
            tags$style(".main-header {max-height: 50px}"),
            tags$style(".main-header .logo {height: 50px;}"),
            tags$style(".sidebar-toggle {height: 50px; padding-top: 1px !important;}"),
            tags$style(".navbar {min-height:50px !important}"),

    )
  ),
  dashboardSidebar(width = 400,
    # Adjust the sidebar
    tags$style(".left-side, .main-sidebar {padding-top: 20px}")
  ),
  dashboardBody()
)

server <- function(input, output){}

shinyApp(ui, server)

Answer: Two elements need change.

width of "logo" to width of sidebar (400px)
margin-left of "navbar" (where the toggle button starts)

Here is CSS code to be inserted to tags$style:
.main-header .navbar {
    margin-left: 400px;
}

.main-header .logo {
    width: 400px;
}


Select items with one class and not other class jquery javascript

Question: I want to select all items which are in one class and NOT in a set of other classes.  For the first step, I imagined something like this would work, but didn't:
$('.class1,!.class2')

What I actually have is a list of classes that I don't want to select:
dont_select = ['class2', 'class3', 'class4']

And I want to select all items which have class1 but not any class in my array of classes in dont_select (which varies in length).  Thanks,
Answer: Try this:
$(".class1").not("." + dont_select.join(",.") );

Answer: Give this a shot:
$(".class1:not(.class2)")

$(".class1:not(" + dont_select.join() + ")");

Answer: You should use .not function. See below,
dont_select = ['.class2', '.class3', '.class4']
$(selector).not(dont_select.join())

Note: Added a . to the string in dont_select array
Answer: Your simple selector will be as below with Jquery
$('div.class1').not('.class2,.class3');

in the .not function of jquery you can put as much element as you want after ","
or if you have array then you can also go with the suggestion of Vega
dont_select = ['.class2', '.class3', '.class4']
$(selector).not(dont_select.join())

Go Ahead !!!


Adding Duplicate Content Placeholders for Sharepoint 2013

Question: I am working on our intranet that utilizes a custom .master page. One content placeholder that refers to the search functionality of SharePoint is being utilized in the footer ().
In our site mockup, we envisioned two search boxes, one in the top of the site, above the nav and one in the footer. I thought, easy, I just duplicate that content placeholder which brought up a duplication error from Sharepoint.
My question is this: Is there a way to duplicate content placeholders without needing to create a custom placeholder? And if not, is creating a custom placeholder the best way to go about this?
Thank you in advance!
Answer: There are many ways to customize this.

Direct master page change
Add (custom) place holder to master page
Use delegate controls (no master page change required)

Delegate controls allow you to create a regular user control (.ascx) and assign it a sequence number so that it becomes attached to an existing master page control. Using delegates could potentially allow you to attach the same user control to two different controls (delegates).
With all the recent "don't change the master page" buzz, it is becoming ever more relevant, although for on-premise scenarios, you can be a bit more eccentric.
Not only you can't duplicate place holders, but you should also be very careful while removing or even adding existing place holders, no matter how irrelevant they may appear to be. Even their original order matters (e.g. PlaceHolderPageTitleInTitleArea, PlaceHolderLeftNavBar).
refs,
http://blog.sharepointexperience.com/2013/08/missing-apps-you-can-add-with-custom-master-page-in-sharepoint-2013/
http://www.eliostruyf.com/missing-apps-can-add-zone-adding-new-app/
http://www.eliostruyf.com/document-set-view-not-visible-in-sharepoint-2013/
examples,
https://zimmergren.net/sp-2013-some-new-delegatecontrol-additions-to-the-sharepoint-2013-master-pages/
http://www.fivenumber.com/understanding-sharepoint-delegate-control/
Comment: Hello, sir! Thank you for your succinct response! I'll dive into these articles you've posted and come up with a solution that best handles the scenario!


How to manage 3rd-party library in iOS project if its source code needs to be modified in order to be used?

Question: We need to use some 3rd-party libraries in our iOS app project (which is an Xcode project).  The 3rd-party libraries are either managed by Cocoapods or directly added in the project by importing source code files.
Sometimes we need to modify a library's source code in order to actually use it appropriately in our project.  It's easy to make the modification since we have all the source code at our hand, but how can we maintain the modification when some time in the future we upgrade the version of the 3rd-party library?  Is there any tools or best practice out there that can help with this?  And after the upgrade of the 3rd-party library, it will be good if we could differentiate in the code history about which part is done by library upgrade and which part is done by our modification.
Comment: if you use Git ,I think it will catch it and tell you what is the deferent you can see where is your modify. unless they delete that file. But also you can check there git and see what this new v. contain.
Answer: That depends entirely on what your change is...
The best option is to not change the external code. Instead, subclass the part you need to change and use only public API so you should find out early when updating if the subclass needs to change. Unit tests also help.
If you can't subclass then you should fork the external code, then you have to manually merge updates on top of your change when you want them. This is obviously significantly more effort both in terms of importing and managing the code.


What is a tandem breaker (aka duplex, cheater, twin, double-stuff, etc.)?

Question: I keep hearing about tandem breakers, and how they won't work with 240V loads and how they should never be used for a multi-wire branch circuit.  Aside from those issues...
What is a tandem breaker?

(note: they can be thrown independently).
Comment: tandem breakers are usually on the same pole 120v where double pole breakers are 240v. I know it is splitting hairs with wording, but I have been called to a home the dryer did not work after a tandem 30 amp breaker was installed DIY. The drum would turn but no heat because it was only 120v. As far as I know all mfg's call there 240 breakers double pole, and tandem or double stuff are on the same pole. With tandem breakers they Cannot be used with a multi wire branch circuit because that would overload the neutral. A double pole,common trip, or 2 adjacent full sized breakers with handle ties
Answer: It starts with spaces in the panel
A service panel has a basic unit I call a space.  That's apparent when you look at the "knockouts" on the cover.
Electrical power in North America delivers split-phase power. Meaning there are two "legs" or "poles" - L1 and L2 - both 120V from neutral, and opposite-phased so they add up to 240V.

Here's an X-ray of a service panel cover.  See the trick?  The buses are arranged in alternating rows. Every other row is a different pole on both sides. Any single-space breaker gets only one pole and 120V (its circuit also attaches to the neutral bar, not shown) -- but a 2-space breaker has access to both poles and 240V.
A single-space breaker cannot get 240V.  That's very important when we get to duplex breakers.  Now let's fit some breakers.

On the upper right you see a single breaker. This occupies one space and serves one circuit.
On the upper left, you see a 2-pole breaker: this occupies two spaces, and can access both poles L1 and L2.  Both sides will trip together if either side overloads.  This is used for 240V loads, or for multi-wire branch circuits (MWBC).

Backside of a 2-pole or quad breaker.  Note the 2 clips grabbing 2 different poles.
Duplex and friend
On the lower right is the star of the show: the duplex/tandem breaker. This occupies a single space and can only access a single pole.  The sides will not trip together.   It cannot power 240V loads, it must not power MWBCs, and it is generally used for two unrelated circuits.  The entire point of the duplex is to save space in the box.  We often call that a "double-stuff" for obvious reasons, and to emphasize how it's different from a 2-pole.

Back of a duplex breaker. Only one clip to grab one pole.
Lower left is the quad breaker, a 2-pole duplex breaker. Again the purpose is to save space.  It's just what it looks like, 2 duplexes, except it can access both poles L1 and L2, and it has handle-ties so the inner pair will trip together on overload.  That makes it suitable for a 240V load or MWBC.  On this model, the outside pair is also tied together with common trip and can serve 240V loads or MWBC.  Or, you can get these breakers with outer breakers independent.
General Electric's Q-line panels take a different approach to the problem, and you will never find a quadplex in Q-line.
No substitute for spaces
Most panels only allow these double-stuff breakers in certain positions.  Some only forbid it in their labeling, while others actually key the buses so duplex breakers won't fit.  Don't force them.
Nowadays in new or remodel work, most circuits must be GFCI and/or AFCI.  Here's the trick: for most panels, GFCI/AFCI breakers are not available in duplex/tandem/double-stuff. This is why you can no longer add circuits by switching to these, and why being low on breaker spaces is kind of a big deal.  Which is why many of us recommend quite large panels.
The 12-space panel featured here for illustration is terribly small, more befitting a shed than a house.  They are made as large as 60 or even 84 space.  Many will say "40 circuits/30 spaces" meaning they can accommodate double-stuff's in 10 spaces, but only have 30 total. Watch out for that.
Comment: Very nice visuals. A great representation and explanation.
Comment: I would fully agree with the exception tandem breakers are usually on the same pole 120v where double pole breakers are for 240v. I know it is splitting hairs with wording, but I have been called to a home the dryer did not work after a tandem 30 amp breaker was installed DIY. The drum would turn but no heat because it was only 120v. As far as I know all mfg's call there 240 breakers double pole, and tandem or double stuff are on the same pole.
Comment: Also worth noting is that the modern standards for panels that ALLOW "tandem" breakers is for them to be "CTL" listed, meaning "Circuit Total Limitation". Per this standard, the bus bars in the panel are designed such that only a FEW of the spaces will allow tandem breakers, which ensures that users don't try to exceed the total number of possible circuits. Older panels, now referred to as "Non-CTL" had no restrictions, but the breakers for them have slightly altered mounting arrangements and will not work on newer CTL panels.
Comment: Can you elaborate on GE's Q-line and what they do differently, or point to some resource that explains it?
Comment: @jmichas please tell me you turned off your main breaker when you were backfeeding? If not, you could be powering your entire block, and deliver a very unpleasant (read: possibly lethal) surprise to a lineman working on what they *believe to be* a de-energized line.
Comment: @DoktorJ More than that; an interlock is required. Cheapest way to get one of those (and a lot more panel spaces) is a subpanel.
Comment: @DoktorJ Yeah, I was sure to turn off my main and I know I should have an interlock but this was an emergency situation and I needed to power my boiler to prevent pipes from freezing.
Comment: I don't get the reason for quad breakers. I think I have some in my square d panel. I had a new panel put in and it has handle ties across spaces that are weird and unrelated. I have a handle between my basement lights and boiler. Both 15 amp circuits that used to have their own independent breaker, now they are tandem-ized, why? What is the benefit?
Comment: @jmichas Most likely because they are a type of configuration called a "multi-wire branch circuit" *which is actually one circuit with two hots sharing a neutral*.  This allows you to run two *effective* circuits on one /3 cable. But it requires a handle-tie, since it is one circuit.  If you want more info, ask a question with some photos of your panel.
Comment: @Harper-ReinstateMonica You nailed it. I figured that out today, I guess in my old panel the circuits weren't handle tied so it was confusing. I took the cover off the panel to look and found all the handle tied pairs that I had were indeed 12 or 14/3. It came into play more when I was backfeeding the panel during a power outage and found out I couldn't power both legs of the MWBC from a single phase 120 generator. Anyway, thanks for your input.
Comment: @jmichas [This question](https://diy.stackexchange.com/questions/179894/why-are-adjacent-breakers-for-unrelated-circuits-ganged)  just came up, which is on-point to your query.
Answer: The lowdown is panels are sometimes better compact and squeezed down for minimal space saving features.  To achieve this, panel manufacturers use what is called tandem breakers.
Most panels have a maximum allocation for tandem breakers and is abbreviated with a ratio.  For example 12/24 ( 12 space / 24 circuits ).


Nested Dropdown alternative for User Skills in web

Question: I have a searchable dropdown from in which user can add their skills like below :

In the example, "Office Software" is main category and items below this are subcategories that user selects to as her skills. But it is hard for user to find all the items by typing in dropdown and add them, so I am looking for an alternative solution that user can easily navigate from categories and select the desired skill.
Do you have any suggestions ?
Comment: How many categories/subcategories/skills there would be? If you have tons of subcategories, a nested dropdown probably wouldn't be an option.
Comment: @Stefano There are tons of subcategories there and nested dropdown does not meet user needs.
Comment: Why are the users having a hard time finding the items? Do they not know what to type in the search bar? Is the hard part the fact that they can only select one item at a time? Do they want to only see the main categories, and select one to browse through those subcategories?
Comment: @TotZam Yes the hard part is that they can only select on item at a time and finding the items is hard between tons of subcategories. May be seeing the main category and then selecting the subcategories is better approach but I am looking for something different than dropdown.
Answer: I think Nested Dropdowns are well for Top-Down explores.
you can ignore theme if you find a way to bottom-up explore.
For example in Facebook search or any Whether service, you will Search city by name (bottom-up) not the old way: Country -> Province -> City (Top-Down)


django: how to get a substring?

Question: I was modifying satchmo(a python online store project), but I found that I can't use [0, 5] to get the substring in the model. And I found the type is  class 'django.utils.safestring.SafeUnicode' in django string processing.
Does class 'django.utils.safestring.SafeUnicode' support [0, 5] to get the substring as in python?
Comment: you have a comma where you should have a colon for slicing
Answer: Slice it.
http://docs.python.org/tutorial/introduction.html
<code>>>> 'foobar'[0:5]
[Out] 'fooba'
</code>

Update: sure, why not?
<code>>>> django.utils.safestring.SafeUnicode('foobar')[0:5]
[Out] 'fooba'
</code>

django: how to get a substring?


DataTable individula search not working while placed on top of grid

Question: I am new and stuck with following, I got a dataTable grid which does individual search. currently individual search boxes are at the bottom of the grid and the search working properly. But i like to place them at top just underneath the table column heading. i did that already but when i place the search boxes the grid's alignment breaks and search doesn't work. the code html and jquery code is given below.

                        Id
                        Join Date
                        First Name
                        Last Name
                        Website

                        Id
                        Join Date
                        First Name
                        Last Name
                        Website
                </tr

    $(document).ready(function () {

    //for top search box

                     $('#agents thead tr#filterrow th').each(function () {
                    var title = $('#agents thead th').eq($(this).index()).text();
                    $(this).html('<input type="text"      onclick="stopPropagation(event);" placeholder="Search ' + title + '" />');
                });

      var tableInstance  =  $('#agents').DataTable({
                    "bServerSide": true,
                    "sAjaxSource": "@Url.Action("NewPromotersQuery", "Admin")",
                    "bProcessing": true,
                    "type": "POST",
                    "pagingType": "full_numbers",
                    "sServerMethod" : "POST",
                    "searchable":"true",
                    "sScrollX": "100%",
                    "orderCellsTop": true,

                    "aoColumns": [
                           { "sName": "Id" },
                           { "sName": "Join Date" },
                           { "sName": "First Name" },
                           { "sName": "Last Name" },
                           { "sName": "Website" },
                    ]
                    });

                tableInstance.columns().every(function () {
                    var that = this;

                    $('input', this.footer()).on('keyup change', function ()                                    {
                        if (that.search() !== this.value) {
                            that
                                .search(this.value)
                                .draw();
                        }
                    });
                });

                function stopPropagation(evt) {
                    if (evt.stopPropagation !== undefined) {
                        evt.stopPropagation();
                    } else {
                        evt.cancelBubble = true;
                    }
                }

            });

I debug and found, after giving any search box value it hit the tableInstance.columns() code and even i can see the search box value in this.value but no data comes up after draw()
Answer: See this example

$(document).ready(function() {
    // Setup - add a text input to each footer cell
    $('#example thead tr#filterrow th').each(function() {
        var title = $('#example thead th').eq($(this).index()).text();
        $(this).html('<input type="text" onclick="stopPropagation(event);" placeholder="Search ' + title + '" />');
    });

    // DataTable
    var table = $('#example').DataTable({
        orderCellsTop: true
    });

    // Apply the filter
    $("#example thead input").on('keyup change', function() {
        table
            .column($(this).parent().index() + ':visible')
            .search(this.value)
            .draw();
    });

    function stopPropagation(evt) {
        if (evt.stopPropagation !== undefined) {
            evt.stopPropagation();
        } else {
            evt.cancelBubble = true;
        }
    }
});

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.11/css/jquery.dataTables.min.css">

      Name
      Position
      Office
      Age
      Start date
      Salary

      Name
      Position
      Office
      Age
      Start date
      Salary

      Tiger Nixon
      System Architect
      Edinburgh
      61
      2011/04/25
      $320,800

      Garrett Winters
      Accountant
      Tokyo
      63
      2011/07/25
      $170,750

      Ashton Cox
      Junior Technical Author
      San Francisco
      66
      2009/01/12
      $86,000

      Cedric Kelly
      Senior Javascript Developer
      Edinburgh
      22
      2012/03/29
      $433,060

      Airi Satou
      Accountant
      Tokyo
      33
      2008/11/28
      $162,700

      Brielle Williamson
      Integration Specialist
      New York
      61
      2012/12/02
      $372,000

      Herrod Chandler
      Sales Assistant
      San Francisco
      59
      2012/08/06
      $137,500

      Rhona Davidson
      Integration Specialist
      Tokyo
      55
      2010/10/14
      $327,900

      Colleen Hurst
      Javascript Developer
      San Francisco
      39
      2009/09/15
      $205,500

      Sonya Frost
      Software Engineer
      Edinburgh
      23
      2008/12/13
      $103,600

      Jena Gaines
      Office Manager
      London
      30
      2008/12/19
      $90,560

      Quinn Flynn
      Support Lead
      Edinburgh
      22
      2013/03/03
      $342,000

      Charde Marshall
      Regional Director
      San Francisco
      36
      2008/10/16
      $470,600

      Haley Kennedy
      Senior Marketing Designer
      London
      43
      2012/12/18
      $313,500

      Tatyana Fitzpatrick
      Regional Director
      London
      19
      2010/03/17
      $385,750

      Michael Silva
      Marketing Designer
      London
      66
      2012/11/27
      $198,500

      Paul Byrd
      Chief Financial Officer (CFO)
      New York
      64
      2010/06/09
      $725,000

      Gloria Little
      Systems Administrator
      New York
      59
      2009/04/10
      $237,500

      Bradley Greer
      Software Engineer
      London
      41
      2012/10/13
      $132,000

      Dai Rios
      Personnel Lead
      Edinburgh
      35
      2012/09/26
      $217,500

      Jenette Caldwell
      Development Lead
      New York
      30
      2011/09/03
      $345,000

      Yuri Berry
      Chief Marketing Officer (CMO)
      New York
      40
      2009/06/25
      $675,000

      Caesar Vance
      Pre-Sales Support
      New York
      21
      2011/12/12
      $106,450

      Doris Wilder
      Sales Assistant
      Sidney
      23
      2010/09/20
      $85,600

      Angelica Ramos
      Chief Executive Officer (CEO)
      London
      47
      2009/10/09
      $1,200,000

      Gavin Joyce
      Developer
      Edinburgh
      42
      2010/12/22
      $92,575

      Jennifer Chang
      Regional Director
      Singapore
      28
      2010/11/14
      $357,650

      Brenden Wagner
      Software Engineer
      San Francisco
      28
      2011/06/07
      $206,850

      Fiona Green
      Chief Operating Officer (COO)
      San Francisco
      48
      2010/03/11
      $850,000

      Shou Itou
      Regional Marketing
      Tokyo
      20
      2011/08/14
      $163,000

      Michelle House
      Integration Specialist
      Sidney
      37
      2011/06/02
      $95,400

      Suki Burks
      Developer
      London
      53
      2009/10/22
      $114,500

      Prescott Bartlett
      Technical Author
      London
      27
      2011/05/07
      $145,000

      Gavin Cortez
      Team Leader
      San Francisco
      22
      2008/10/26
      $235,500

      Martena Mccray
      Post-Sales support
      Edinburgh
      46
      2011/03/09
      $324,050

      Unity Butler
      Marketing Designer
      San Francisco
      47
      2009/12/09
      $85,675

      Howard Hatfield
      Office Manager
      San Francisco
      51
      2008/12/16
      $164,500

      Hope Fuentes
      Secretary
      San Francisco
      41
      2010/02/12
      $109,850

      Vivian Harrell
      Financial Controller
      San Francisco
      62
      2009/02/14
      $452,500

      Timothy Mooney
      Office Manager
      London
      37
      2008/12/11
      $136,200

      Jackson Bradshaw
      Director
      New York
      65
      2008/09/26
      $645,750

      Olivia Liang
      Support Engineer
      Singapore
      64
      2011/02/03
      $234,500

      Bruno Nash
      Software Engineer
      London
      38
      2011/05/03
      $163,500

      Sakura Yamamoto
      Support Engineer
      Tokyo
      37
      2009/08/19
      $139,575

      Thor Walton
      Developer
      New York
      61
      2013/08/11
      $98,540

      Finn Camacho
      Support Engineer
      San Francisco
      47
      2009/07/07
      $87,500

      Serge Baldwin
      Data Coordinator
      Singapore
      64
      2012/04/09
      $138,575

      Zenaida Frank
      Software Engineer
      New York
      63
      2010/01/04
      $125,250

      Zorita Serrano
      Software Engineer
      San Francisco
      56
      2012/06/01
      $115,000

      Jennifer Acosta
      Junior Javascript Developer
      Edinburgh
      43
      2013/02/01
      $75,650

      Cara Stevens
      Sales Assistant
      New York
      46
      2011/12/06
      $145,600

      Hermione Butler
      Regional Director
      London
      47
      2011/03/21
      $356,250

      Lael Greer
      Systems Administrator
      London
      21
      2009/02/27
      $103,500

      Jonas Alexander
      Developer
      San Francisco
      30
      2010/07/14
      $86,500

      Shad Decker
      Regional Director
      Edinburgh
      51
      2008/11/13
      $183,000

      Michael Bruce
      Javascript Developer
      Singapore
      29
      2011/06/27
      $183,000

      Donna Snider
      Customer Support
      New York
      27
      2011/01/25
      $112,000

JSFiddle Demo
Comment: still search is not working, it is showing "uncaught referanceErroe: stopPropagation is not defined". I exacly followed what u said in example.
Comment: I sorted the above problem but still search not working. Even after writing in the search field jquery search code does't hit.
Comment: Thanks @111 the problem sorted. Here how i sort.
Comment: Initially the code was not working. Then i  just change the table name in  " // Apply the filter" section. In here the table name won't be the same table name we give in HTML id instead debug the jquery code in browser source and check the table id or class. for me the table class name was "dataTable". while i change in the  // Apply the filter" section then all good. HAPPY CODING.


400 Message on VBA

Question: Hello I am trying to refresh a specific pivot table and connection/query/worksheet in the same code. I am getting a 400 error when i run in the first time. If i try again the code runs and works. Im thinking something is wrong in Worksheets("Rejects_Dashboard) line.
Sub RefreshAllPivotTablesAtOnce()
Dim wb As Workbook:         Set wb = ThisWorkbook
Dim con As WorkbookConnection

    For Each con In wb.Connections
        If con.Name = "BPO_STATS_DB" Then con.Refresh
        Worksheets("Rejects_Dashboard").PivotTables("PivotTable2")
        .PivotCache.Refresh
Next con
End Sub

Comment: Could you kindly fix the indentation?
Comment: `Worksheets("Rejects_Dashboard").PivotTables("PivotTable2")` and `.PivotCache.Refresh` should be a single line unless using a with block.
Answer: Some suggestions:
Sub RefreshAllPivotTablesAtOnce()
    Dim wb As Workbook:         Set wb = ThisWorkbook
    Dim con As WorkbookConnection

    'Refresh the folderContents query
    For Each con In wb.Connections
        If con.Name = "BPO_STATS_DB" Then
            con.Refresh
            wb.Worksheets("Rejects_Dashboard").PivotTables( _
                            "PivotTable2").PivotCache.Refresh
             Exit For 'done at this point
        End If
    Next con
End Sub

Comment: Thank you Tim for fixing up my code a bit. I have a command button attached to the module...when i click it the first time i still get a 400 error. If i click it again the code runs.
Comment: Its a blank 404 message. Not sure if it helps but my connection name is bpo_stats_db. If i refresh that con.refresh it should refresh the query i hage tied to that connection right? Then the second part reject_dashboard is my sheetname and pivot2table is a separate pivot table connected to reject_dashboard. Just making sure all that is right, im pretty new to vba.
Comment: Maybe check your query is not set to refresh in the background, or your pivot table will try to update before the query is done refreshing.

400 Message on VBA


C++: wrong template function overload selection

Question: I would like to implement some lazy evaluation in my code. Here is a snippet representative of what I would like to do:
#include <Eigen/Dense>
#include <iostream>

template <int N, int M>
struct S {
  template <typename T>
  S &operator=(const T &src) {
    v = src();
    return *this;
  }

  Eigen::Matrix<double, N, M> v;
};

// If I comment this one the code compiles
template <typename Lhs, typename Rhs>
auto operator+(const Lhs &lhs, const Rhs &rhs) {
  return [&]() { return lhs() + rhs(); };
}

template <typename Lhs, int N, int M>
auto operator+(const Lhs &lhs, const S<N, M> &s) {
  return [&]() { return lhs() + s.v; };
}

template <typename Rhs, int N, int M>
auto operator+(const S<N, M> &s, const Rhs &rhs) {
  return [&]() { return s.v + rhs(); };
}

template <int N0, int M0, int N1, int M1>
auto operator+(const S<N0, M0> &s0, const S<N1, M1> &s1) {
  return [&]() { return s0.v + s1.v; };
}

int main() {
  static constexpr int n = 4;
  S<n, n> s0, s1;
  S<Eigen::Dynamic, Eigen::Dynamic> s2;

  s1.v = 2. * Eigen::Matrix<double, n, n>::Ones();
  s2.v = 3. * Eigen::Matrix<double, n, n>::Ones();

  s0 = s1 + s2;

  std::cout << s0.v << std::endl;

  return 0;
}

I got a compilation error which relates to the fact that when implementing s1 + s2, the first overload of the + operator is selected (and if I comment it, the code works). It seems that for the compiler the first one is considered as the more specialized, whereas to my common sense the last one is the more specialized: the first one accepts whatever arguments, whereas the last one only accepts type related to the template class S.
What is the explanation to that? How can I fix this snippet to make it work while keeping the first overload (which will be required for the lazy evaluation of 'nested' expressions)?
Many thanks!
EDIT: from the answer and comments, I now understand that the problem is related to a conflict between the first overload of the + operator in the snippet and the some overload of the + operator in the Eigen library. The simplified snippet following illustrate that:
#include <Eigen/Dense>
#include <iostream>

template <typename Lhs, typename Rhs>
auto operator+(const Lhs &lhs, const Rhs &rhs) {
  return [&]() { return lhs() + rhs(); };
}

int main() {
  Eigen::Matrix<double, 4, 4> m0, m1, m2;
  m2=m0+m1;
  return 0;
}

Here, the + operator of the snippet is selected, whereas I expected that one of the Eigen's would be selected... Why is that?
Comment: Unconstrainted `operator+` is indeed dangerous.
Comment: Presumably `Eigen::Dynamic` is `-1` or at least an integer that can't be misinterpreted as a column count
Comment: @Jarod42 I get the fact that the first overload catches everything, and so 'pollutes' the whole namespace it is defined into. But being so generic I would expect him not to be selected in this case... Also, do you see a trick to do lazy evaluation without defining such 'generic' operator?
Comment: @janou195: "in this case" - _which_ case? `return s0.v + s1.v;` or `s0 = s1 + s2;` ?
Comment: `requires(requires (lhs() + rhs()))` would be a good first step.
Comment: @Jarod42: I'm not entirely certain if that works as intended, because Eigen also has an `operator()`. I think a custom named concept `LazyEvaluable` would make more sense here.
Comment: @MSalters: Issue is that OP returns lambda: so `(s1+s1)+(s1+s1)` no longer use custom types.
Comment: BTW, Eigen already uses template expression.
Comment: @Jarod42 `requires(requires (lhs() + rhs()))` seems to be c++20. The code I am working on is in c++17. Is there an equivalent c++17 way?
Comment: You might do that with SFINAE... but I strongly suggest to use your own type instead of relying on lambda.
Answer: It looks like the first overload is selected, but not for s1 + s2. That selects the 4th overload. However, inside that 4th overload you have s0.v + s1.v;, and .v is not an S<N, M>
Comment: @janou195: You are correctly noticing that the first overload is selected in the code above, because removing it makes a difference. You are incorrectly assuming that is it selected for the line `s0 = s1 + s2;`. That line instead instantiates the 4th overload. In turn, the instantiation contains `s0.v + s1.v;`, which _again_ requires overload resolution of `operator+`. And **now** it matters whether you commented out the first overload.
Comment: I don't understand your answer. What do you mean by 'the first overload is selected, but not for s1 + s2'? Also I am not sure to understand what you mean in your 2nd sentence...
Comment: Thanks, I got your point! My interpretation was wrong. But now my problem is that: why my operator is selected instead of the Eigen ones at the spot `s0.v + s1.v`? I wil edit my question in this sense!


Avoid the yellow message at the top of the gnome-terminal window that states "The child process exited normally with status 0."

Question: I have a gnome-terminal profile created with "When the command exists: Hold the terminal open" set. How can I avoid the yellow message at the top of the gnome-terminal window that states "The child process exited normally with status 0."?
Below are the contents of the desktop entry I have pinned to the Unity launcher. File name: twitterText.desktop
[Desktop Entry]
Type=Application
Terminal=false
Icon=vinagre
Name=Text Twitter Timeline
Exec=/usr/bin/gnome-terminal --window-with-profile=Microblog --hide-menubar --command="/usr/bin/python /home/htplainf/twitterTimeline.py"

Answer: Basically, don't let the program you are running terminate!
That yellow line indicates that the command you called within gnome-terminal finished sucessfully. You can even hit "relaunch" to start the program (in this case, your command line twitter) again.
I would do the following: Since you are most likely interested in a continuous update of the twitter messages, run your program within the watch command. This way, you can even define the interval "twitterTimeline.py" is run again!
Change your twitterText.desktop into the following:
[Desktop Entry]
Type=Application
Terminal=false
Icon=vinagre
Name=Text Twitter Timeline
Exec=/usr/bin/gnome-terminal --window-with-profile=Microblog --hide-menubar --command="watch -t -n 60 '/usr/bin/python /home/htplainf/twitterTimeline.py'"

Have a look at the Exec command in the last line:
watch -t -n 60 '/usr/bin/python /home/htplainf/twitterTimeline.py'

-n 60 means that your python script is executed every 60 seconds. You can easily set a different interval. Also, have a look at man watch to discover its compete functionality!
By using watch, your command never stops, so you will not see the yellow message bar on top of gnome-terminal. And your tweets are updated!
Comment: Thanks for the idea. I added `raw_input()` to the end of my Python script and removed "Hold the terminal open" from the gnome-terminal profile. This works perfect for my use case. I don't want to refresh the content as I have a twitter feed displayed by conky. I only open this terminal twitter feed when I've spotted something interesting with a link. I can click on the link from here. When I'm done, I press Enter and the terminal goes away. Perfect!
Comment: I agree :-) That also prevents the process from stopping and closes the terminal. Nice!
Answer: Your terminal setting may have,

Edit > Profile Preferences > Title and Command > When command exits:
  Hold the terminal open

set,

When command exits:Exit the terminal


Show that $p+q^{2}=1$ where $x^{3}+px+q=0$ and one of the roots is the reciprocal of the other?

Question: let the three roots be $z, 1/z, t$.
So $z+1/z+t=0$ and $zt+1+t/z=p$ and $z(1/z)t=-q=t$
$-1/z-z=t$
$p+q^{2}=zt+1+t/z + t^{2}$
How do I simplify the RHS to get 1?
Answer: $-1/z-z=t \Rightarrow t/z + tz = -t^2$.
$p+q^{2}=zt+1+t/z + t^{2} = 1 - t^2 + t^2 = 1$.
Answer: $zt+t/z =t(z+1/z) = - t^2{}{}{}$.


Run multiple SSIS projects on the same server in parallel

Question: I have about 7 projects deployed on a SQL Server. Each one contains a MasterPackage which run all the child packages of that project. The issue is that I want all 7 projects to run in parallel, starting at the same time, but as it is right now, they get queued up and start one after another. Can I make all the projects start at the same time?
Answer: You can always schedule packages' executions by the means of SQL Server Agent jobs. You will probably have to create a separate job for each project, but after that, whatever schedule you pick for them should be followed.
Just keep in mind that, if packages push a lot of data through, server might not cope with the total workload, so parallel execution might be slower than a serialised one.


msmtp cannot write to /var/log/msmtp/msmtp.log

Question: In /etc/msmtprc I added credentials for a gmail account and also specified a log file to use in /var/log/msmtp/msmtp.log
I also created the folder and file in /var/log/msmtp/msmtp.log
When I test it using: echo "This is a test e-mail from my server using msmtp!" | msmtp ******@gmail.com
I receive an email but in the terminal I also see an error message like so: msmtp: cannot log to /var/log/msmtp/msmtp.log: cannot open: Permission denied
The current permissions for /var/log/msmtp are:
drwxr-xr-x  2 root      root        4096 Jan 29 20:19 msmtp

What am I doing wrong? What do the permissions on the log file need to be for msmtp to be able to write to the file?
Comment: Is it similar to this question?  http://unix.stackexchange.com/questions/146466/as-what-user-does-a-command-end-up-executing
Answer: I had the same error message, and ultimately changing permissions, creating the log file, etc., didn't work. The problem in my case was caused by AppArmor: in my system, the file /etc/apparmor.d/usr.bin.msmtp only listed /var/log/msmtp as write permission in /var/log, so solution can be:

to use /var/log/msmtp as log in the configuration, instead of /var/log/msmtp.log
modify the rules in the msmtp apparmor profile to allow adding and locking the file we want.
Comment: Had the same problem.  Finally had to set the log to ~/.msmtp.log.  Could not understand why AppArmor was not letting me use /var/log/msmtp or /var/log/msmtp/msmtop.log
Comment: Thanks! That was the case for me as well after upgrading from Debian 9 to Debian 10, where an apparmor config for msmtp was added.
Answer: After installing msmtp there is an msmtp user and group. If you change the ownership of the logfile to msmtp, and change rights to read/write for user and group, the logging works.
groups msmtp
sudo touch /var/log/msmtp
sudo chown msmtp:msmtp /var/log/msmtp
sudo chmod 660 /var/log/msmtp

I haven't tested it, but I suppose this works for /var/log/msmtp/msmtp.log as well, if you set the rights for the folder properly.
Comment: Very helpful and hard to find information. It seems to me that almost nobody knows this simple solution. Thank you.
Answer: I prefer to have my email logs in /var/log/mail.log because that's the default in /etc/rsyslog.d/50-default.conf and I wanted to avoid modifying apparmor config if possible, so I removed logfile and added this to /etc/msmtprc:
# The logs will appear in /var/log/mail.log because of the rules in /etc/rsyslog.d/50-default.conf
syslog LOG_MAIL

Answer: On a laptop running Debian stable, I also had the permission denied error. I set the log to be ~/var/msmtp.log. It was caused by apparmor as well. To correct it, I found the log lines in /etc/apparmor.d/usr.bin.msmtp:
  owner @{HOME}/.msmtp*.log wk,
  /var/log/msmtp            wk,

I copied the first line above to the usr.bin.msmtp in /etc/apparmor.d/local and edited it to point to my log location:
  owner @{HOME}/var/msmtp*.log wk,

I rebooted because I didn't take the time to figure out how to get apparmor to read the updated files. Now it logs properly.
Answer: I tried with 0640 but it did not work, it workd only with 0770
(I chowned with user msmtp + 0640, but it did not work either)
# mkdir /var/log/msmtp
# chmod -R 0770 /var/log/msmtp
# [nano|vim] /etc/apparmor.d/usr.bin.msmtp
  owner /var/log/msmtp/msmtp.log wk,

# service apparmor restart
$ echo 'message test mail backup' | msmtp the.email

Answer: Running on Debian Bullseye,
I have tried to pull together various solutions posted here and elsewhere which in themselves are
both good practice and any one of which may solve the problem in some circumstances.
I am hoping that with the addition of my discovery every instance of error should be covered.
First:
Add users to "mail" group
sudo adduser nobody mail

Second:
Set log & configuration file path and permissions.
sudo touch /var/log/msmtp
sudo chown -R root:mail /var/log/msmtp
sudo chmod -R 660 /var/log/msmtp
sudo chown root:msmtp /etc/msmtprc
sudo chmod 640 /etc/msmtprc

Finally:
When I looked at my configuration file /etc/msmtprc I found that I had specified the log file path
incorrectly:
#SET PATH TO LOG FILE
logfile /var/log/msmtp.log

Once this was corrected to....
#SET PATH TO LOG FILE
logfile /var/log/msmtp

and tested
echo 'message test mail backup' | msmtp the.email

The error message was finally gone.
Sadly msmtp was sending emails to tell me about a degraded RAID array.