How to draw functions in C++

Question: I would like to create charts of functions in C++. Can anyone help me in getting started ?
Let's suppose I want to draw the function y=x ( it is a straight line passing through the points (0,0) (1,1) (2,2) ..... (20,20) etc. )
How could I do it ? ( If you also suggest how to draw the y & x axes it is even better )
Sorry but it is not on books ( good texts recommendations are welcome, by the way :-) C++ ) and on the net there are references mainly to game graphics.
The only serious reference to my problem I was able to find is this:
somewhat related question asked in this very forum  ( God bless, we have stackoverflow ! )
Comment: If you want draw graphics in you program,you must create a GUI program.And the C++ standard library don't provide any function to draw graphic.But you can use functions provided by you operation system to draw.
Comment: just wanted to add that you don't *have* to have a GUI to create graphical output - no reason why a command line app can't generate graphical output with libgd or similar.
Answer: I would consider two options:

If you want to do everything in C++, you will probably need an external library. OpenGL is a solution, there is also Qt, which is probably easier to learn and larger (and more powerful).
If you can afford to output a file and read it with another program, the easiest way is to simply write an ASCII file with the coordinates of the points and plot is with Octave (free).
Comment: nit pick: QT GUIs require the use of MOC which renders your code into something other than C++.
Comment: @KitsuneYMG True, but it's not a problem in practice.
Answer: You could also use Gnuplot, an interactive plotting program: your C++ code handles and computes your data, and then it can export the result to a file or the standard output that can be processed by Gnuplot. For instance, you can do something like this:

my_program | gnuplot

which will call Gnuplot with the result of your program.
Gnuplot is very powerful, you can check the examples available here.

(source: sourceforge.net)
You can find additional information on Gnuplot in C/C++ here:
How to plot graphs in Gnuplot in Real time in C++?
UPDATE
Another possibility is to use R. This language is very famous among statisticians. You may want to look at some examples.

Related question: How to run plot of R into C/C++?
Comment: Thanks for the tip. I wanted to follw the examples in the book but this looks like a wondeful solution for the future.
Comment: @ BenC    Yes, along with ROOT, it is the best choice, so I decided to begin to explore both and to use which is the best for every task I need. How can I begin ? How can install it ? Any easy tutorials ?
Comment: You can check [**this tutorial**](http://physicspmb.ukzn.ac.za/index.php/Gnuplot_tutorial). After that, it really depends on what you are trying to plot. Install is straightforward. If you're using Windows, [**this**](http://www.maths.manchester.ac.uk/~pjohnson/Gnuplot/windows_gnuplot.html) might help you (I only used it on Linux).
Comment: @ BenC    Ben, do not misunderstand me, but I would kiss you !  :-)
Answer: i dont know of a effective fast and simple method to do what you describe in c++.
you will either be outputting text to a console to show the effect of the "lines" you wish to display. or setup a proper GUI interface with either directx or opengl.
Many librarys do exsist which simplify the task of setting up a GUI. but there is initial overhead.
i would suggest making a c# form application and looking into drawing lines within that. it would also easily allow you to put equations in at run time rather then hard coding them.
Comment: An alternative to ASCII art would be to simply output image files (e.g. BMP, PCX, GIF and so on).
Comment: that is true but you would still need to setup some sort of GUI to render the image. while ascii art can be achieved in a console.
Comment: A web browser should be enough for viewing common image formats.
Answer: I use ROOT.  It's what most particle physicists use, particularly at CERN and Fermilab.  It's free.  They have versions for Linux, Mac, and Windows.
http://root.cern.ch/drupal/
It's easy to make plots, histograms and produce output suitable for publication.
Edit: It's built on C++ but has python bindings as well.
Edit: If root is install on linux to compile code using ROOT with GCC do e.g:
g++ foo.C -o foo `root-config --cflags --libs` -O3

Comment: @ raxman wow ! I have a scientific background, I love these things ! thanks for the info !!
Comment: @ raxman  it's really great !!! Unfortunately I am not a very advanced programmer. Can you tell me ( or provide a page ) how I can begin to use it ? Installation, etc...
Comment: Try googling "ROOT cern tutorials".  You could start with this one
http://root.cern.ch/root/html/tutorials/hist/hsum.C.html
Installation should be easy. I never used ROOT on windows though except with Cygwin.
Answer: I had this same question about three months ago. The best way I found to plot for my application was utilizing the Qt framework (because it already creates a GUI for you, and then leveraging this tool:
Qt plotting widget
This widget, when compiled and linked with your project, allow you to plot 2d graphs directly from your interface. This saves you the trouble of writing to a file, loading with matlab, etc.
Currently, it only handles 2 d plots, but it wouldn't be difficult to extend it to three dimensions or maybe a surface plot.
Best of luck!
Answer: In these days I discovered a couple of things:
1. the book "introduction to C++ programming and graphics"  C.Pozrikidis
2. Visual Studio C++ 2010 express and OpenGL
   ( see the last comment in that page )
Can anyone suggest better solutions ? ( textbooks, free dlls etc. )
Comment: I'd suggest using Qt (in particular, subclassing a QWidget and reimplementing the paintEvent(QPaintEvent*) method.  The QPainter class has all the drawing commands you'd want to use, e.g. drawLine())  The advantage of Qt is that it's easier to use than most graphics APIs, and once you've written your program it can be compiled and run on almost any operating system.  Qt is available for free under LGPL.
Comment: by the way, in the above mentioned book the author uses the freeglut library. I visited their site, could anyone teach me how to install it ? Actually there is a page devoted to it but I did not understand anything. Here is their site: http://freeglut.sourceforge.net/
Comment: Found !  http://lazyfoo.net/tutorials/OpenGL/01_hello_opengl/windows/msvsnet2010u/index.php
Comment: VOGLE library ( a simpler graphic library used in the book; Unix ): http://home.comcast.net/~urbanjost/CLONE/LIBS/LIBRARY/libvogle/html/index.html
Comment: @JeremyFriesner. Thank you a lot. If freeglut does not work as expected, I will give Qt a try. For the time being I prefer to follow the examples in the book.
Answer: You can use some functions that are there in Windows.h. Start with the console functions. They are a good place to start and enable us to work on the console as if it were a Cartesian plane.
Though I have never tried to draw something with them. I have been able to create nice tables and layouts for text presentation. Like the name and telephone number of a contact as a table in a contacts application.
The functions enable moving the cursor to specific coordinates. And write something there. And overall they quite work like a Cartesian plane. But only the coordinate system is not the normal one which we use(4 quadrants) it is more of a computer type system with only one quadrant and labelled from left o right on the x axis and from up to down on the y axis. You may have to build some functions so as to optimise this or the normal system that we use.
But all in all, it is useful and you can try it.
Answer: I installed gnuplot ( very easy: create a folder in the hard disk, unzip and send a link to the destop from wgnuplot.exe ) and now I export the data to be plotted from Visual Studio ( C++ ) in .txt files and then I call those files from the gnuplot window. Just to save to others the same waste of time and headache I experienced :-)
I have also installed ROOT, very easy, there is a regular Microsoft installer in the cern page. Here is the link:
http://root.cern.ch/drupal/content/production-version-534
and scroll to the bottom of the page then select the MSI version compatible with your Visual Studio. I must still learn how to use ROOT from Visual Studio, anyway. Help would be appreciated.
There is also this page helping a lot with the creation of projects in Visual Studio using ROOT: http://root.cern.ch/phpBB3/viewtopic.php?f=3&t=11641
All of the above is for WINDOWS users.
Answer: i was just plotting a simmilar function y=x²
in windows, or any library based on windows you will probably intercept message WM_PAINT

     case WM_PAINT:
     HDC hdc = beginpaint();

// change device contexts      hdc y      axys orientation
// change logical coordinates of point (0,0) to half of width and half of //eight of your client area

// u might want to change from pixels to mm
// for each x from -10 to 10 y = x²
// draw a little line for each point in this range

// end painting, this will release     hcd

Comment: Please explain your answer

How to draw functions in C++


grails render tag: can't find file unless it's located in src/templates/scaffolding?

Question: I tried to follow the example under "Shared Templates" here:
http://grails.org/doc/latest/guide/6.%20The%20Web%20Layer.html#6.2.3%20Views%20and%20Templates
But this just plain didn't work.  The tag I used was:
<g:render template="/includes/mySearch"></g:render>

I created a directory under the views called "includes" and created a gsp file, with a very basic form in it, named mySearch.gsp.
However, grails reported being unable to find the file:
 java.io.FileNotFoundException: C:\springsource\sts-2.8.1.RELEASE\grails-1.3.7\src\grails\templates\scaffolding_mySearch.gsp
According to the documentation: "In this case you can place them in the root views directory at grails-app/views or any subdirectory below that location and then with the template attribute use a / before the template name to indicate the relative template path."
It would appear that this is exactly what I did, but grails was not looking there?  Any advice?
Many thanks,
Alexx
Comment: my question was more to the effect of, why is the framework looking in \scaffolding, and not \includes?
Answer: Template files need to be starting with an underscore. Therefore you need to rename your mySearch.gsp to _mySearch.gsp.


Was Anakin really the only human who could race pods?

Question: I was wondering if Anakin Skywalker really is the only human who can race pods.. I find it hard to believe considering the sheer number of populated worlds. Is there any mention of any other human, Force-Sensitive or not, who can race pods? I would be okay with a Legends answer..
Comment: In the Star Wars Knights of The Old Republic videogame there are many humans who race pods...
Comment: To add a guess. Podracing is going to take an insane reaction speed to stay alive. Many other species, likely have the advantage of heightened reflexes. Think about the reaction time of real world small insects. Anakin's got the force subtly helping him - and It's unlikely other force sensitive users would enter into pod racing (via raw probability)
Answer: According to the novelisation of Revenge of the Sith he wasn't the only human to ever start a race, but he was certainly the only human to successfully complete one. Note that over two-thirds of the racers in Anakin's race crashed and several died.

A few wings of droid fighters didn't much scare a man who'd been a
  Podracer since he was six, and had won the Boonta Cup at nine. Who
  was, in fact, the only human to ever finish a Podrace, let alone win
  one.

Notably, this section of the book is told from the perspective of the omniscient narrator rather than Anakin's own limited view.
Comment: @Thunderforge - ..or you could say that he was *of the opinion* that he was the only human who could successfully do it, and then proceeded to show that assessment correct.
Comment: This would mean that Anakin was exaggerating then when he said in Phantom Menace that he was the only human who could podrace. He hadn't finished a race yet, so he was just one of a number of humans who could start one.
Comment: Or, like so many six year olds, he thought he could do anything.  Or perhaps it was some sort of force enlightenment.
Comment: He was correct in that he was the only human who could podrace, from a certain point of view...


Validation with exceptions vs IDataErrorInfo and the new INotifyDataErrorInfo

Question: I'm trying out different ways of validating and I'm having a problem with the new INotifyDataErrorInfo-interface.
When writing in for instance a bound textbox that only accepts 10 chars. I write 11 chars and tab out. The validation kicks in and marks the textbox red etc. Now, I don't want to write this invalid value down to the source of this binding, but if I'm not doing this I immediately get the value in the textbox reset to the last valid value. It's as if the binding does an UpdateTarget on it's binding even though there was an error.
By using ValidatesOnExceptions and throwing exception in the setter I get the behaviour I'm after. The binding is not updating it's value from the source if an exceptions has been thrown in the setter. This leaves the invalid value in the textbox so that I can work with it to make it valid. I think this is far better than having to store the invalid value in the underlying object.
The question is why IDataErrorInfo and the new INotifyDataErrorInfo behaves in this way that it updates target from source even though there were errors? Can I make it to behave more like ValidatesOnExceptions?
I need INotifyDataErrorInfo because of other features such as async validation...
Answer: If you need to validate a value before it has been committed to the source, then you will need to create a custom validation rule and set the ValidationStep to RawProposedValue or ConvertedProposedValue.
See the documentation on the Validation Process and ValidationStep for more info.


Tool to list users who accessed a particular file and when

Question: In windows I can look at the Last Access time of a file and it will show me when the file has been touched last time. Is there any tool which could give me the list of the users who accessed a particular file and when did they did that. Basically I have a file on a network drive and I would like to have some kind of basic audit reporting tool.
Answer: You don't need a separate tool, Windows is already capable of doing that (works very similar for other versions of Windows):

How to audit user access of files, folders, and printers in Windows XP


problem on expand network using a router

Question: I have a Netgear FS605 v3 router, and i'm trying to expand my network. The router is connected to the cable modem with cat5 cable. I have 2 laptop connected to the router but i'm only able to get internet connectivity in one. The first laptop i turn on, get the signal and the other one will show no connectivity. I have restarted all the devices many times but no luck. Can somebody explain me how to get this solved. Thanks.
Answer: Your problem is the Netgear FS605 is a switch not a router.  Your ISP probably only provides you with 1 IP address, and the first computer to connect to the network will get it.  You will need an actual router if you want to connect more than one computer without buying additional IP addresses from your ISP.
Here are a couple of questions that might help you in choosing a router:

Basic (cheap) wireless router recommendation for home
Good reliable cheap router for dorm room?
Comment: yep... right tool for the right job....  this being said... now that you already have a switch you do not need to worry about how many ports the router has.  you can connect toe router to the modem and the switch to the router to have more ports available and all will work great.  This said, for two laptops just about any router will do just fine without the need for your netgear switch.


Rigging a tank turret and gun

Question: I decided to make the Panzer VIII "Maus" tank in Blender as a way to experiment with techniques and such on the go, but i had also made another tank before the Maus and since then, i have still not been able to figure out how i can make the tank's turret and gun to be rigged properly.
What i want is for the turret to be able to be rotatable on the Z axys (left and right), but the gun to follow the turret's rotation, WHILE the gun itself can rotate on the Y axys (up and down). Before, n my previous tank, i was able to make the Turret rotatable, but the gun was either left floating in the air, or not being able to rotate, WHILE remaining attached to the Turret.
Here's a pic for a better understanding:

Feel free to point out any mistakes with bone placement, that would also help me as i'm not yet familiar with rigging.
I hope my explanation wasn't confusing or anything.
Thanks in advance for any help!
Answer: Each bone has a head and a tail. The head is the centre point of any rotation, so you position the head at the centre point of the pieces rotation, for the turret that is the centre of its connection to the base and for the gun it is the end that is connected to the turret. Position each bone so that its movements make sense for the piece of the tank that it will control.
Now parent each bone to the piece that it is connected to, the turret is the parent of the gun and the base is the parent of the turret. When parenting bones you can choose between connected and keeping offset, choosing connected will move the head to the tail of the parent but keep offset will parent the bone without moving it, this allows the bone to follow the parent and keep its position for its rotations.
To make animating easier you can add some constraints.
For the turret and gun, under transform locks in the bone properties, enable the location locks, this prevents you manually moving the bones in pose mode.

For the turret add a Limit Rotation constraint and enable Limit X and Limit Y and change World space to Local Space, now it can only be rotated on its Z axis. Any time you press G or R it will only rotate the one direction you want it to rotate.

For the gun also add a Limit Rotation constraint. Enable all three limits and change to local space. Now set a min and max value for the X axis, in my quick example I found a max of 32 and a min of -4.2 looks about right, allowing you to rotate the gun up and down without hitting the tank body and not point straight up in the air.

Here is my simple example rig.
Comment: I'm still confused as to how exactly to do it, i couldn't understand if i need to put the bones in as different armatures, or if i need to parent the mesh itself and then do something with the bones or something else. I'm sorry, i just find this rigging thing to be really confusing and hard for me.
Comment: Well, i added each bone as an individual armature, parented the bones to their corresponding parts and they all interact like they're supposed to. If i move the hull bone, the Hull, Turret and Gun moves, if i rotate the Turret, the Gun follows and the Gun rotates at the bone's base. This should be fine for animating and shouldn't cause any problems, right ?
Comment: @Ivan you only need one armature object, that one armature can have as many bones in it as you need but if what you have works for you then go ahead. Like separate objects, each bone can be [parented to another bone](https://docs.blender.org/manual/en/dev/rigging/armatures/bones/editing/parenting.html) so that it follows it around. For example in a character, the upper arm is the parent of the lower arm so that the lower arm always moves with the upper arm. Same with your tank, the turret is a child of the hull and follows it, it just doesn't have to be directly connected to the parent.
Comment: Yeah, now that i took a closer look at the hierarchy, everything became "Hull-bone" which branches off into the the different mesh objects and armature, so i got what i was supposed to. And i'm SURE that i understood rigging and parenting this time :)
Comment: How do you do this in blender 2.8. transform constraints no longer exist
Comment: @tatsu they still exist, the link was broken from changes to the manual, not that it was removed. The link is updated now.

Rigging a tank turret and gun


Debug through libstdc++

Question: I'm using gcc on GNU/Linux and the debug-files and headers of libc and libstd++ are installed. But I don't know how to tell gdb to use the source-code of them, especially to debug into libstd++.
The source-code of libstdc++ itself seems to be provided in a complicated structure. I think the directory command is the right choice. I'm using here Debian/Ubuntu and downloaded the source with apt-get source libstdc++6 into my home-directory.
I'm pretty sure I didn't need take special steps for this with Fedora (some years ago). Maybe Fedora was prepared in a special way for this. So I will be glad about general instructions, which fit for every distribution.
Thank you
Update
I figured out, that I need to compile with -D_GLIBCXX_DEBUG in addition to -g, so compile command looks like $ g++ -o test test.cpp -g -D_GLIBCXX_DEBUG.
Furthermore I got warning about missing pretty printers, which I solved as described here:
http://gcc.gnu.org/onlinedocs/libstdc++/manual/debug.html#debug.gdb
Now I can debug into libstdc++, but I always got this message:
Breakpoint 1, main () at test.cpp:9
9       string str = "str";
(gdb) s
std::allocator<char>::allocator (this=0x7fffffffe1e0)
    at /build/buildd/gcc-4.7-4.7.2/build/x86_64-linux-gnu/libstdc++-v3/include/bits/allocator.h:104
104 /build/buildd/gcc-4.7-4.7.2/build/x86_64-linux-gnu/libstdc++-v3/include/bits/allocator.h: No such file or directory.
(gdb) s
std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string (
    this=0x7fffffffe1c0, __s=0x402930 "str", __a=...)
    at /usr/include/c++/4.7/bits/basic_string.tcc:217
217                    __s + npos, __a), __a)

I don't need to set the directory in gdb to the my downloaded source (I' think it search through my home-directory). So I thought I need a different command to fix this and found "set substitute-path" and pointed it to /home/username/gcc-4.7-4.7.2/gcc-4.7.2/libstdc++-v3 but I doesn't work. Why does gdb look for allocator.h in the completely wrong place?
Comment: What is your exact `set substitute-path` command?
Answer: First find out the sources from :-
https://gcc.gnu.org/onlinedocs/libstdc++/latest-doxygen/index.html
Later compile libstdc++ with DEBUG_FLAGS set it ON.
Then, try it out to debug with gdb.

Debug through libstdc++


if all income is spent on consumption how will it change or affect the economy

Question: Imagine all incomes being spent on consumption would such a system be in a position of no change.
Answer: No, at least not if you mean "final consumption", that is spent on goods and services solely for our own enjoyment.
We produce goods and services with capital and labour (and natural resources and technology and human capital, but for simplicity let's put those under capital as well). The thing is that capital detoriates over time. My computer at my work place will have to be replaced at some point. The plough of the farmer will break down eventually. The natural gas that I use to heat my house will run out eventually, although potentially not during my life time.
To make up for these losses we need to invest some money in replacing the lost capital and finding replacements for non-natural resources. That is we need to invest money. If we'd only spend all our money on final consumption goods eventually we'd run out of capital and wouldn't be able to produce all those goods.


iOS 7 update failed - stuck on Connect to iTunes

Question: I was downloading iOS 7 to my iPhone 4 and the update was going for almost 1 day. I left it overnight and when I was about to use my phone it is stuck on the 'Connect to iTunes' screen (iTunes logo with a USB cord). My phone is still stuck on that and when I try to fix it with iTunes with my PC (Windows 7) the message always pops up saying that my phone needs to restore. Can you help me with this?
Comment: Did you start the update from a download to iTunes or an over the air update? That might help, better step in troubleshooting, can you use iTunes to initiate a restore now that it is stuck?
Answer: When your phone gets stuck trying to update, it usually means it has way too much data in it. For a good average update that's takes at least 20 mins, you'll need to have at least 2.5 GB. Your phone has gotten stuck because it had way too much stuff in it, and it can't continue.
My solution: restore the phone. There is way too much data inside,and it will stay that way unless something happens. This can be a good and bad thing. If you had some stuff on iCloud or some storage, you just might restore your apps and everything else. But if you don't, let's just hope you had nothing important in the phone, because it might just go down the drain. Besides you are left with no other option, right?
I hope this helps. If you find a better way, please use that way instead of this way. I hope you are able to fix your phone.
Answer: The best way to solve this is to actually restore your iPhone.


Can't remove icon from gnome panel by Alt+right click or Windows+Alt+right click?

Question: I have read some questions about how to remove icon from gnome panel, I try to hold Alt and right click or Windows+Alt and right click but not menu display!
I use Ubuntu 12.0
Comment: well, after some weeks, I finally solved this problem. There two ways: 1. You can login with Gnome (no effects) and you can use Alt+right click or Alt+windows+right click; 2. You can using command: gconftool –recursive-unset /apps/panel
=> rm -rf ~/.gconf/apps/panel

=> pkill gnome-panel
Or you can use other commands that similarly! good luck :)
Answer: Hold down ALTSUPER then right click on the icon you want to remove.
In the context menu that follows from your click, you will see 2 options, 'move' or 'remove from panel'; and these are your options.


Where are the swap files stored?

Question: The swap files used to be stored at /var/vm but when I look there on Catalina, the only thing I find is a sleepimage of approximately 1 GB. Where is the swap stored? Want to know how much of the disk it consumes.
Answer: See this thread: https://discussions.apple.com/thread/252816786

They likely changed that with Big Sur. I think it was mounted to /private/var/vm/ in Catalina. Mounting it to /System/Volumes parallels the rest of the volumes in Big Sur.

The swapfile (swapfile0) appears to be at /System/Volumes/VM now
Comment: /private/var/vm was always the directory /var is a link to /private/var since NeXT

Where are the swap files stored?


What to put on job application after being fired?

Question: I was terminated  from my security  job because I let an unauthorized  person into the building; but I didn't know he was not supposed  to  be  in the  building. He came into the building with proper ID but his access on his card was disabled.  Because  of this reason the company let me go. My question  is if I go apply  for another security  job what do I put on the application for reason for leaving?
Comment: Did you follow the correct procedures for checking access?
Comment: There's always a tactful way of sayings things. Never lie, and accept things might be a bit rocky in your field if you stay.
Comment: Just write "dismissed"
Answer: I would not say "dismisssed" or anything negative -- the new company will likely imagine the worst, and may not even call you back.
Say something simple, general, and neutral. You're probably feeling bad/guilty right now and in a confessing mood, but that will work against you. I've been fired twice, and got new jobs by explaining it simply, and not dwelling on the past -- most companies are far more interested in your experience and what you can do for them, as opposed to what happened with your previous employer.
People make mistakes. Do not say anything about it unless asked, and if asked, explain it as you do here, indicating that you have learned from your mistake and will be extra careful in the future. Do not blame your old company -- on the contrary, say you understand completely their actions.
Use your mistake to your advantage as much as possible. Convince your new company that you never want to make a mistake like that again.
Answer: Dismissed for breaching security is about the worst thing next to stealing in that industry. Best not to mention it at all. Expect to be asked why you left your last position and have that impact badly on your application. There is no sense lying about it, it's too easy to find out unless you leave the locale.
Personally I would change industries. Security skills can be used elsewhere (I'm assuming you're licensed and trained). Also security jobs encompass a huge range of activities, you might want to look into a change that way.
Comment: Unless your in politics, then you just claim some -ism. :)


Is there any reason an odd resolution for images/videos would not work as well as an even resolution?

Question: It seems fairly random, but I wanted to cover my bases, has anyone heard this before?
Answer: Most  analog video formats are interlaced : odd lines and even lines are drawn alternatively. So you have an odd number of lines.
But more than that, having image sizes factorizing as powers of 2 3 and 5 allow to have an easy scaling with integer factors. You can check the usual resolutions of cameras : they have a lot of 2s and 3s.
And generally compression algorithms like to work by splitting the image in blocks : JPEG uses 8x8 blocks. Processing video of arbitrary resolution requires some extra coding to handle the incomplete blocks on the image border, so one can say it does not work as well.
Answer: Not generally. There are reasons to prefer certain resolutions but that has nothing to do with the even or odd number of pixels. Do you have a reference for this?
Answer: Packing?
On modern processors, stuff can be retrieved most efficiently in even-number-of-bits groups.
Likewise many compression algorithms want to work on groups of pixels that are 2^n high and/or wide, and edge cases may be less efficient.
Probably not a big deal in either case.


Is there a way to automatically change resolution when pluging in a monitor?

Question: I bought a Cable Matters SuperSpeed USB 3.0/2.0 to HDMI/DVI Adapter  up to 2048x1152/1920x1200 and used it to connect a Lenovo Yoga Pro 2 which allows a  fairly high resolution into an old acer monitor. At first I thought it was broken but then I realized it only worked at a lower resolution. I'm trying to set this up for my mom who isn't much of a technical user. Is there a way to get it to automatically change resolutions when plugged/unplugged?
Comment: Going through a convertor may interfere with the computer recognizing the monitor characteristics.  The fact that it required manual intervention pretty much says that you can't automate the setting.
Answer: The monitor may not be able to handle that high a resolution and goes out of synch. Do you hear any high-pitched whistling and clicking as it tries to synch up to the signal? That's usually a sign that the monitor doesn't work at that resolution, and why it can only display a much lower resolution.
You don't say the vintage of the display, but my hunch it probably can't go much more than 1024 x 768 which was high-resolution way back when except on expensive CAD/CAM and graphics systems which used special video cards and monitors capable of the resolutions we use every day now.


Event Receivers

Question: Where can we implementthe event receiver?
I am new to the SharePoint so please guide me! Thanks!
Answer: Event handlers are something "similar" to the triggers databases. If we imagine a list as a table, we can imagine that an event is a trigger.
Then you can create a business rule associated with the creation, modification or deletion of an item.
You can also create events associated with other actions such as creating a site. A good way to generalize is to associate with content types, rather than list.
They are created with Visual Studio C #.

Event Receivers


Book about space traders who run into alien traders

Question: From what I can remember, a down and out family of space traders, in which one female member of the family is a psychic or a witch, run into an alien ship, also running out of options.  Possibly the alien ship was alive, could be mistaken about that part.
Comment: Maybe Julie E Cznerneda? Try the Vattas War series too, that may be something you would like.
Answer: Angel Station by Walter Jon Williams (1989)
Ubu has four arms, a fantastically faithful memory and is 13 years old. His 11-year-old sister Maria is more conventionally constructed, yet so psychic she considers herself a witch. (Both mature with the artificial aid of "mones" to the time of their late teens.) Their father, Pasco, a small-time trader with an ancient spaceship, originally assembled them from spare genetic material and personality programs, but he commits suicide while in the throes of a depression, leaving his children to fend for themselves. Ubu compounds their problems by making an unwise business move, putting them deeply in debt--in danger of losing the ship and facing a life of virtual indenture. An attempt to capitalize on Maria's psychic abilities in a casino ends in disaster, leading to their arrest, escape and lives pursued on the edge of the law.
Comment: Yes!  Thank you so much Dai.  I have 3 other books by WJW on my bookshelf but didn't realize I was missing that one.  I must have lent it to someone and never got it back.


Computer only recognize 4Gb out of 8Gb

Question: I replaced the two cards of memory, of 2Gb each, with two cards of 4Gb each (Samsung M395T5160QZ4 - CF7  1412).
(I have ubuntu so it should be able to use memory above 4Gb.)
My motherboard is GA-MA78LM-S2H.
When the computer loads the BIOS says I only have ~4Gb. (I expected 8Gb)
Is there something I can do (maybe in the bios) to enable all the memory?
Comment: OS won't affect BIOS
Comment: do u have ram from another system to test with
Comment: and try with one stick then the other stick, as maybe you have one faulty stick
Comment: I did, they both worked separately.
Comment: Did you solve it? And if so, what solved it?
Comment: @barlop, I think now that the problem is that the memory is not one of the supported ones for the motherboard.
Comment: you still won't know whether that was it, unless you get that RAM and try it
Answer: I imagine you are talking about Windows not seeing 8GB, not the BIOS. If it is the BIOS, skip a bit further on.
When you are running a 32 bit operating system (in normal mode with a normal kernel), it can only access a 32-bit address register, which are a total of 232 addresses or guess what 4 GiB of RAM.
With 64 bit, on a technical scale,  you can access about 16 EiBs (18.1 exabytes) of RAM. Do note that practically this is impossible and also chipset/operating system limits are MUCH lower.
You need to download and reinstall a version of Ubuntu with a 64 bit kernel and 64 bit support.
If you do not see all your RAM in BIOS
It is also possible that in your BIOS, it is not enabled to access 64 bit memory. This was common on older motherboards with older BIOS. Update the BIOS just in case.
If after updating the BIOS, you do not see all 8GB of RAM

Check that you actually physically installed the RAM correctly
You might want to check your manual for a option for access all of your memory. Sadly there is no universal term. Microsoft calls it "memory remapping" or "memory extension".
After this, if you still do not see all of the RAM, is the RAM you installed specifically listed as being compatible in the manual with the motherboard? Sadly, some motherboards are REALLY picky and just do not want to play nice with say Crucial memory but do play nice with Kingston memory. Again, this is something from the older motherboards and less common nowadays.
Comment: +1 re flashing BIOS. I'm not sure that it'd do/fix it but it's a good idea worth doing just in case it does.
Comment: I posted the exact same thing before the answer that is selected as "Correct"  and mines isn't marked. Amazing...
Comment: we till have no idea what, if anything, solved it for him
Comment: see my note on the accepted answer, as to what the OP considers to have solved it
Comment: I suggested that if his RAM still does not work he should check the manual for comparability...
Comment: You're right.  At least your answer (as of writing) has one more votes than the accepted one.  It wasn't that obvious that you got there first, but looking in the revisions, you added it in an edit, and he added it in an edit, so you did indeed add it first
Answer: You shouldn't have to do anything in the BIOS etc—it should just work.
And your board does support up to 8GB of RAM.
Try removing and reseating the memory, to make sure it has connected properly.
If that doesn't help, and the memory is of the correct type, one of the 4GB modules you have installed may be defective. Try with one module at a time, to establish whether they both work.
Comment: They are right in principle, but your motherboard was [first available as recently as 2010](http://www.amazon.co.uk/Gigabyte-SKT-AM2-AM3-GA-MA78LM-S2H-Motherboard-x/dp/B002YOFNPW) so I'm guessing the BIOS isn't the issue. But a BIOS update is certainly a good idea if the other checks haven't helped.
Comment: I am confused, others in this thread claims that this could be BIOS related.
I tested each memory module by itself and each of them worked fine.
Answer: Operating System
You will need to be more specific on the type and make of the memory, the bit level of the OS and what is telling you there is only 4GB available. Is the OS showing 4GB or is it the BIOS? If the BIOS is showing 8GB, but the OS is showing 4GB, that's likely a 32 bit OS issue.
32 bit operating systems max out at 4GB regardless of how much you place into the motherboard. Though, some 32 bit Linux systems with the correct CPU setup and the correct kernel can expand the 4GB to 64GB with the PAE bit. To actually enable memory above 4GB on an operating system, you would need to upgrade the OS to a 64 bit version. Or, alternatively, find a Linux 32 bit version that supports PAE.
BIOS
If your BIOS is not showing 8GB, then you may have the wrong type of memory inserted, one of the sticks may be faulty or not fully inserted, interleave is set up incorrectly, the motherboard requires a specific jumper setting or the BIOS needs to be told about the new memory. Though, with most recent motherboards, any memory inserted should automatically be detected and recognized.
I would also review Gigabyte's supported memory list just to be sure your memory is supported for this motherboard model.
Since it has been determined that the BIOS is not seeing the 8GB, I'd look at the memory itself. I've reviewed the memory stick model M395T5160QZ4-CF7 and it is not in the list of supported ram sticks list by Gigabyte for this MB. In theory, it is PC2-6400 DDR2-800 ECC RAM and it seems like it should work. The Samsung memory stick that is listed is M378T5263AZ3-CF7. Though, there are also plenty of other brands to choose. Not all memory sticks are created equal. This is the reason MB manufacturers create lists of tested memory and publish them. If you can return this memory and replace it with memory in the supported memory list, you may be better off in the long run. I wouldn't trust using an unsupported memory stick in my computer even if it seems it should work.
Added by barlop
The aspect of this answer that the OP considers to have solved it, is the mention of the
Memory Support List here
http://download.gigabyte.eu/FileList/Memory/mb_memory_ga-ma78lm-s2h.pdf
Which does not include his model of RAM so to rectify that, he could get modules that are listed.
Comment: It is the BIOS that is telling me that I have 4GB.
Comment: Regarding the PAE, Actually, on Ubuntu, you don't need any special setup, the kernel (since ubuntu 12.04) supports PAE out of the box. So once you add memory it will just work.
Comment: I would recommend opening the computer up and inserting one stick in a slot at a time (assuming the motherboard supports this). Then, power on and test each stick separately. This way you can determine if both sticks are functioning.
Comment: As for PAE, Ubuntu doesn't always enable it depending on processor make. Certain Pentium and Celeron processors do not automatically enable PAE. Because your motherboard appears to based on AMD Athlon or Phenom, this shouldn't be an issue.

Computer only recognize 4Gb out of 8Gb


Does turkish coffee require different beans or roast or grind than espresso?

Question: After a while I settled on the beans that for filtered coffee, and I like espresso with them too, just ground more finely. So now I tried Turkish coffee with the same beans and the same grind as espresso, and, well, it doesn't seem to taste as well as I expected. Sort of more oily than espresso. What would be the prime thing to try change? Any special beans required for optimal taste?
Answer: I believe many people simply boil the grounds in their earlier attempts. This approach is known not to be a good practice.
Based on my experience, I could say the most notable changes that you could note in Turkish coffee is twofold: it should be fresh and quick.
Freshness is important as the grounds are as fine as flour. So, they stale very quickly. One of the reasons that people have traditional hand grinders is this. Ground just before you prepare.
Quick preparation is important to be able to extract more before the all the flavor has been evaporated. That's why you need a pretty good cezve with a decent stove to transfer heat as quickly as possible. It is said that whole preparation must take under two minutes.
OF course there are many details regarding any kind of coffee preparation. I believe these two could be the first things to change. Unfortunately, Turkish coffee preparation requires serious experience and the learning curve is steep. You could fine tune many parameters after gaining some more experience.
For similar discussion that may include a hint please see:

What gives Turkish coffee that unique "quality"?

Triple heating of the Turkish coffee
Answer: I assume your espresso blend is a dark roast. Try light roasts for Turkish. The extremely fine grind can lead to overextraction of dark roasts when using the Turkish method.
Additionally, double check your method. You haven't provided details of your method or grind size, so I can't comment on that. Still, using dark roasts could cause that oily taste you describe, so try switching to light roast first and foremost.
Answer: Definitely, you need to use a different grain of different roast for each type of cooking. After all, all this will affect his taste. Plus, you can always make coffee to your liking. For example, you like a thick and bitter espresso, while Chemex is more fruity and sour. Than one type of grain will definitely not suit you.


After upgrading to Ubuntu 13.04, KDE programs don't work any more

Question: After upgrading to Ubuntu 13.04 i cannot run any more KDE programs under Ubuntu.
I have both installed. Ubuntu and Kubuntu.
I run Rkonq and K3B already lots of years under Ubuntu.
But after the upgrade it is not possible any more.
This is what i get starting Rekonq from a terminal:
QDBusConnection: session D-Bus connection created before QCoreApplication. Application may misbehave.
QDBusConnection: session D-Bus connection created before QCoreApplication. Application may misbehave.
unnamed app(3756) kdemain: rekonq is already running!
Comment: I'm running Ubuntu 13.04. I just opened Synaptic Package Manager and installed the k3b packages(version 2.0.2-6ubuntu1). Results: k3b works.
Answer: I just got around to upgrading my work ubuntu machine, KDE environment would not run but it did complain about starting dbus.  CTRL+ALT+F1 (or any console).
sudo apt-get install qdbus

The update uninstalled the 386 version and installed a new version.  ALT+F7, login with KDE came up just fine after this.
Answer: I installed ubuntu-sdk as described here: http://ubuntuforums.org/showthread.php?t=2130894&p=12581777#post12581777
Comment: Welcome to Ask Ubuntu! Whilst this may theoretically answer the question, [it would be preferable](http://meta.stackexchange.com/q/8259) to include the essential parts of the answer here, and provide the link for reference.


Can the microsoft basic optical mouse be modified to contain spyware or a keylogger if the attacker had physical access to the mouse?

Question: I was given a mouse by someone who now i realized would want to hack me. It is the Microsoft basic optical mouse v2.0. Can this mouse be modified to inject spyware and malware onto my laptop?
Comment: Ever heard about the Rubber Ducky? Ninja cable? USB attacks are definitely possible.
Answer: The USB protocol allows to emulate mass storage which you then need to run from manually in order to get hacked, so it's unlikely you could have missed it.
But even without a built-in ROM this mouse could possibly send all your mouse actions via radio channels which is enough to infer a lot of information about you.
Another avenue is a vulnerable USB stack in your operating system but if you keep your software up to date it's highly unlikely you could have been hacked this way.
AFAIK USB4/Thunderbolt is a whole different affair as it can function as a PCI-E device with full DMA control over your system (meaning full read access to your RAM without your OS knowing anything about that) but USB4/Thunderbolt devices are still relatively rare and Intel claims modern operating systems have safeguards against this.
Comment: Would they be able to see what i type on the keyboard? I read on the internet and this website that macros can be overwritten to contain scripts or payloads. Would they have been able to do this to the mouse using their own device and then given to me to infect my device?
Comment: It depends on whether or not you've installed any software which the mouse pushed on you. If you only installed the edrivers from Windows Updates, it's very unlikely you've been hacked.
Comment: The mouse didn't push me to install any software. It just plugs in and works. So fingers crossed i should be safe right?
Comment: That's correct.
Answer: Yes, it is possible!
A full up custom device that looks like a Basic Optical Mouse would require a fair amount of technical resources and money.
A more Do It Yourself approach might use something like The O.MG Adapter either embedded in the mouse, if there is room, or permanently attached in-line on the cable. It runs around $200 and still requires some significant technical expertise. Only you can decide how likely that is in your circumstances.
Answer:
Can this mouse be modified to inject spyware and malware onto my laptop?

In principle, yes, USB can be used to infect your computer with malware. See for example rubber ducky, juice jacking and ninja cable (as mentioned in Kate's comment).
If I were you, I wouldn't expose my computer to any risk by using a mouse given to me by a person that wants to harm me. I would ditch the mouse and buy a new one, just to be on the safe side.


How to get/copy files in HDFS into Git repo vice versa?

Question: I have files in HDFS that need to be compared with other files in the Git repo. So, I want to copy HDFS files into the Git repo. Another tool will compare that can't talk to HDFS.
Is it doable or not?
If yes please advise if there is another way to get the files out?
Answer: Some ideas that come to my mind:

You can copy the files from hdfs to local machine and then run the tool that compares the files.
a) You can do it manually, using command line tools:
hadoop fs -copyToLocal <hdfs file> <local file>

b) You can compose oozie workflow that will contain action with your 'comparer' and will fetch files from hdfs using distributed cache.
c) If you do not have command line tools available you can fetch the files using webhdfs: https://hadoop.apache.org/docs/stable/hadoop-project-dist/hadoop-hdfs/WebHDFS.html
You can stream the data content from hdfs and compare it 'on the fly' using file system API: https://hadoop.apache.org/docs/r2.7.5/api/org/apache/hadoop/fs/FileSystem.html#open-org.apache.hadoop.fs.Path-


Displaying chart with meaning and readability for users

Question: I'm working on an app and one flow will be showing a chart for a users mood. Two things the chart will include is the time and feeling of the user from  1-5. I was wondering if you think the way this image is displaying the mood feeling is too cluttered and could potentially confuse a user? I am trying to let the user know that 5 means the best feeling and 1 is the worst feeling. Should I even include the text or assume most people already know 1-5? Or maybe a small description just above instead? Also do you think the numbers on the time side is too close to each other?
Answer: Checkout the Rating Scales references at the Usability Body of Knowledge website. One of those, Tullis and Dumas (2009) offers some advice for situations like yours:

use word labels for at least the end points of your scale
avoid the trap of a bipolar scale (an example is given comparing a bipolar scale from easy to difficult to a scale from "very easy" to "not easy at all")

Based on the above heuristics, the word labels on the "mood" axis are important! Consider trying a design without the numeric labels, instead using unlabeled marks or a solid axis with an arrow pointing upward and a single label, "improving mood". It might also be possible to use an icon or emoji to represent the end points of the scale.
In addition to the "mood" scale, consider the UX of your time scale. What do the numbers on the time axis represent? If those are days, consider labeling the axis "Day" instead of "Time" and consider how to indicate the month. It may be appropriate to use a chart tile "Mood in January" for example. Or, maybe relabel the drop down menu that says "Day, Month" to "Mood in January".
Caution: my answer assumes that it is correct to show mood as a scalar value, ranging from bad to amazing. A quick look at the Wikipedia article for mood raises the possibility that a 5-point scale may not accurately represent psychological mood. For example, what number is "irritable" compared to "anxious"? It may be that mood is more effectively represented as positive or negative.
Answer: What you have on the y-axis is clear.
The x-axis is not clear because there are no units. The dropdown at the top says 'Day, Month', yet it looks like x-axis is showing hours of the day.
A few suggestions:

I would challenge you to consider the value of assigning specific numeric values to mood. Does each number have real meaning? Assuming the answer is no, I suggest you collect input in an open slider that has no numbers:

Roll up the time values on the y-axis to unclutter it.

The underlying question is: Is there value in associating exact numeric values to exact times – or – is it more meaningful to collect and present the a relative picture of mood over time. If it's the latter, then your chart of results becomes much simpler.
Comment: The dropdown is actually meant to be it's own separate thing. It will be a calendar style picker to switch dates easily. The x axis is suppose to represent hours of the day. The ideas you gave are solid and I think this can work.
Comment: Interesting about the dropdown. I see it now. I think I was caught up on the mismatch between it and the chart. Good to hear some of the ideas above are helpful, @Ralphunreal. Will you accept and upvote it please? Just getting start here on ux.stackechange.com so I'm not ashamed to grovel a bit ;-D


How can I convert Unicode to uppercase to print it?

Question: I have this:
>>> print 'example'
example
>>> print 'exámple'
exámple
>>> print 'exámple'.upper()
EXáMPLE

What I need to do to print:
EXÁMPLE

(Where the 'a' gets its accute accent, but in uppercase.)
I'm using Python 2.6.
Answer: I think it's as simple as not converting to ASCII first.
 >>> print u'exámple'.upper()
 EXÁMPLE

Comment: That is another question, but you have to set sysencoding to utf. Take a look here: http://stackoverflow.com/questions/5419/python-unicode-and-the-windows-console/8020#8020
Comment: if I do s = 'exámñple', how can I print s correctly in uppercase?
Comment: I mean, how can I convert s in unicode w/o this error UnicodeDecodeError: 'ascii' codec can't decode byte 0xa0 in position 2 (I was using u''+s)
Answer: In python 2.x, just convert the string to unicode before calling upper(). Using your code, which is in utf-8 format on this webpage:
>>> s = 'exámple'
>>> s
'ex\xc3\xa1mple'  # my terminal is not utf8. c3a1 is the UTF-8 hex for á
>>> s.decode('utf-8').upper()
u'EX\xc1MPLE'  # c1 is the utf-16 aka unicode for á

The call to decode takes it from its current format to unicode. You can then convert it to some other format, like utf-8, by using encode. If the character was in, say, iso-8859-2 (Czech, etc, in this case), you would instead use s.decode('iso-8859-2').upper().
As in my case, if your terminal is not unicode/utf-8 compliant, the best you can hope for is either a hex representation of the characters (like mine) or to convert it lossily using s.decode('utf-8').upper().encode('ascii', 'replace'), which results in 'EX?MPLE'. If you can't make your terminal show unicode, write the output to a file in utf-8 format and open that in your favourite editor.
Answer: first off, i only use python 3.1 these days; its central merit is to have disambiguated byte strings from unicode objects. this makes the vast majority of text manipulations much safer than used to be the case. weighing in the trillions of user questions regarding python 2.x encoding problems, the u'äbc convention of python 2.1 was just a mistake; with explicit bytes and bytearray, life becomes so much easier.
secondly, if py3k is not your flavor, then try to go with from __future__ import unicode_literals, as this will mimic py3k's behavior on python 2.6 and 2.7. this thing would have avoided the (easily committed) blunder you did when saying print 'exámple'.upper() . essentially, this is the same as in py3k: print( 'exámple'.encode( 'utf-8' ).upper() ). compare these versions (for py3k):
print( 'exámple'.encode( 'utf-8' ).upper() )
print( 'exámple'.encode( 'utf-8' ).upper().decode( 'utf-8' ) )
print( 'exámple'.upper() )

The first one is, basically, what you did when used a bare string 'exámple', provided you set your default encoding to utf-8 (according to a BDFL pronouncement, setting the default encoding at run time is a bad idea, so in py2 you'll have to trick it by saying import sys; reload( sys ); sys.setdefaultencoding( 'utf-8' ); i present a better solution for py3k below). when you look at the output of these three lines:
b'EX\xc3\xa1MPLE'
EXáMPLE
EXÁMPLE

you can see that when upper() got applied to the first text, it acted on bytes, not on characters. python allows the upper() method on bytes, but it is only defined on the US-ASCII interpretation of bytes. since utf-8 uses values within 8 bits but outside of US-ASCII (128 up to 255, which are not used by US-ASCII), those won't be affected by upper(), so when we decode back in the second line, we get that lower-case á. finally, the third line does it right, and yes, surprise, python seems to be aware that Á is the upper case letter corresponding to á. i ran a quick test to see what characters python 3 does not convert between upper and lower case:
for cid in range( 3000 ):
  my_chr = chr( cid )
  if my_chr == my_chr.upper() and my_chr == my_chr.lower():
    say( my_chr )

perusing the list reveals very few incidences of latin, cyrillic, or greek letters; most of the output is non-european characters and punctuation. the only characters i could find that python got wrong are Ԥ/ԥ (\u0524, \u0525, 'cyrillic {capital|small} letter pe with descender'), so as long as you stay outside of the Latin Extended-X blocks (check out those, they might yield surprises), you might actually use that method. of course, i did not check the correctness of the mappings.
lastly, here is what i put into my py3k application boot section: a method that redefines the encoding sys.stdout sees, with numerical character references (NCRs) as fallback; this has the effect that printing to standard output will never raise a unicode encoding error. when i work on ubuntu, _sys.stdout.encoding is utf-8; when the same program runs on windows, it might be something quaint like cp850. the output might looks starnge, but the application runs without raising an exception on those dim-witted terminals.
#===========================================================================================================
# MAKE STDOUT BEHAVE IN A FAILSAFE MANNER
#-----------------------------------------------------------------------------------------------------------
def _harden_stdout():
  """Ensure that unprintable output to STDOUT does not cause encoding errors; use XML character references
  so any kind of output gets a chance to render in a decipherable way."""
  global _sys_TRM
  _sys.stdout       = _sys_TRM = _sys_io.TextIOWrapper(
    _sys.stdout.buffer,
    encoding        = _sys.stdout.encoding,
    errors          = 'xmlcharrefreplace',
    line_buffering  = true )
#...........................................................................................................
_harden_stdout()

one more piece of advice: when testing, always try to print repr( x ) or a similar thing that reveals the identity of x. all kinds of misunderstandings can crop up if you just print x in py2 and x is either an octet string or a unicode object. it is very puzzling and prone to cause a lot of head-scratching. as i said, try to move at least to py26 with that from future import unicode literals incantation.
and to close, quoting a quote: " Glyph Lefkowitz says it best in his article Encoding:

I believe that in the context of this
  discussion, the term "string" is
  meaningless. There is text, and there
  is byte-oriented data (which may very
  well represent text, but is not yet
  converted to it). In Python types,
  Text is unicode. Data is str. The idea
  of "non-Unicode text" is just a
  programming error waiting to happen."

update: just found python 3 correctly converts ſ LATIN SMALL LETTER LONG S to S when uppercasing. neat!
Answer: I think there's a bit of background we're missing here:
>>> type('hello')
<type 'str'>

>>> type(u'hello')
<type 'unicode'>

As long as you're using "unicode" strings instead of "native" strings, the operators like upper() will operate with unicode in mind. FWIW, Python 3 uses unicode by default, making the distinction largely irrelevant.
Taking a string from unicode to str and then back to unicode is suboptimal in many ways, and many libraries will produce unicode output if you want it; so try to use only unicode objects for strings internally whenever you can.
Answer: Try it:
s = 'exámple'
print unicode(s).upper()

Comment: This is an eight-year old question that has an accepted answer, which, by the way is almost exactly the same as yours. What we might need here is a viable alternative. Make sure your answer provides that.


Can I re-enter the US for another 90 days on an ESTA after having already been there for 90 days?

Question: I was in the US for 90 days last year to visit my boyfriend. I have been back to Europe now for 3 months, and planning to go back to the US for another 90 days under the same ESTA. Is this possible?
Comment: Just a correction, ESTA is not a Visa.
Answer: Contrary to other places like the Schengen Area which have a very explicit 90/180 rule, the US is a lot more vague.
You should not use repeated or successive visits to try to live in the US, and the rule of thumb is that you should spend at least as much time outside the US as you stayed in.
So you're just on the edge of that rule, but again, it's an informal rule, and the CBP agent you may talk to when you arrive will decide whether you are allowed or not (and possibly for how long).
The questions they will want answers about (and they may ask directly or indirectly) are:

How can you afford to spend so much time in the US?
Don't you have a job to go back to?
What's your source of income?
Will you not be working in the US?
Will you effectively leave at the end of your trip and no overstay?

Depending on your exact circumstances, you could get stamped in without any further discussion, or they may ask more and more questions, and if they don't like the answers, they could either let you in but only for a shorter amount of time, or outright refuse entry and send you back home, which is an altogether unpleasant and costly experience, and can have consequences on your future visits to the US and even other countries.
We don't know your circumstances so it's difficult to judge which way it may go, but you may want to make sure you are not so close to the (informal) limit.
Or, if appropriate, you may be better off exploring options for longer-term visas (which may depend on the status of your boyfriend in the US).
Comment: Thank you so much! This is very helpful. :)
Answer: ESTA is valid for 2 years, so as long as it is valid you can use it to seek admission. That said, you may be questioned as to your intentions and ways to finance your stay. The CBP officer needs to be convinced that you'll return back home, and that you're not going to be working or studying in the US in violation of your terms of admission, and the pattern of travel may not be supportive of that.
Comment: Hi There, continue to my case above. I did send in a B1 VISA application. Though I got the decision back says " Your visa application has been refused under Section 221(g) of the Immigration and Nationality Act." It ask me to attend an interview. Although the next available time is way to far, I don't actually need to go to US anymore if it's then. Now I am wondering if I can still enter with my ESTA.
Comment: Although in the last part of the letter, it saids "Pls be advised that for U.S. Visa purpose, including ESTA, this decision constitutes a denial of a visa. ..." But does it mean that including my valid ESTA it has been all denied? Or untill the time of interview, this all doesn't count?
Comment: @Louisa you can no longer use your esta. You need to attend that interview.
Comment: Wait until the time of the interview, I would be no longer need to go to the US anymore. But I don't know what to do now, just for the future travelling I don't want to have a bad record. I guess I should still go to the interview. But can I ask them to withdraw the case by the time of the interview?
Comment: I don't think so, the current decision is tentative, but is a decision
Comment: Thanks. In case it will still be a deny after my interview, can I ever get a ESTA in the future, or do I always have to go through a VISA application process?
Comment: You'll need to go through a visa application probably. But 221(g) in this case doesn't necessarily mean it would be denied, it just means they want you to come for an interview.


What is the save DC of a supernatural ability?

Question: I am playing as a oracle who has the supernatural ability Brain Drain. It says that the target gets to make a Will save. What is the DC of this Will save? Normally a Will save's DC is 10 + spell level + ability modifier, but since it is a supernatural ability what do I add for spell level?
Answer: PFSRD:

...the DC to save against these revelations is equal to 10 + 1/2 the oracle's level + the oracle's Charisma modifier.

Because the revelation is a supernatural ability, not a spell or spell-like ability, spell level doesn't apply.  If another effect needs to refer to spell level for some reason (it happens very rarely), a suggested houserule is to use the highest level spell you could cast at the earliest level you can get the supernatural ability (for brain drain, this would make it effectively first level).
Comment: @KRyan when you have opposing magics interact, it virtually always either goes to a caster level check or one effect will check the other's spell level.  There's a part in the FAQ where a dev (Mr. Jacobs?  I can't recall) goes off on a tangent complaining about how many times he begged to have these things assigned spell levels.  It's more often done with SLAs that don't directly map to actual spells, though, like some sorcerer bloodline powers.  They're SLAs with no spell level, and he suggests the rule I suggested there.
Comment: I think just using half your oracle level works as well for the "level" of the supernatural abilities; allowing it to grow with you isn't a bad idea, and it's far easier to keep track of. Though really, *nothing* should ever be looking for that number; when does that happen?
Comment: @KRyan You mean, "When does a supernatural ability look for a spell level when that spell level isn't provided, forcing the DM has to compare it to existing spells and make an *ad hoc* ruling?" All. The. Damn. Time. *Sigh.* (Or did you mean something else?)
Answer:
Mysteries
Each oracle must choose from among the following mysteries. Unless otherwise noted, the DC to save against these revelations is equal to 10 + 1/2 the oracle's level + the oracle's Charisma modifier. Spells marked with an asterisk (*) appear in Chapter 5 of this book
Answer: The DC for a supernatural ability is usually 10 + 1/2 the class level (or racial HD) + an ability score modifier. The specific DC should be listed under the class, feat, creature description, or universal monster rule that grants the ability.
For an oracle revelation, the DC is 10 + 1/2 your oracle level + your Charisma modifier as noted under the revelation class feature.


Why does the gemarah start on daf bet?

Question: Mesechtas in the Bavli shas start on daf bet instead of daf aleph, why is this so? As a child I was told it was to give you incentive to start ("Hey, I'm already on page 2!") but that now seems both childish and wrong; for example, why then is the same thing not done in talmud Yerushalmi?). Is there a real reason for this?
Answer: The simple explanation is that this is how the printers typeset it (open up almost any book on your shelf and you will notice that the first page of the actual book not page one).
However, the Lubavitcher Rebbe (Sichas Erev Shavuos 5745) notes that everything in the world is hashgacha protis, and if the printers decided to add a title page with the name of the tractate there must be something we can learn from it. He explains that "Daf Aleph" contains the title of the tractate, which is the life-force behind the entire mesechta.
Comment: I think that leaves the fact that Yerushalmi starts on alef unexplained
Comment: I think the emphasis is more on the printers' choice to number the title page "1", than choosing to add the title page
Answer: The Taamei HaMinhagim (729) says that it's so that if you finish all of Shas you don't brag, because you didn't even learn page 1 (like what msh210 says he was told).
Answer: The answer I've been given, although I don't have a good citation for it is "because the Torah is daf aleph".
Comment: Do you mean the written Torah?
Comment: dta, welcome to the site; I hope tyou stick around and enjoy it. Thanks for this answer, which could be improved on by [editing it](http://judaism.stackexchange.com/posts/19058/edit) to clarify per @ba's question in the comment just above and also to include information on the identity of the person who gave you this answer.

Why does the gemarah start on daf bet?


Stacking two videos with a precise time offset

Question: I'm trying to use FFmpeg to produce a stereoscopic side-by-side video (Full 3D SBS) from a left-right pair of videos.
If the two source videos were perfectly in sync, I could use:
ffmpeg -i left.mp4 -i right.mp4 -filter_complex hstack stereo.mp4

Unfortunately, the cameras were not synchronized and I determined that I need to trim the first 30 frames or 1.0 second from the left video to align it with the right one.
Referring to the FFmpeg wiki on Seeking, I could either use fast input seeking with -ss 1 -i left.mp4, or accurate output seeking with -i left.mp4 -ss 1. I want accurate seeking, but unfortunately -i left.mp4 -ss 1 -i right.mp4 doesn't work the way I'd hope.
How can I accurately skip the first second of left.mp4 while starting from the beginning of right.mp4?
Answer: I ended up using the tpad filter in conjunction with hstack to delay the right side 30 frames, rather than trim the left side:
ffmpeg -i left.mp4 -i right.mp4 -filter_complex \
    "[0:v]null [left]; \
     [1:v]tpad=30:start_mode=add [right]; \
     [left][right]hstack" \
    stereo.mp4

(However without electronically synchronized shutters, I found that the frame alignment does drift over time by quite a lot.)


C++ library for drawing graphics

Question: Someone can suggest me a good, free, easy to use library for c++ that allow to draw a mathematical function in a window for microsoft windows? (e.g. the parabola x^2+5x+3=0)
Comment: i need something like the TChart component of C++ Builder (rad studio) in terms of the usage semplicity
Answer: Since you need a ready-made plotting widget, use Qwt.
It uses Qt.
You could use Qt directly as in contero's answer, without Qwt, as the task is simple enough. However, Qwt has lots of graph features built in, and the usage is straightforward.
Answer: Another option is wxMathPlot which is wxWidgets based.
From it's website:
wxMathPlot main features:

Completely mouse-driven view control: pan, zoom, scroll, box
positioning.
Printing class.
Screenshot saving of plot window (BMP, PNG and JPEG formats).
Overlay movable boxes with legend or mouse coordinate display.
Can set margins to avoid plots to cover axis labels.
Flexible axis positioning
A series of useful layer to directly plot data from STL vector, movable objects, covariance ellipse,  bitmaps, etc.
Multi-platform: runs everywhere wxWidgets does.
Answer: I wrote a program similar to this using Qt. Qt is wonderful once you get it set up, but it may take a bit of effort if you've never used it (as will OpenGL, DirectX, etc..).
You can create a QImage and set it to whatever background color you want, then run your program through the width of the image pixel by pixel calling your function to get the y value. Roughly:
<code>for (int i = 0; i < imageWidth; i++) {
   image->setPixel(i, yourFunction(i), lineColor);
}
</code>
Once you've created your QImage, you can attach it to a QLabel using setPixmap(). Once you've attached it you can then display the image in a layout.
Answer: Another wxWidgets-based option is wxArt2D, It has got tons of good features for drawing mathematical functions as curves, like you could easily pass this y=140*cos(x/20) + 80*cos(x*2/20) + 40*cos(x*4/20)" to a curve object and it will get drawn, it's amazing!
Check out these screenshots there are some curves drawn by equations in string format!
Comment: Is the double quote at the end of your example formula a second-derivative operator or just a closing double quote?
Answer: You mention your language (C++) and platform (Windows), but there are frameworks available for writing a Windows C++ application: Qt, MFC, C++Builder...  Additionally, C and C++ can interface with just about anything.  So your decision for which plotting library to use will depend on what framework you're using for your UI and on what kind of external interfaces or dependencies you're willing to introduce:

If you're using Qt, you should use Qwt, as Stefan Monov said.
If you're using C++Builder, you should try TeeChart or TMS Advanced Charts.
For wxWidgets, try wxMathPlot or wxArt2D, recommended by Eugen Constantin Dinca's answer and Parsa Jamshidi's answer.
If you don't mind calling an external program to do your plotting, then Gnuplot is a popular and powerful solution.  C and C++ libraries exist to simplify calling Gnuplot.
If you're willing to embed Python, then Matplotlib is very popular, and Python could simplify the development of some of your charts.
For an atypical solution, you could have your C++ library generate a jqPlot web page then point an embedded web browser at it.
For a framework-independent C or C++ library with no external dependencies, the most promising solution I've found is PLplot, although I haven't yet had a chance to use it.
Answer: You can use GDI/+, OpenGL, Direct3D, Direct2D as well if you're using Vista/7. There's plenty out there.
Comment: I mean some library done on that purpose, that would allow me  to draw a graph of a function with a few easy steps
Answer: Definitely gnuplot, and the library gnuplot++
Answer: I created a tool to plot graphics and published it several hours ago.
https://www.youtube.com/watch?v=xD080qQVaD8&feature=youtu.be
https://github.com/burlachenkok/plotter_plusplus
To use this tool you can use desktop computer to show graphics.
Your target project can be run anywhere in any language in any platform - to update graphics just send data over the network.

C++ library for drawing graphics


Probability of getting two events from a Poisson process, given a total of two events

Question:
Let $\{X_t\},\{Y_y\},\{Z_t\}$ be independent Poisson processes, of rates $\lambda_1,~\lambda_2\,\lambda_3,$ respectively. Assume that events arrive from all the above processes. Find the probability the next two events (from now) concern the process $\{X_t\}.$

Attempt. Let $t>0$ be the time we get exactly two events, that is $X_t+Y_t+Z_t=2$, where $X_t,~Y_t,~Z_t$ are rv's from the Poisson distribution of parameters  $\lambda_1t,~\lambda_2t,\,\lambda_3t,$ respectively. Given $X_t+Y_t+Z_t=2$, the rv $X_t$ is from the Binomial distribution $Bin\Big(2,\frac{\lambda_1}{\lambda_1+ \lambda_2+\lambda_3}\Big)$ (classic result from probability), so the desired probability of $X_t=2$ is $\Big(\frac{\lambda_1}{\lambda_1+ \lambda_2+\lambda_3}\Big)^2.$
Thanks in advance for the tip!
Answer: Good job. The answer is indeed
$$\left( \frac{\lambda_1}{\sum_{i=1}^3\lambda_i}\right)^2$$


Sulfur smell in one hot water heater, but not the other hot water heater

Question: We have two hot water heaters in our house; one is in the attic and one is in our crawl space. We have a sulfur smell coming from the crawl space hot water heater, but the water smells fine coming from the attic hot water heater. Our cold water smells fine throughout the house, so we don't think the well water is the issue. The smell seems to be isolated to just the hot water heater in the crawl space. Any suggestions as to why one hot water tank would smell even though the other hot water heater smells fine?
Comment: Both water heaters have tanks. Neither are tankless. Also, I should have mentioned in my original post that both water heaters are new. We just built this house last year and moved in around November 2015. That's one of the reasons we find it odd that one water heater smells and the other doesn't. Our water (cold and hot) smells fine everywhere else in the house, except from the downstairs hot water heater. Thanks
Comment: Are they both tank heaters or both tankless? Regardless, just flush out the one in the crawl space. If it has an anode rod, replace it. It probably just hasn't been cleaned out recently enough and the location doesn't help.
Comment: Are they the same model? Again it might be best to flush it. It might say in the installation manual to flush it to remove the particles and 'new' smell from manufacturing. No bets on this though. Has the smell been around or did it just show up?
Answer: Your crawlspace Water Heater's Anode Rod is shot. This can be replaced at minimal cost compared to a new water heater by a plumber or HVAC guy or by you with some good straining on a long breaker bar...AFTER the Water Heater's been turned off, de-pressurized & very slightly drained.
Solid or Segmented Anode Rods, depending on "ceiling" clearances, can be obtained at Home Improvement or Plumbing Supply places. If one Water Heater went the other could be close behind & should be done as well, since checking it is the time to just replace it. There's nothing wrong or bad about replacing it too soon.
Comment: Thanks Iggy. Both of the water heaters are new. I should have mentioned that. We just built this house and moved in around November 2015. Knowing that both water heaters are new, would that change your recommendation?
Comment: Ah yeah Scott, doy! Sorry, I'm just kidding. Actually that doesn't change anything & the Anode Rod should be the only culprit. That tank may have been roughly handled getting it down there, which is quite plausible. The good news is that the installer should fix it for free & no need to do anything with the other one, yet.
Comment: This was very helpful Iggy. You are 100% correct about fixing it for free. The plumbing company was at my house this AM to replace the entire unit since it was under warranty. Hopefully that solves it. I was worried I might have to fix it myself. Thanks for your time responding here.
Comment: Fantastic & it better solve it! Otherwise, you've got Chinese Drywall or a very bad Chef in the house. I'm so glad you didn't have to put up with it & pull anyone's teeth.
Answer: The sulfurous hot water heater may have sulfate-reducing bacteria in it. These are typically removed by chlorinating the heater tank and its associated lines. Switching the anode inside from magnesium to aluminum (if applicable) is also suggested online; water reacting with a magnesium anode, if present, is more likely to make the H2 that the bugs live off. But don't ditch the anode entirely, as the reaction can also occur on the steel innards of the tank if they're exposed (and the steel innards will now begin to corrode, which the anode is supposed to prevent).


Android: SQLite - insertWithOnConflict

Question: I am calling insertWithOnConflict, using SQLiteDatabase.CONFLICT_IGNORE. However, when a conflict occurs "-1" is returned instead of the id of the existing row. How do I correct this?
Table creation:
EDIT :
String CREATE_CATEGORY_TABLE = "CREATE TABLE "+TABLE_CATEGORY+"(" +
    BaseColumns._ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+
    KEY_CATEGORY_NAME+" TEXT UNIQUE" +
    ")";
db.execSQL(CREATE_CATEGORY_TABLE);

Insert statement:
ContentValues values = new ContentValues();
values.put(KEY_CATEGORY_NAME, name);
int catID = (int) db.insertWithOnConflict(TABLE_CATEGORY, null, values, SQLiteDatabase.CONFLICT_IGNORE);

Comment: A return value of -1 means an error has occurred. Does it also return -1 if you insert a unique (non-conflicting) row?
Comment: @Graham Borland : No. A non conflicting insert will return the correct row id.
Answer: insertWithOnConflict, using SQLiteDatabase.CONFLICT_IGNORE does not work as expected and should probably be avoided altogether, as per this issue:
https://code.google.com/p/android/issues/detail?id=13045
Answer: Android expects the primary key column to be called _id. Might be the cause: since the column does not exist, it can't return the value and returns -1.
Answer: SQLiteDatabase.CONFLICT_IGNORE comment is supposed to function the same way as you had observed. While trying to insert, if there is no conflicting row, then it will insert a new row with the given values and return the id of the newly inserted row. On the other hand if there is already a conflicting row (with same unique key), then the incoming values will be ignored and the existing row will be retained and then the return value will be -1 to indicate a conflict scenario. To know further details and to understand how to handle this return value, please read Android/SQLite: Insert-Update table columns to keep the identifier
Answer: The workaround that I used is using insertOrThrow instead of insertWithOnConflict, and explicitly catching SQLiteConstraintException. You need to explicitly catch it because it inherits from RuntimeException.
I had to use this workaround because insert was dumping the database scheme to the logs when there was a conflict, and that was unacceptable.
Answer: try {
        long id = db.insertWithOnConflict(StatusData.TABLE, null, values, SQLiteDatabase.CONFLICT_IGNORE);
        if (id == -1){
            throw new RuntimeException(String.format("%s: Failed to insert [%s] to [%s] for unkwon reason.",TAG,values,uri));
        }else
            return ContentUris.withAppendedId(uri, id);
    }

I am still able to get the row inserted into the database, the CONFLICT_IGNORE does not work as expected @Tom is right but i am not sure if that issue was fixed

Android: SQLite - insertWithOnConflict


Retrieving SSIS 2012 environmentvariable.name via power shell

Question: We are using power shell to deploy our 2012 SSIS packages and have environment variables on a SSIS 2012 Server. Now during project deployment I am attempting to loop through eachvariable in the environment variables collection (foreach($variable in $environment.Variables)). That is no problem. I can see "EnvironmentVariable[@Name = 'something']"....however attempting to retrieve the name ("something") from the variable via $variable.Name or $variable.Key doesn't work.  I've tried looping through $environment.Variables.Keys and still nothing. My power shell skills are a little weak since I've been using NANT the past several years but is there something I'm just not seeing?
Thanks in advance,
Anthony
Adding snippet of existing power shell script.  The bolded $variable.Name is not working within the CreateETLPackages task.  There is a lot of setup and other scripts called from this scripts so I haven't included everything.  When $variable.Name is returned in a debug statement it returns "EnvironmentVariable[@Name = 'something']" as I mentoned in my original post:
Task CreateSSISFolder -Depends CreateSSISCatalog {
    if (!$script:SSISCanBeDeployed) { return }
<code># Create the project for the packages in the catalog
$catalog = $script:SSISCatalog
if ($catalog.Folders.Count -eq 0) {
    Write-Host "Creating folder $SSISFolderName ..."
    $script:SSISFolder = New-Object "Microsoft.SqlServer.Management.IntegrationServices.CatalogFolder" ($catalog, $SSISFolderName, "Folder for EDGE ETL packages")
    $script:SSISFolder.Create()
    Write-Host "... done"
} else {
    Write-Host "SSIS folder $SSISFolderName already exists; skipping create"
}
</code>
}
Task CreateSSISEnvironment -Depends CreateSSISFolder {
    if (!$script:SSISCanBeDeployed) { return }
<code># Create the environment in the project
$folder = $script:SSISFolder
$environment = $folder.Environments[$SSISEnvironmentName]
if ($environment -eq $null) {
    # Create the environment
    Write-Host "Creating environment $SSISEnvironmentName ..."
    $environment = New-Object "Microsoft.SqlServer.Management.IntegrationServices.EnvironmentInfo" ($folder, $SSISEnvironmentName, "Environment to configure the SSIS packages")
    $environment.Create()
    Write-Host "... done"

    # Now create the variables (Constructor args: variable name, type, default value, sensitivity, description)
    $environment.Variables.Add("TestDatabase", [System.TypeCode]::String, "Data Source=$SSISServerName.TestDatabase;User ID=<USERNAME>;Password=<PASSWORD>;Initial Catalog=EdgeAviTrack;Provider=SQLNCLI11.1;Persist Security Info=True;Auto Translate=False;", $false, "Connection string for TestDatabase database")
    $environment.Alter()

} else {
    Write-Host "Environment $SSISEnvironmentName already exists; skipping create"
}
</code>
}
Task CreateETLPackages -Depends CreateSSISFolder, CreateSSISEnvironment {
    if (!$script:SSISCanBeDeployed) { return }
<code># Get list of ETL .ispac files in the solution
$SSISProjects = GetListOfDeploymentFiles "*.ispac"
if ($SSISProjects -ne $null) {
    $folder = $script:SSISFolder
    $environment = $folder.Environments[$SSISEnvironmentName]
    if ($folder -ne $null) {
        foreach ($file in $SSISProjects) {
            # Read the ispac file, and deploy it to the folder
            [byte[]] $projectFile = [System.IO.File]::ReadAllBytes($file.FullName)
            $nameParts = $file.Name.split(".")
            $curProjectName = [string]::join(".", $nameParts[0..($nameParts.length - 2)])
            Write-Debug "Deploying SSIS project $curProjectName"
            $project = $folder.DeployProject($curProjectName, $projectFile)

            if ($project.Status -ne "Success") {
                Write-Error "SSIS packages did not deploy correctly!"
            } else {
                # Get the full information set, rather than the short version returned from DeployProject
                $project = $folder.Projects[$curProjectName]
            }

            # Connect the project to the environment to stitch up all the connection strings
            if ($project.References.Item($SSISEnvironmentName, ".") -eq $null) {
                Write-Host "Adding environment reference to $SSISEnvironmentName ..."
                $project.References.Add($SSISEnvironmentName)
                $project.Alter()
                Write-Host "... done"
            }

            # Connect all the project parameters to the environment variables
            Write-Host "Adding connection string references to environment variables ..."

            foreach($varialble in $environment.Variables) {
                try {
                    $project.Parameters["CM." + **$varialble.Name**  + ".ConnectionString"].Set([Microsoft.SqlServer.Management.IntegrationServices.ParameterInfo+ParameterValueType]::Referenced, **$variable.Name**)
                }
                catch {
                    Write-Debug "Unable to set connection string **$variable.Name** on SSIS project $curProjectName"
                }
            }
            $project.Alter()
            Write-Host "... done"
        }
    }
}
</code>
}
Comment: This question is about the 2012 SSIS Environment variables/configuration, which is completely unrelated to the operating system's environmental variables. Could you provide more of your powershell script? I started up SQLPS but did not see anything that corresponded to the integration services catalog. I did see Databases\SSISDB but I would have expected something custom.
Comment: billinkc did you happen to get the chance to look over the scripts I sent?  Still trying to figure this one out.  -Thanks Anthony
Answer: Ok I found my issue.  Looks like I was trying I need to use the $($object.Name) to get what I need out.  Appreciate those that reached out to for their help.
Thanks,
Anthony


what is the best way to upgrade security patches on ubuntu 14.04

Question: I am trying to upgrade security patches on production boxes.
Need to know how can i plan this activity.
I also need to make sure that in case something is wrong then how do i roll the updates.
Comment: Then you simply keep your system up to date and updates, including security patches, will be installed when they are available. You may also automate security only updates. http://askubuntu.com/questions/194/how-can-i-install-just-security-updates-from-the-command-line
Comment: It is unclear what you are doing / wanting . If you are writing your own patches , or you are downloading patches from somewhere and using something other then `sudo apt-get update && sudo apt-get upgrade` support will be likely  limited.
Comment: Well i am using official ubuntu repo.I am looking for an option to install specific security update and Just in case anything goes wrong with any specific update ,I am looking for option to have a rollback to previous state.
Comment: I want to do it manually.Is there any option to do that.
Comment: `sudo apt-get update && sudo apt-get upgrade`
Comment: see also http://askubuntu.com/questions/152179/how-do-i-check-only-security-updates-from-the-command-line
Answer: You do that by using common business practices:

Read the Ubuntu Security notices
Keep system back-ups of your system (you're definitely user type 4)
Have a test system (virtual or not) to test updates before rolling them out
Use secure passwords and don't re-use them.
Install software intelligently and keep it updated as well.
etc...
Comment: Don't thank me!  ;-) If you like my answer, just click the little grey **☑** under the "0" now turning it into beautiful green.  If you do not like my answer, click on the little grey down-arrow below the 0, and if you *really* like my answer, click on the little grey checkmark *and* the little up-arrow...  If you have any further questions, go to http://askubuntu.com/questions/ask


How do acids prevent ferrous sulfate from getting oxidised?

Question: If $\ce{FeSO4.7H2O}$ is dissolved in an acidic environment, for example in 0.05 M aqueous solutions of methanoic or ethanoic acid, would that prevent it from getting oxidized if an oxidizing agent like bromine water was added to it? If so, how? Since this is not examining oxidation with respect to air or oxygen.
Comment: @user109975 You should be able to do it yourself, shouldn't you ?  Ferric ions have much greater hydrolysis tendency than ferrous ions, what leads to decreasing ratio of ferric/ferrous ions and decreasing redox potential, making it some what less vulnerable to oxidation in acidic solutions. But is is not sufficient not to be oxidized by bromine. Carboxylic acids presence brings another factor, forming complexes with iron. See https://en.wikipedia.org/wiki/Iron%28III%29_acetate  and https://en.wikipedia.org/wiki/Iron%28II%29_acetate
Comment: Diluted solutions of $\ce{FeSO4}$ are partially hydrolyzed, producing $\ce{[Fe(OH)(H2O)5]+}$ ion. In the presence of an acid in aqueous solution, the main ion containing iron is $\ce{[Fe(H2O)6]^2+}.$ This ion must be more resistant to oxidation than the partially hydrolyzed ion.
Comment: @Maurice can you please provide the equations for the formation of the respective ions?
Answer: No, adding acid to a ferrous sulfate solution will not prevent its being oxidized by bromine water.
Fresh FeSO$_4$ solutions are light blue-green, almost colorless, but pick up O$_2$ readily:
Fe$^3$$^+$ + e$^-$ --> Fe$^2$$^+$       +0.770 V and
O$_2$ + 2 H$_2$O + 4e$^-$ --> 4 OH$^-$    +0.401 V
(The half cell voltages are only indicative of what's going on, because we are not at standard concentrations of 1 M.)
The light-colored solution quickly becomes yellowish and consumes all the oxygen in the vessel, and then sucks in more air and consumes that oxygen, and then things slow down a little, but diffusion still lets a bit more oxygen get in, and the "ferrous" becomes somewhat ferric, and the liquid becomes a muddy color and you wish you could preserve the nice blue-green color somehow.
You could preserve the ferrous if you could somehow complex it and keep it from oxidizing to ferric. But nature prefers to complex the ferric ion: smaller ion, bigger charge. Typical ferric stability constants are larger than ferrous by ten orders of magnitude.
It is instinctive to suppose that metals will oxidize in the presence of O$_2$, and if higher valences are possible, well, then, the metal will go as far as possible. But the oxidation of ferrous to ferric is unfavored (+0.770 V) and Fe$^2$$^+$ needs help from O$_2$. The reduction of water is also unfavored, but is driven forward by the consumption of OH$^-$ ions by precipitation by Fe$^+$$^3$, which also keeps the Fe$^+$$^3$ low.
LeChatelier predicted as much: by increasing the acidity, you reduce the availability of electrons from OH$^-$, and O$_2$ is more able to take electrons from Fe$^+$$^2$.
So you could say that adding acid stabilizes the ferrous ion, but what it really does is inhibit the oxygen molecule. Bromine is totally unaffected.
Comment: How about just adding metallic iron to the ferrous sulfate solution and, of course, keeping the solution in a sealed bottle to reduce oxygen issues? Ferric ions will certainly oxidize iron, with ferrous ions being the result.
Comment: @Ed V: I like that approach to keeping the ferrous as Fe+2. Why have I never heard of it before? We put desiccants in solvents to keep them dry. Sodium in benzene. Iron in ferrous sulfate solution sounds great!
Comment: We used to do it in labs I was in. One little problem: iron powder is readily available, and I even used to have two 5 pound bottles of it. But high purity iron is a bit harder to find. We used small pieces of high purity iron wire: just drop a clean piece in the solution.


Standard communications protocol for cubesats

Question: Is there a well-accepted standard protocol for communicating between a cubesat and ground station?
On what basis would I choose the protocol?
Answer: This ESA presentation has some considerations regarding frequency allocation. Getting an allocation from ITU can turn out to be the hardest part of your project, so --- to my knowledge --- all cubesats use amateur radio bands. In the 2m VHF band, some frequencies are reserved for satellite telemetry by IARU.
IARU states "all modes", but according to ITU Radio Regulation 25.2A, your transmissions in amateur radio bands need to be accessible to other radio amateurs. You are free to create a new modulation scheme and/or protocol, but you would need to publish it. To keep things easy, cubesats usually go for AX.25, for which tested hard- and software is available.
Answer: I'm not aware of any studies on different comms protocols in use and which ones are most common. I did find this page on the Cubesat Space Protocol.
More generally about space comm protocols, the CCSDS publishes a wide set of recommendations and reference implementations at various layers.
If I was starting from scratch I'd probably first look into what radios were available and if their designs presume anything about comm protocols. Many include packet formats, forward error correction codes, and other details that it will be a pain to work around.
If you're going to use an existing ground station you should also ask them for an ICD defining what protocols they already use.


Getting Stale object error. Optimistic Locking: How does it work?

Question: I think I've eliminated everything, but I'm not sure I understand OL perfectly enough to be sure. In general, let's say you and I are on a team to keep a foo up to date. I'm in one room and decide to save time I'll update the foo myself. So I start updating it. A minute later you have the same idea and log onto the edit page to update it as well. What happens if I finish first? What happens if you finish first? In a configuration where it fails how does it distinguish between someone editing and someone reading. If I catch and reload to update the lock I lose all my changes, how is this solved? Here, it's simple to redo the update, but potentially it's part of a more complicated form object.
My specific problem came when (best I can make out) loaded one copy in my browser, later forgot about it and then one in my console (also lock: 0?) couldn't update the one in my console with stale object error. Noticed the browser thing. Closed my console. Tried to reload my browser and got stale object error as well. Here's the code that's failing:
=>  7:       self.update_attributes({
    8:         failed_view_attempts: self.failed_view_attempts += 1,
    9:         failed_view_at: Time.now
   10:       })
   11:     end
(byebug) self
#<Product id: 12... lock_version: 0>

#=> ActiveRecord::StaleObjectError (Attempted to update a stale object: Product.)

Things I've tried:
To see if another instance was being loaded I added puts "CALLED !!!!" in an after_initializecallback, but it only printed once.
And checking self.changed after rescuing from the error and get back ["updated_at", "failed_view_attempts", "failed_view_at"]
Answer: Need to set lock_version column default to zero (0).
Answer: Optimistic locking is based on an object version number.
Reading and object should not affect the version number at all.
If you try to update some object, this version number is compared (in sql actually update statement is used for example "update ... where version = 1 and ..." ) and increased on update.
If the comparison fails when trying to update, you get the stale object error. This means that the object was modified by somebody else while you was doing your changes.
To resolve this error you need to load the object again to get the actual version and maybe merge the changes manually (presenting the user some info about it, and let user decide for example).
Comment: But, if while I'm editing someone calls an instance of the same row to read it it will bump the version number. It's based on loading it, not what you do with it, correct?
Comment: not really, if you load it, the version number remains the same, otherwise there will be a lot of updates so the version number is only bumped on update (i.e: update version = 2 where version = 1) and if no record matches the where then you get the stale object error. The problem with page reload can be that it is cached and you are not reloading the object from DB.
Comment: Yes, the browser using a cached version is something I'm already familiar with