Let A be a square matrix of order $n$ such that $A^{2}= I$. Prove that if $1$ is the only eigenvalue of $A$, then $A = I$.

Question: I have been trying to solve this for hours now and still have no idea. I have tried:
a) substituting $\lambda = 1$ into $\lambda x - Ax = 0$.
b) substituting $\lambda = 1$ into $\det(\lambda I-A)x = 0$.
Both ways have proven ineffective. Any help would be appreciated.
Comment: Rewrite $A^2-I$ as $\left(A+I\right)\left(A-I\right)$, and meditate on the kernel of $A+I$.
Comment: To make @darijgrinberg's nice suggestion clearer: on the one hand $A^2-I = 0$ - on the other do you see that $A+I$ is invertible?
Answer: We have $A(x-A(x))=A(x)-A^2(x))=A(x)-x=-(x-A(x))$ thus $x-A(x)$ is a eigenvector with eigenvalue is $-1$, since $1$ is the only eigenvalue, $x-A(x)=0$, thus $x= A(x)$.
Comment: What is the identity for you?
Comment: If x = A(x), why is A = Identity?
Comment: Correct me if I'm wrong but, if x is not invertible, A is not necessarily the identity matrix?
Answer: You have $(A+I)(A-I)=0$. If $1$ is the only eigenvalue, then $A+I$ is invertible. Therefore,
$$
     0=(A+I)^{-1}(A+I)(A-I)=A-I \implies A=I.
$$
Answer: Hint:
$x^2-1$ is an annihilating polynomial of $A$. Hence, either it is the minimal polynomial (in which case there are $2$ eigenvalues) or the minimal polynomial is one of its divisors.


I need to get the divs inside the main div and if the data inside them is empty hide theat div

Question: I have a main dive and inside that there are 2 dives. I need to check that if div's data is empty don't show them. BTW data comes from API.
Here is code:

               {$feed/API Feed_142197/__data["1-Title"]}

{$feed/API Feed_142197/__data["1-Desc"]}

{$feed/API Feed_142197/__data["1-Price"]}

click to call image

              {$feed/API Feed_142197/__data["2-Title"]}

{$feed/API Feed_142197/__data["2-Desc"]}

{$feed/API Feed_142197/__data["2-Price"]}

click to call image

Comment: As concerned as your code I can see the 2 div situation twice. Do you mean the two divs without id's?
Comment: You can find the solution to your problem by reading [How to check if element has any children in Javascript?](http://stackoverflow.com/q/2161634/218196) and [javascript hide/show element](http://stackoverflow.com/q/6242976/218196).
Answer: using jQuery
var div1 = $('#product1'),
    div2 = $('#product2');

if (!(div1.text() || div2.text())) {
     $('#select').hide()
}

Comment: And without jQuery? What if the OP does not even know what jQuery is?
Comment: what if? well, it will be much harder for them to code in-browser JS
Comment: I actually meant that you maybe explain at least what jQuery is and provide a link...
Answer: Here is a modern browser, no libraries required solution.
var nodes = document.querySelectorAll('#select div:empty');
for (var i = 0, il = nodes.length; i < il; i++) {
    nodes[i].style.display = 'none';
}


Tools or Techniques for Removing Grass and Moss from Brick Patio

Question: This is what I'm dealing with - rudimentary efforts have not paid off and I feel like I must be missing something.
Comment: @BrownRedHawk bleach will kill the top of the plant, the root will live tho and grow back. If I wasn't using roundup for this job I'd chose salt and ammonia which will kill the root, roundup is still better for this tho but pricier.
Comment: Have you tried plain old bleach and water? I find it kills just about everything, and is great in general. I would bet muriatic acid would be similarly effective, just by nature of its strength
Comment: I would be interested in eco-friendly approaches.
Answer: Round-Up 365 will stop frequent reoccurrence. But, with Round-Up 365 only, you spray everything down & when dead & dry in 2-weeks, just scuff the remnants away with your shoe or a string trimmer.
Birds & wind are your enemies & the only way to avoid this entirely is to go with slab concrete. Not a good option unless it's colored concrete, your pavers look worlds better. You'll need to repeat the Round-Up 365 & shoe or string trimmer annually or bi-annually.
Filling the paver joints won't do anything good. It would ruin drainage, looks & the pavers much needed movements.
Comment: +1 We used to have a patio just like this. Roundup all the way.
Comment: Thank you!  That's really helpful.  One question about Round Up.  There are occasionally bunnies that come by and nibble on these weeds and grass.  Will that product poison them?  (It might be okay if I physically pull out the tallest ones, those seem like the main ones the bunnies are drawn to)
Comment: No problem, they sniff out what's healthy or not first. But, you can trim them down with a mower at its lowest setting or a string trimmer, animals usually just eat the new growth tips. Also the paver joints are just filled with regular sand, so anything you pull out you can just broom sand back in or over the whole patio to fill-in back to the top.


error: (-215:Assertion failed) !empty() in function CV2 Error

Question: I am making a program in python that just draws a rectangle around a car. I am currently stuck on getting the coordinates of the car, here is the code:
#################################################
import cv2
#################################################
car_data = cv2.CascadeClassifier(cv2.data.haarcascades + "cars.xml")
img = cv2.imread("car_front.jpeg")
#################################################
img_but_bnw = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

car_coordinates = car_data.detectMultiScale(img_but_bnw)
print(car_coordinates)

#################################################
cv2.imshow("Detect Everything", img_but_bnw)
cv2.waitKey()
print("Code Completed")
#################################################

I am running in on an error with the function "cv2.detectMultiScale".
error:
File "e:\Python2\Body_Detection.py", line 11, in <module>
    car_coordinates = car_data.detectMultiScale(img_but_bnw)
cv2.error: OpenCV(4.6.0) D:\a\opencv-python\opencv-python\opencv\modules\objdetect\src\cascadedetect.cpp:1689: error: (-215:Assertion failed) !empty() in function 'cv::CascadeClassifier::detectMultiScale'

I have tried googling, it says to use cv2.CascadeClassifier(cv2.data.haarcascades + "cars.xml") instead of cv2.CascadeClassifier("cars.xml"). It didn't work :(, Any help would be appreciated.
Comment: this is being asked every other day. please use the search function.
Comment: Maybe first use `print()` (and `print(type(...))`, `print(len(...))`, etc.) to see which part of code is executed and what you really have in variables. It is called `"print debuging"` and it helps to see what code is really doing.
Comment: OpenCV doesn't raise error when it can't read file but later it show problem when you try to use files. You should first check if you get data from `.xml` and from `.jpg` because they can be empty. ie. image may need to use `/full/path/to/image.jpg`. You could also check if `cv2.data.haarcascades + "cars.xml"` really exists on disk. See `print( os.listdir(cv2.data.haarcascades) )`
Comment: I checked `print( os.listdir(cv2.data.haarcascades) )` on my computer and there is NO `cars.xml`. If it is your file then better use `/full/path/to.cars.xml` because code may run from different folder and it may not find this file in your folder.
Comment: Your code is working If I used this cv2.CascadeClassifier("cars.xml"). But in ur case the filename is not in currently directory or probably misspelled filename or extension.
Answer: The file cars.xml is not part of the opencv library although you may find tutorials in the internet that use this filename. The folder addressed by cv2.data.haarcascades includes xml examples for things like eye and face detection (current content see https://github.com/opencv/opencv/tree/master/data).
You can search for an existing cars.xml example by other authors and copy it to your project folder. Then just use "cars.xml" without cv2.data.haarcascades.
E.g. I found this project Vehicle Detection with Haar Cascades that includes a file cars.xml working fine with your code above.
Comment: yeah so, it was just my stupid brain. the "cars.xml" file didn't actually have XML code in it...

it had like ```  ```


Linq Include just one object from a one to many relation

Question: I have two tables with a one to many relation.
One Order has many Products.
I want to take a list of Orders with the free Product in each (one per order).
I've tried something like this:
this.ObjectContext.ORDERS.Include("PRODUCTS").Where(e=>e.PRODUCTS.price == 0).OrderBy(e => e.Order);

But this is not working.
Is there any other approach??
Thanks in advance.
Answer: if PRODUCTS is a collection, you can use the Any() extension method to find out if any product is free (alternatively, the All() method to find out if all products are free):
this.ObjectContext.ORDERS
                  .Include("PRODUCTS")
                  .Where(o => o.PRODUCTS.Any(p => p.price == 0))
                  .OrderBy(e => e.Order);

Based on your clarification of the desired output (all orders with optional free product), you can use this query:
this.ObjectContext.ORDERS
                  .Include("PRODUCTS")
                  .Select(o => new {
                      Order = o,
                      FreeProduct = o.PRODUCTS.FirstOrDefault(p => p.price == 0)
                  });

It will return a sequence of an anomymous type containing the order, and the free product (or null if no free product exists).
Comment: What happens if there isn't any free product? Would it return the order without the PRODUCT??
Comment: @zapico No, it would not return the order at all. The orders without free products are just skipped. And if no order contains a free product, you will get an empty sequence.
Comment: :( Is there anyway to make it return the Order?? Or should I return them in other query and return both lists together?? Thanks for your help :)
Comment: @zapico I thought you want only the orders with at least one free product?
Comment: No no, I want all the orders with a free product if it has it (there is no way to have more than one free product in an order)
Comment: @zapico Sounds the same to me. The products are returned together with the orders anyway. What should the desired output look like?
Comment: It would be something like: "Order 1 - Product Free 1, Order 2 - Product Free 2, Order 3 - Product Free 3, Order 4 - null, Order 5 - Product Free 4"... I want ALL the orders and, if they have a free product, the free product.
Comment: @zapico Ah, i see. I updated my answer with a query that should work.


How can I break blocks remotely?

Question: I want to break blocks far away (e.g. A piece of glass 50 blocks away) with commands, but I don't know if there's any way.
Is it possible to break a block (literally break a block, which means with sound & with particles) with a command? Or should I use the /particle /sound and /fill command to "break" the block? (/particle will create the glass-breaking particle, /sound will play the glass-breaking sound, and the /fill command will fill the glass with air.)
Comment: Wild idea, not even remotely sure if it is possible. But a very localized explosion without sound? Or that not possible?
Comment: I tried to use `/summon Fireball ~ ~ ~ {ExplosionPower:1,Direction:[0.0,0.0,0.0]}`but it cannot break obsidian, and it causes a very loud explosion.
Answer: This should do it.
/setblock <x> <y> <z> minecraft:air 0 destroy

From Minecraft Wiki:

destroy — The old block drops both itself and its
contents (as if destroyed by a player). Plays the appropriate block
breaking noise.
Comment: I did not expect this option.
Answer: Use /setblock ~ ~ ~ air 0 - making sure that the chunk the block is in is loaded.
Alternatively, put the /setblock command in the spawn chunks so that no matter where you go it will destroy the block. This is because when you reach the chunk and load it in, the command block will perform the setblock command.

How can I break blocks remotely?


What underlay is used for installing pool tiles

Question:
Is it concrete? (i.e. cement and water)
Is it some kind of special caulk?
Is it something else?
Answer: You are going to use pool plaster to build up the area, modified thinset to apply the tiles and epoxy grout to grout the area.
Additional info -
Your pool will generally have a pool plaster for the "liner" (what you feel).  It could however have a ton of products - example is pebbletech - for this.  It really depends on how nice your pool is.   Pool plaster is generally made of concrete, sand, and quartz.  There are other combos and there is premade combos too.  If you are doing your whole pool then you can choose whatever you want - each will have their own characteristics.  If you have a question on this I would ask it on its own since you will get a lot of different views/help.
If you are doing patchwork then you will need to try to match up the characteristics of current "lining".  This will take practice/guesswork and maybe bringing in a little experience.
For the tile section at the top of the pool you generally want to buy tile that curve towards the pool bottom so there is a smooth transition or you will need to feather up to the tile area with a thicker amount of plaster (they sell very expensive "pool tile" for this).  This will create an indention to apply your thinset and tile.  And you will basically tile as you would a shower.
I would use a modified thinset that is best suited for the type of tile (a lot of pools use porcelain) you are using.  Note that under your tile should be sealed with pool plaster.  So the tile is really just decorative.  This is where there are differences in showers and pools.  Using tiles on the top ledge or steps in pools should be used to provide a nice surface/decorative - not as any sort of moisture barrier.
A lot of DIYers use "regular" porcelain/granite tile (I would not use marble or ceramic and I would make sure the porcelain I use has a low absorption rate) and can buy everything from a big box.  The hardest part is making sure the tile plus thinset depth is close to the depth of the adjoining plaster - for pool steps you don't have to worry about this.
And if you are replacing tile a lot of the stuff should be kind of set up for you.  You will damage some of the plaster when chipping out the old thinset.  You might have to make some repairs - I guess if the repairs are behind tile your plaster type is less important as long as it bonds.  Also you will need to match up the old tile thickness to the new tile thickness.  If you go with a new "thicker" tile it could create a lot of work because you may only have so much plaster you can get rid of before you hit the concrete base.  In general almost all pools with a tile layer on the top sides have a "lip".  You won't match it up exactly.  But you want to make sure that it isn't dangerous - as far as people scraping themselves.  And with a larger lip there is more upward force that could be put on the tile - causing more needed repairs down the road.
Comment: what kind of thinset should I use? Is there a "name" I can just buy or if not, what are the components / proportions? thanks.
Comment: mapei modified thinset is fine - epoxy grout brand doesn't matter - pool plaster is usually a mix on concrete, sand, quartz...
Comment: you mean something like [this](http://images.lowes.com/product/converted/093994/093994104502.jpg) for a thinset? or "that" plus cement and water? is there just the thing I can buy to dilute with water and apply tiles on? thx.
Comment: See my edits to the answer.  Something like that if you are using glass block tiles.  I would read - http://www.mapei.com/public/US/catalogues/102/EN/PDF/102_US-EN.pdf.  It gives specific examples of Mapei products that are suitable for water immersion.  Laticrete has a similar specsheet.  I didn't put these in the answer because the links may change.  Either way the specsheet will say water immersion or under water.  You can also call them (Mapei/Laticrete) up once you have your tiles picked out and they will tell you what they would recommend - probably the most expensive haha.


How to update pixelPosition of a custom infoWindows on Google Maps V3 after dragging?

Question: I'm creating a new mashup on top of Google Maps. It's simple enough that I chose to use V3 to provide longer life span.
However, there's some special needs that Google Maps infoWindow doesn't provide.
I've positioned my custom infoWindow with marker.projectionContainer.pixelPosition. I get correct position after zooming, but dragging doesn't update markers pixelPosition. How can I get difference between markers old position and new after drag?
or
Should I use OverlayView instead of trying to hack position from DOM? I think Maps' own infoWindows are automatically updated/parked on panels.
Answer: This answer assumes that by drag you mean dragging the marker and not dragging the map, let me know if that is not the case
You should use the OverlayView and then you can use MVC techniques to bind to the marker's position property.
<code>function MyOverlay(marker) {
  this.bindTo('position', marker);
}
MyOverlay.prototype = new google.maps.OverlayView();

MyOverlay.prototype.position_changed = function() {
  this.draw();
};

MyOverLay.prototype.draw = function() {
  // This is where you recalculate the latLngToPixel stuff where latLng
  // is this.get('position');
};
</code>
You also need to implement the rest of the OverlayView interface: onAdd and onRemove.
Comment: Assumption was right and at the time I used a solution similar to one you provided. Thanks!


Black Derman & Toy Model

Question: The BDT model is given by
$$d(\ln\,r)=\left(\theta(t)-\frac {d(\ln\sigma(t)}{dt}\ln r\right)\,dt+\sigma(t) \, dW.$$
How can one rewrite the BDT model as $dr=A\,dt+B\, dW$, using It$\hat o$?
Answer: Apply Ito's Lemma to $r = f(X) = \exp(X)$ where X = ln(r).
$$df  = \frac{\partial f}{\partial X}dX+ \frac{1}{2}\frac{\partial^2 f}{\partial X^2}dX^2$$
In this case
$$\frac{\partial f}{\partial X}= \exp(X)=r,$$ $$\frac{\partial^2 f}{\partial X^2}=\exp(X)= r.$$
Then substitute
$$dX = dln(r) = \mu(r,t)dt +\sigma(t)dW$$
$$dX^2 = [\sigma(t)]^2dt$$

Black Derman & Toy Model


Set initial combobox selection DevExpress Razor

Question: I simply want to have the "Area" value (which is one of the items) be selected when the view appears.  This is what I have:
<code>@Html.DevExpress( ).ComboBox( settings =>
{
    settings.Name = "cmbFieldLevel";
    settings.CallbackRouteValues = new { Controller = "Equipment", Action = "FieldLevelPartial" };
    settings.Properties.ValueType = typeof( string );
    settings.Properties.TextField = "AreaName";
    settings.Properties.ValueField = "AreaID";
    settings.Properties.EnableClientSideAPI = true;
    settings.ClientSideEvents.DataBound = "function( s, e ){ cmbFieldLevel.SelectedItem = "Area"; } ";
}).BindList(FieldLevel.GetAreaFilters()).GetHtml()
</code>
Any clues?
Answer: 2 ways I can think of.

If you change your ComboBox to ComboBox for you can specify the model's value

like so
<code>@Html.DevExpress().ComboBoxFor(x => x.ParamOrderNo, settings =>
{
      settings.Properties.ValueField = "OrderNo";
      settings.Width = 200;
      settings.Properties.TextField = "Name";
}).BindList(CeduleProductionMVC.ViewModels.ViewModelCeduleGlobale.GetCommandes()).GetHtml()
</code>

Also, you can set the SelectedIndex, if your combolist content is fixed, the index might always be the same everytime all the time.  Also, If you list is not fixed, you might be able to make a method to retrieve the index and set in after that.


Gnu make: Target in macro from subst

Question: I want to generate a list of equivalent targets:
TARGETLIST = a b c d e f

define RULE
$(subst X,$(1),file_X.txt) $(subst X,$(1),otherfile_X.txt) &: # some dependency
    # some commands
endef

$(foreach _t, $(TARGETLIST), $(eval $(call RULE, $(_t))))

This does not do what I want: If I want to build file_b.txt for example the recipe is not found. How do I fix this?
Comment: a `patsubst` could easily generate `file_a.txt file_b.txt ...` from the initial list, the result assigned to another var, and use that var leading a target rule; details of dependencies could vary the design
Comment: what do the dependencies look like and any relation the example elements `a b c ...` ?
Comment: @Milag That does not work; I left some part out of my answer. See the updte. Each `file_X.dat` is grouped with another `otherfile_X.dat`.
Comment: @Milag That does not seem to matter. It does not work for no dependencies.
Answer: Your problem comes from the double expansion that takes place in your macro when calling foreach-eval-call. You need to double the $ of your $(subst...: $$(subst.... But why not simply letting call do your substitutions?
TARGETLIST = a b c d e f

define RULE
file_$(1).txt otherfile_$(1).txt &: # some dependency
    # some commands
endef
$(foreach _t,$(TARGETLIST),$(eval $(call RULE,$(_t))))

call automatically replaces the $(1) occurrences in the RULE macro by the current $(_t) of the foreach loop. This is what call is made for.

Gnu make: Target in macro from subst


Execute java from batch JCL

Question: In the past I have used BPXBATCH to execute java class files from JCL. I would like to move to using the custom JVM launcher as IBM recommends in the link below.
http://www.ibm.com/developerworks/systems/library/es-java-batchz.html
I wrote up a hello world java program and compiled it on the mainframe and packaged it into a jar.
Below is an example JCL member using BPXBATCH that works.
<code>//LMGHWRLD JOB (MY,ACCOUNTING,INFO),'HELLO WORLD',
//   CLASS=A,MSGCLASS=H,REGION=512M,NOTIFY=&SYSUID
//********************************************************************
//* Run Java under a UNIX System Service shell
//********************************************************************
//STEP2 EXEC PGM=BPXBATCH,
// PARM='SH java com.foo.bar.HelloWorld'
//STDIN  DD DUMMY
//STDOUT DD PATH='/tmp/&SYSUID..bpxbatch.out',
// PATHOPTS=(OWRONLY,OCREAT,OTRUNC),
// PATHMODE=SIRWXU
//STDERR DD PATH='/tmp/&SYSUID..bpxbatch.err',
// PATHOPTS=(OWRONLY,OCREAT,OTRUNC),
// PATHMODE=SIRWXU
//STDENV DD *
CLASSPATH=/u/myuid
//*********************************************************************
//* Copy HFS output files to SYSOUT, since BPXBATCH can only write
//* STDOUT and STDERR to HFS files.
//*********************************************************************
//STEP3 EXEC PGM=IKJEFT01,DYNAMNBR=300,COND=EVEN
//SYSTSPRT DD SYSOUT=*
//HFSOUT DD PATH='/tmp/&SYSUID..bpxbatch.out'
//HFSERR DD PATH='/tmp/&SYSUID..bpxbatch.err'
//STDOUTL DD SYSOUT=*,DCB=(RECFM=VB,LRECL=133,BLKSIZE=137)
//STDERRL DD SYSOUT=*,DCB=(RECFM=VB,LRECL=133,BLKSIZE=137)
//SYSPRINT DD SYSOUT=*
//SYSTSIN DD *
OCOPY INDD(HFSOUT) OUTDD(STDOUTL)
OCOPY INDD(HFSERR) OUTDD(STDERRL)
//
</code>
I would like to use all the features using the custom JVM launcher brings as detailed in the article above.
The example above executes class files, but the article seems to suggest JAR files are needed for the custom JVM launcher. Below is the job I created to try and use the custom JVM launcher.
The JAR file is ~/HelloWorld/HelloWorld.jar on OMVS.
<code>//LMGHWRLD JOB (MY,ACCOUNTING,INFO),'HELLO WORLD',
//   CLASS=A,MSGCLASS=H,REGION=0M,NOTIFY=&SYSUID
//STEP1    EXEC PGM=JVMLDM60,
//   PARM='com.foo.bar.HelloWorld'
//STEPLIB  DD DSN=<MY.LIBRARY.PATH>,DISP=SHR
//SYSPRINT DD SYSOUT=*
//SYSOUT   DD SYSOUT=*
//STDOUT   DD SYSOUT=*
//STDERR   DD SYSOUT=*
//STDENV   DD *
. /etc/profile
. ~/.profile
export CLASSPATH=~/HelloWorld
for i in ~/HelloWorld/*.jar; do
    export CLASSPATH=$i:$CLASSPATH
    done
//
</code>
Currently the output of this job fails with a CC of 102. The specific output is below:
<code>JVMJZBL1001N JZOS batch Launcher Version: 2.3.0 2013-05-02
JVMJZBL1002N Copyright (C) IBM Corp. 2005. All rights reserved.
JVMJZBL1038E Child shell process exited with exit code: 1
JVMJZBL1042E JZOS batch launcher failed, return code=102
</code>
My region size is 200,000 so I don't believe region size is the issue. Is there something I am doing incorrectly?
Comment: I have had to increase the size of my region from 200M to 300M with our last upgrade to z/OS 1.13.  I don't recall which version of Java was installed at that time.  Think big (compared to COBOL, et. al) when it comes to Java and region size.
Comment: 200,000 what? And why do you think that? On your JOB card you have 0M. Did you try 200M?
Comment: You might want to check with the support forums Dovetailed Technologies runs.  (http://community.dovetail.com/forum/viewforum.php?f=1)
Comment: Hello Bill, 200,000 is the region size on my TSO session. I previously had an issue where I couldn't compile .java files so I figured I would bring it up in my post. I did try running with 256M, no luck. I'm still working on resolving it.
Answer: The resolution to this wound up being a change to the STDENV DD statement. The following code should work on any environment with the indicated areas changed.
<code>//STDENV   DD *
#
# Java home location
#
export JAVA_HOME=/your/omvs/path/to/java/lib
#
# Standard java path updates
#
export PATH=/bin:"${JAVA_HOME}"/bin
LIBPATH=/lib:/usr/lib:"${JAVA_HOME}"/bin
LIBPATH="$LIBPATH":"${JAVA_HOME}"/lib/s390
LIBPATH="$LIBPATH":"${JAVA_HOME}"/lib/s390/j9vm
LIBPATH="$LIBPATH":"${JAVA_HOME}"/bin/classic
export LIBPATH="$LIBPATH":
#
# Define location (and version if applicable) of jar home
#
APP_HOME=/var/location/of/your/jar
CLASSPATH=$APP_HOME:"${JAVA_HOME}"/lib:"${JAVA_HOME}"/lib/ext
# Add Application required jars to end of CLASSPATH
for i in "${APP_HOME}"/*.jar; do
    CLASSPATH="$CLASSPATH":"$i"
    done
export CLASSPATH="$CLASSPATH":
//
</code>
Comment: Understood, but env would have been same according to account used ?  BPXBATCH is just a background ISH ?  Only thinking from troubleshooting aspect here.  I often have to run "find" on the HFS for example. Good question in this case.
Comment: Gut feeling is you should have been able to test this from the "command line"  **TSO ISH** ?
Comment: This did run in ishell/omvs. I needed it to be a batch job for job scheduling, live spool output, and visibility in sdsf.

Execute java from batch JCL


$\sum_{N=6}^{\infty}\frac{6}{N}\binom{N-1}{5}p^6(1-p)^{N-6}$

Question:
Find the sum: $\sum\limits_{N=6}^{\infty}\frac{6}{N}\binom{N-1}{5}p^6(1-p)^{N-6}$

I could not find a way to manipulate $\binom{N-1}{5}$ to get any suitable form here. Note that $\binom{N-1}{5}p^6(1-p)^{N-6}$ are probability masses of negative binomial distribution.
Comment: Look here at the special cases of [Binomial series](https://en.wikipedia.org/wiki/Binomial_series). Then integrate once
Comment: @callculus It looks like the first right parenthesis belongs at the end of the whole expression.  See [here](https://www.wolframalpha.com/input/?i=%5Csum_%7BN%3D6%7D%5E%7B%5Cinfty%7D(%5Cfrac%7B6%7D%7BN%7D*%5Cbinom%7BN-1%7D%7B5%7Dp%5E6(1-p)%5E%7BN-6%7D))
Comment: It seems that it doesn´t exist a closed form. See [here](https://www.wolframalpha.com/input/?i=%5Csum_%7BN%3D6%7D%5E%7B%5Cinfty%7D%5Cfrac%7B6%7D%7BN%7D*%5Cbinom%7BN-1%7D%7B5%7Dp%5E6(1-p)%5E%7BN-6%7D) what wolfram alpha figured out.
Comment: @saulspatz Thanks for the correction. I haven´t noticed the misinterpretation of  the parenthesis by w.a .
Comment: *Mathematica* gives:

$$\frac{60 p^6 \log (p)-(p-1) p (p (p (p (137 p-163)+137)-63)+12)}{10 (p-1)^6}$$

which suggests that manipulation will be rather difficult.
Answer: What we want to find:
$$\sum_{k=0}^\infty \frac{6}{k+6}\binom{k+5}{k}p^6(1-p)^k =S(p) $$
What we know from Binomial series:
$$\sum_{k=0}^\infty \binom{k+5}{k}z^k =\frac{1}{(1-z)^6} $$
Some manipulation, and integration:
$$\int_0^{1-x}\sum_{k=0}^\infty \binom{k+5}{k}z^{k+5} dz =\sum_{k=0}^\infty \frac{1}{k+6}\binom{k+5}{k}(1-x)^{k+6} =  \int_0^{1-x} \frac{z^5}{(1-z)^6}dz = \frac{300x^4-300x^3+200x^2-75x+12}{60x^5}+\ln(x)-\frac{137}{60} $$
After substitution, and some multiplying by constants:
$$S(p) =\frac{300p^5-300p^4+200p^3-75p^2+12p}{10(1-p)^6}+\frac{6p^6\ln(p)}{(1-p)^6}-\frac{137p^6}{10(1-p)^6} $$


File upload window after Sweet Alert

Question: Use Case:

I'm trying to change window.alert to Sweet alert.
When I used window.alert, alert pop-up appeared before file-upload window and then clicked 'OK', file upload window appeared.
But, after changing window.alert to Sweet alert, file-upload window appears simultaneously.

<input id="ScanFile" type="file"/>

When a user clicks the label, Sweet-alert appeared, and then the user can select the file.

uploadAlert() :
$scope.uploadAlert = function() {
        $window.alert(~~~~~~);
}

How to solve this problem?
Comment: is `` show to the user in the UI?
Comment: yes, that is User's view
Comment: i meant is the label that is shown to the user or Choosefile button, or both are visible ?
Comment: just label shown. I hide file input using CSS
Answer:
 <input id="ScanFile" type="file"/>

your uploadAlert() function will be like,
$scope.uploadAlert = function(e) {
    e.preventDefault(); // this will prevent the upload dialog from opening
    swal(); // sweetalert popup
}

now you can programatically click on the <input id="ScanFile" type="file"/> using the id, to open the dialog after closing sweetalert dialog.
 document.getElementById("ScanFile").click();

For example:
 $scope.uploadAlert = function(e) {
    e.preventDefault(); // this will prevent the upload dialog from opening
       swal({
      title: 'Demo',
      text: 'Demo',
      showCancelButton: true,
      confirmButtonText: 'Submit',
      },
      function() {
         document.getElementById("ScanFile").click();
     });
  });
}

Comment: Thanks! But I should use `$event` than `event` in `ng-click`

File upload window after Sweet Alert


Door lock only on one side?

Question: Guests room has 2 doors:

One that opens inside the house, to let those already in the house move to guests room.
One that opens to the outside of the house, to let those outside to get in.

The inside door will have a lock only on the inside.  The guests side will have no key hole, since it is never locked/unlocked from there.  The guests also never need to know if the door is locked, so no need for red/green indicators either.
Question: what are the options for such oneside-locked doors?
I thought of cutting a cylinder/barrel in half to eliminate the key hole on the guests side.  But not sure how it works.
I also thought of using door latches, but these have no locks/keys, which might be useful to limit kids going to guests' room without parents' approval (key).
I also thought of digital locks, but they cost a lot in every aspect:  initial and maintenance costs are too high, and replacement parts are too hard to find for the same lock, as they evolve a lot over time, which may require cutting doors again and again to adapt to size variations.
Comment: Have you looked at an ordinary "privacy door knob?"  This is a door knob that lock from the inside, without a key.
Comment: What about a lever [Mortice lock](https://en.wikipedia.org/wiki/Mortise_lock) without a keyhole drilled on the guests side? The key can be removed to prevent locking if needs be too... EDIT: [like this](https://cdn.aws.toolstation.com/images/141020-UK/800/79242.jpg)
Comment: What is the context, are you renting the room out on AirBnB or is this for known guests? I think most AirBnB guests would try all the doors in a room they were staying so I'm not sure it matters if they see a lock on the door, they know it will be locked. I would use a simple one sided cylinder deadbolt. Or for a cheap and simple solution a slide latch
Comment: And typically also unlock from the outside with a screwdriver - they provide privacy, not security.  this is the sort of lockset typically used on home bathrooms.
Answer: Which side of the pond are you? If in Europe, I would use the so-called "half-cylinder" for the door lock:

and just put some filler plates on the guest room side to cover the holes in the door.

Door lock only on one side?


Wiring a C (common) wire to a Triangle Tube Prestige Excellence 110?

Question: Wiring noob here. Can someone give me step-by-step instructions for where and how I should attach a C (common) wire to a Triangle Tube Prestige Excellence 110 boiler for a ecobee3 thermostat?
I think the gray box on top (pictured below) with the blue, brown, red and white wires is the 24VAC transformer, but I'm not sure.
Also I'm not sure where or how I should connect a C wire.
Answer: Nowhere convenient, and nowhere that is clearly documented but it's a reasonable guess that the white wire connected to terminal X10-7 is the 24V common.  You would have to splice in to it as there does not appear to be anywhere else available to connect to it.  None of the convenient terminals on the orange terminal blocks is 24V Common.
Do some testing first to make sure that pair of white/red wires there is the 24V supply and then to ensure the red one is used as "+" (bearing in mind it's AC).  If so, I'd cut the black cable exactly in half, insert a new terminal block there and add my C wire to it.
Note the other black cable and a lot of the wiring is 120V.  Be cautious.
Answer: I think the 24v terminal is the orange one on the bottom right labeled with the ports 7 to 19. you should be able to confirm this by seeing only small (18 or 20 gauge) wires entering into these ports and a red and white wire in location 7 and 8.
I am installing a Nest thermostat and if I need a Common wire, I will add some comments when I figure this out too! I sent triangle tube a request for this information.
Scott


How to write like statements in Entity Framework when the liked valued contains %

Question: I know that String.Contains('x') would translate to LIKE '%x%', and String.StartsWith('x') and String.EndsWith('x') would translate into LIKE '%x' and LIKE 'x%' respectively. However, I'm now in a situation in which I'm gonna build the LIKE operator regular expression clause in the business layer, and send it to the SQL Server through Entity Framework. I mean, now the end users builds the regular expression through a GUI and we need to retrieve the result based on that. For example, user creates something like [Any Letter][Any Number]ab[Many Characters] and we translate it into [a-zA-Z][0-9]ab%. Now we want to send this to SQL Server using Entity Framework. However, it seems that Entity Framework can't do this, and the query won't get the correct result back.
Any idea how we should implement this requirement?
Comment: possible duplicate of [How do I escape a percentage sign in T-SQL?](http://stackoverflow.com/questions/7191449/how-do-i-escape-a-percentage-sign-in-t-sql) asking just yesterday
Comment: @gbn, that question wants to search for literal `%` sign. My question is to pass percentage sign directly from EF. It's not duplicate.
Answer: Entity framework is able to do this but linq-to-entities are not. You must use Entity SQL and LIKE operator. Some example.
Answer: You can create a Stored procedure and execute it using entity framework.
Comment: Seems the only **easy** way without getting into the trouble of learning a lot of new things. I think Microsoft should really implement the `Like` extension method for String type and translate that into SQL in EF. It would be really nice if developers can do something like `entities.Employees.Where(e => e.LastName.Like(pattern))`.


If $S= \overline {abc}_j$ and $S = \overline{cba}_{j+1}$ with $a, c \neq 0,$ find $S$.

Question: If $j\ge 3$ is a positive integer, and $S= \overline {abc}_j$ and $S = \overline{cba}_{j+1}$ with $a, c \neq 0,$ find all possible $S$.

My progress:
I set up the equation
$$aj^2+bj+c = c(j+1)^2+b(j+1) + a,$$
and simplified it into
$$a(j^2-1) = c(j^2+2j)+b.$$
But I'm not sure how to proceed from here. Any help?
EDIT: It seems as though they only exist for odd $j$ and are of the form $a=\lceil j/2\rceil, b = c =a-1,$ in base $j$. How can I prove these are the only ones? Or, are they even the only ones?
Comment: What is your $g$?
Comment: Sorry, I meant $j$!
Answer: Instead you should write it as a quadratic equation as follows:
$$aj^2+bj+c=c(j+1)^2+b(j+1)+a=cj^2+2cj+c+bj+b+a$$
$$(a-c)j^2-2cj-(b+a)=0$$
Suppose $j^*$ is a positive integer solution to the equation above. By considering the expansion of $(mj+n)(j-j^*)$ (with $m,n \ge 0$), we see that $j^* \mid (b+a)$.
However we must have $0 \le a,b < j^*$. This forces $a+b = j^*$. We now have
$$(a-c){j^*}^2-2cj^*-j^*=j^*((a-c)j^*-2c-1)=0$$
This implies $j^* = \dfrac {2c+1}{a-c}$. Suppose $a-c > 1$. $a-c \ne 2$ since $j^*$ is an integer.
This gives $a-c \ge 3$, and we will have $j^* \le \dfrac {2c+1}3\le \dfrac {2c+c}3=c$, which is a contradiction.
Hence $a-c = 1$ and $a+b = j^* = 2c+1$. (Here it is more obvious that $j^*$ is odd.)
Solving the equations in terms of $j^*$, we have
$$a = \frac {j^*+1}2, b = c = a-1 = \frac {j^*-1}2$$
and finally we check the result for any odd $j^* \ge 3$.
Comment: Thank you so much!  What motivated you to write the quadratic in that form?
Comment: Since we assumed that $j^*$ is a root of our quadratic equation, it must contain the factor $(j-j^*)$. The general result for polynomials is the Rational Root Theorem.
Comment: $(a-c)(j^*)^2-2c(j^*)-(b+a)=0 \Rightarrow j^* | (b+a).$
Comment: Or killing two birds with one stone:
$2j^* > a+b=j^*((a-c)j^*-2c) \Rightarrow j^*=a+b, (a-c)j^*-2c=1$. Anyway, nice proof!


Paypal PHP REST API for payflow

Question: We would like to use Paypal for credit card authorization exactly as we do for Paypal transactions, only skip right to approval for users who do not want paypal.
The REST API for paypal has the setPaymentMethod always set to "paypal" in every example I can find, and I don't find a list of possible values. May this constant be set to something like "payflow"?
The hope is that the REST API would work to allow a credit card customer get payflow dialogs rather than paypal login/guest login. The idea is to try and use our existing REST code to process credit card payflow transactions and retain the "create order" then "capture" processes we have for paypal transactions. I can't tell if the REST API is capable of this.
Answer: Payflow does not work with the REST API in any way. Payflow is very old, and uses a much older NVP API.
If possible, use a more modern solution such as Braintree Direct or Advanced Credit and Debit Cards rather than the old Payflow gateway.
Comment: Thanks very much, that is exactly what I needed to know to put away the false hope. We are looking at Braintree as the solution, but I was trying to reuse if possible. I apologize that I don't have sufficient reputation to vote your answer as the solution.
Comment: Well Advanced Credit and Debit Cards does use the REST API to create and capture orders

Paypal PHP REST API for payflow


How can I add a GFCI receptacle on a circuit with split receptacles?

Question: I have a typically wired living room with all receptacles switchable on the top outlet. We are installing a large fish tank and decided to add GFCI protection. I'm trying to change a single duplex to a GFCI + single duplex. I would like this box for the fish tank to be hot at all times. I tied together the switchable lead in this box so everything downstream is still the same. I fed the hot circuit through the GFCI and jumped to the neighboring duplex. You see where this is going? I didn't until I flipped the light switch. Shared neutral returning current not seen leaving the GFCI. Is there a way around this without pulling wire? Or do I have to live with switchable top outlets in this box?
Comment: Check out [this answer](http://diy.stackexchange.com/a/9332/33) which has a diagram showing how to wire a GFCI in a shared "neutral" situation. Unfortunately, in your situation you won't be able to provide GFCI protection to the other receptacles. Unless of course, you pull an additional wire throughout the rest of the circuit.
Comment: Note that if the switches are the only means of switched lighting in the room at least one will have to stay that way to stay within the NEC.
Answer: Short answer, pigtail the GFCI on both hot and neutral side.  Do not attempt to daisychain any other outlets off the "load" side of the GFCI.


Planar object Homography calculation and Pose Estimation

Question: I'm trying to implement my own Homography and Pose estimation in OpenCV. Suppose I have a square image as a model which I want to locate in input frame from camera.
My question is about how to prepare model data to calculate Homography.
I did the following procedure:
1-I extracted 3 corresponding set in both images.
 Input features:       Model Features:
p1_Input(278,278)---> p1_model(137,273)
p2_Input(317,235)---> p2_model(176,230)
p3_Input(217,204)---> p3_model(76,199)  //all in pixel

2- Solving P3P problem:
a) normalizing input points using camera Intrinsic parameters:
u.x=(p1_Input.x - cx) / fx
u.y=(p1_Input.y - cy) / fy
u.z=1

v.x=(p2_Input.x - cx) / fx
v.y=(p2_Input.y - cy) / fy
v.z=1

w.x=(p3_Input.x - cx) / fx
w.y=(p3_Input.y - cy) / fy
w.z=1

b) normalizing the lenght in order to have a unit vector:
d = sqrt(u.x*u.x + u.y*u.y + 1);
u.x=u.x/d;
u.y=u.y/d;
u.z=u.z/d;  // and same for v and w

c)Finding distance between u and camera focus.(same for v and w) by solving p3p and storing in a,b and c
d)computing 3D coordinates:
A_Input.x=a*u.x;
A_Input.y=a*u.y;
A_Input.z=a*u.z;  // same for B_input and C_Input

like:
A_Input:(-0.0899342 ,0.0570672 ,0.976046)
B_Input:(-0.0197703 ,-0.0194311 ,0.955101)
C_Input:(-0.197233 ,-0.0746457 ,0.967379)

3-Computing Homography
My question is arising here. How should I prepare and modify p1_model,p2_model and p3_model to be prepared for Homography computing?
Obviously  A_Input is 3D vector with normalized date while p1_model is 2D vector in pixel.
After solving the problem the rest would be as follows:
a)finding centeroid point for both set.
b)finding H using this formula dot prodoct
4- finding rigid transform using H and SVD
more detail is available here and here
Comment: you need 4 points to uniquely define a perspective transformation, are you making an affine approximation?
Comment: @Hammer No I used 3points to determine rigid transform rather perspective transform
Comment: I am still a bit confused, do you want a 2d rigid transform or a 3d one?  You can't get a 3d rigid transform unless you have 3d coordinates but it looks like you want to use the rigid transform to find your 3d coordinates (step c).  It seems a bit like pulling yourself up by your bootstraps.
Comment: I'm asking how to prepare 3D coordinate for calculation 6DOF rigid transform. As you can see I assume z=1 for the first set
Answer: As far as coordinate systems go, there is no specific "format" that you need to put your points in to get good results from a P3P (or PnP) algorithm, just be consistent.  The solution the algorithm is looking for given a correspondence between p1 and p2 is
p2 = [resulting_3x4_transform]*p1;

for each correspondence.  It may be advisable for numerical reasons to not have any coordinate values be very large or very small but other than that, feel free to put your points in any coordinate system you like.
Comment: You mean using a pixel format for one set and normalized one for another works?
Comment: no, I mean be consistent between sets.  You can use any Cartesian units you can imagine, just don't expect the transform you get back to work on anything other than the units you put in.
Comment: you could try posting a more specific question.  List the coordinates that go in, which function you are using, and the transform that comes out, along with why you think the transform is wrong.


Preventing Stackoverflow exception using static methods

Question: I was programming a class which recursively instantiates itself in order to parse a XSD into another type of XSD. It downloads it from internet and walks through each element and if one of the elements has a complexType which is located in another URI then it simply does the same thing by creating one of the instance of itself.
But when the XSD is so big and has many external links, today my class crashed because of the Stackoverflow exception.
I decided to put some of the instance methods to another class (Helper.cs) as static members and now call them from within the parser class.
But I wonder if this is a good solution and can solve the Stackoverflow exception? I know how the instance methods are put into the stack frames but Will the static methods be treated in the same way? Will it cause any Stackoverflow exception?
Answer: The only difference between instance methods and static methods is that instance methods take an additional hidden this parameter.  (actually, instance methods can also be virtual, but that doesn't make any difference here)
They are both equally vulnerable to stack overflow.
If you want to avoid stack overflows for large inputs, don't use recursion.
Comment: +1. Recursive code to parse untrusted input is security issue. There is not much to do but refactor to avoid recursion OR have some sort of "deep recursion prevention" counter to fail for excessively nested structures.
Answer: Static vs instance has no bearing on the question. the stack depth rises and falls based on calls, not on actual memory containing a function be it on the stack or the heap.
look for any recursion without a solid exit condition, loops that count to infinity, or datasources that are just plain too big. is your project running on a webserver? IIS has a builtin limit on stack size (compiled into w3wp.exe) that is more restrictive than desktop apps.


Matplotlib / python clickable points

Question: I have a bunch of time series data with points every 5 seconds. So, I can create a line plot and even smooth the data to have a smoother plot. The question is, is there any way in matplotlib or anything in python that will allow me to click on a valid point to do something? So, for example, I would be able to click on (10, 75) if that datum exists in my original data and then I would be able to do something in Python.
Any thoughts? Thanks.
Comment: yes, see the picker demos
Answer: To expand on what @tcaswell said, see the documentation here: http://matplotlib.org/users/event_handling.html
However, you might find a quick demo of pick events useful:
import matplotlib.pyplot as plt

def on_pick(event):
    artist = event.artist
    xmouse, ymouse = event.mouseevent.xdata, event.mouseevent.ydata
    x, y = artist.get_xdata(), artist.get_ydata()
    ind = event.ind
    print 'Artist picked:', event.artist
    print '{} vertices picked'.format(len(ind))
    print 'Pick between vertices {} and {}'.format(min(ind), max(ind)+1)
    print 'x, y of mouse: {:.2f},{:.2f}'.format(xmouse, ymouse)
    print 'Data point:', x[ind[0]], y[ind[0]]
    print

fig, ax = plt.subplots()

tolerance = 10 # points
ax.plot(range(10), 'ro-', picker=tolerance)

fig.canvas.callbacks.connect('pick_event', on_pick)

plt.show()

Exactly how you approach this will depend on what artist you're using (In other words, did you use ax.plot vs. ax.scatter vs. ax.imshow?).
Pick events will have different attributes depending on the artist selected.  There will always be event.artist and event.mouseevent.  Most artists that have individual elements (e.g. Line2Ds, Collections, etc) will have a list of the index of the items selected as event.ind.
If you'd like to draw a polygon and select points inside, see: http://matplotlib.org/examples/event_handling/lasso_demo.html#event-handling-example-code-lasso-demo-py
Answer: If in case you want to bind extra property to your artist object, for example you are plotting IMDB ratings of several movies, and you want to see by clicking on a point which movie it corresponds to, you can do that by adding a custom object to the point that you plotted, like this:
import matplotlib.pyplot as plt

class custom_objects_to_plot:
    def __init__(self, x, y, name):
        self.x = x
        self.y = y
        self.name = name

a = custom_objects_to_plot(10, 20, "a")
b = custom_objects_to_plot(30, 5, "b")
c = custom_objects_to_plot(40, 30, "c")
d = custom_objects_to_plot(120, 10, "d")

def on_pick(event):
    print(event.artist.obj.name)

fig, ax = plt.subplots()
for obj in [a, b, c, d]:
    artist = ax.plot(obj.x, obj.y, 'ro', picker=5)[0]
    artist.obj = obj

fig.canvas.callbacks.connect('pick_event', on_pick)

plt.show()

Now when you click one of the points on the plot, the name property of the corresponding object will be printed.
Comment: I am getting the following error:     x, y = artist.get_xdata(), artist.get_ydata()
AttributeError: 'PathCollection' object has no attribute 'get_xdata'
Answer: With respect to "a bunch of" in the question, I tested whether picking works with twin axes (no), multiple axes (yes), multiple figures (yes):
import numpy as np
from matplotlib.pyplot import subplots

def on_pick(e):
    print(e.artist.s, e.ind)

x = np.linspace(0, np.pi)

fig, ax = subplots(2)
ax[0].plot(x, np.cos(x), picker=5)[0].s = 'cos'
ax[1].plot(x, np.sin(x), picker=5)[0].s = 'sin'
fig.canvas.callbacks.connect('pick_event', on_pick)
fig.tight_layout()
fig.show()

fig, ax0 = subplots()
ax0.plot(x, np.tan(x), picker=5)[0].s = 'tan' # Won't work, masked by ax1.
ax0.set_ylim(-3, 3)
ax1 = ax0.twinx()
ax1.plot(x, np.sqrt(x), picker=5)[0].s = 'sqrt'
fig.canvas.callbacks.connect('pick_event', on_pick)
fig.tight_layout()
fig.show()

Example output:
cos [6]
sin [32]
sqrt [30]

Matplotlib / python clickable points


Kleisli categories of monads on Kleisli categories

Question: In general, the composition of two monadic adjunctions is not necessarily itself monadic. Two known counterexamples include $\mathbf{TorsionFreeAb} \to \mathbf{Ab} \to \mathbf{Set}$ and $\mathbf{Cat} \to \mathbf{Quiver} \to \mathbf{Set} \times \mathbf{Set}$ (the latter is because $\mathbf{Cat}$, the category of small categories, is not regular).
Now, let $C$ be a category with a monad $T$ and $S$ be a monad on the Kleisli category $C_T$. Then, for any two objects $X$ and $Y$ in $C$, morphisms from $X$ to $Y$ in the Kleisli category $(C_T)_S$ correspond to morphisms from $X$ to $SY$ in $C_T$, which in turn correspond to morphisms from $X$ to $TSY$ in $C$. This suggests that $(C_T)_S$ is also the Kleisli category of a monad $\bar{S}$ on $C$ for which $\bar{S}X = TSX$ on objects.
Question:

Does there always actually exist such a monad $\bar{S}$? In other words, is the composition of two Kleisli adjunctions always itself a Kleisli adjunction?
Comment: Related (but doesn't answer) : you can find an answer, not for the Kleisli category but for the Eilenberg-Moore category, with the keywords distributive law - there is for instance an exercise sheet on Samuel Mimram's website about these : http://www.lix.polytechnique.fr/Labo/Samuel.Mimram/teaching/cat/
Answer: Surprisingly to me, yes-there's no need for any distributive laws or anything. If $U:D\leftrightarrows C:F$ is an adjunction, then by Peter Lumsdaine's answer here, our adjunction is equivalent to the Kleisli adjunction of the monad $UF$ if and only if $F$ is essentially surjective, and isomorphic to it if and only if $F$ is bijective on objects. Both these properties are closed under composition of functors.


Align window buttons to the right in GNOME fallback mode?

Question: There have been many a question on how to do it with gconf-editor in < 11.10, but how can I align the window buttons (close, minimize and maximize) to the right in Ubuntu 11.10?
Please close if it's a duplicate. I searched around but couldn't find anything. I'm in the gnome-session-fallback WM.
Answer: The old way does work still, you just have to be more patient with it:
Run (or do whatever you do - you'll need to install gconf2 for this one)
gconftool-2 --set /apps/metacity/general/button_layout \
 --type string "menu:minimize,maximize,close"

Then log out. And log back in again.
Before 11.10 the change was instant but I'm guessing now the settings are loaded out of gconf into something else at login and don't refresh until you've started a new session.
Comment: Thank you ever so much! This brings me one small step closer to being able to put up with 11.10. It's in a VM at the moment.
Comment: Yeah I was a bit worried when I first upgraded. I struggled to get the menus in the right place (but fixed it), I still can't get Cardapio working yet (developer needs to improve it for GTK3) and there's been some weirdness with shortcuts thanks to Compiz/Unity but I'm slowly getting into a position where things are the same as they were in Natty. It's a shame people have to fight so hard just to keep things the way they want them but that's "progress", I guess.
Comment: "progress" indeed. I do like it, but not when it goes in the wrong direction! Thanks for protecting my question - I can see it being visited quite a lot.


How to create a correlation matrix with correlations from one df below the diagonal and from another df above the diagonal?

Question: I have two data sets (i.e. different data frames) containing the same set of variables (measured at two different time points). I would like to create a correlation matrix (all variables correlated with each other) separately for both data sets. I would like to report them in one table showing the correlations from data set 1 below the diagonal and from data set 2 above the diagonal. Is there a special R function that will lead me to this goal (preferably in a way that I can export the full correlation matrix as Excel)?
Many thanks in advance for any hint!
Answer: This correlation matrix sounds rather bespoke, but here's a method you can adapt.
corr2 <- function(x, y) {
  cor1 <- cor(x)
  cor2 <- cor(y)
  cor1[upper.tri(cor1)] <- cor2[upper.tri(cor2)]
  cor1
}
mtsplit <- lapply(split(mtcars[,1:4], seq_len(nrow(mtcars)) %% 2), head, 10)
corr2(mtsplit[[1]], mtsplit[[2]])
#             mpg        cyl       disp         hp
# mpg   1.0000000 -0.8349547 -0.8733379 -0.8880032
# cyl  -0.9015514  1.0000000  0.8980527  0.9160083
# disp -0.8945514  0.8481032  1.0000000  0.9266008
# hp   -0.8793122  0.9683139  0.8962127  1.0000000

If we debug that function and look at each value, we see:
cor1
#             mpg        cyl       disp         hp
# mpg   1.0000000 -0.9015514 -0.8945514 -0.8793122
# cyl  -0.9015514  1.0000000  0.8481032  0.9683139
# disp -0.8945514  0.8481032  1.0000000  0.8962127
# hp   -0.8793122  0.9683139  0.8962127  1.0000000
cor2
#             mpg        cyl       disp         hp
# mpg   1.0000000 -0.8349547 -0.8733379 -0.8880032
# cyl  -0.8349547  1.0000000  0.8980527  0.9160083
# disp -0.8733379  0.8980527  1.0000000  0.9266008
# hp   -0.8880032  0.9160083  0.9266008  1.0000000

(And since it's a matrix, it can be written to a CSV file with write.csv, i.e., Excel-friendly.)


Why did my Canon or Epson printer stop working after a recent update on 12.04?

Question: I have a Canon (or Epson) printer and use Ubuntu 12.04. It looks like my printer has partially stopped working after a recent update -- only half of the last page is printed out (sometimes this happens with all pages).
Is there a way to fix it?
Answer: This problem was a known bug with Ubuntu's printing subsystem (CUPS), introduced by a recent update towards the end of July.
It has now been fixed (as of August 7, 2012).
The fixed version should be installed as part of your regular Update Manager process within the next few days; if you would like to fix it now, please do the following:

Open a terminal with Ctrl+Alt+T.
Select and copy the below with Ctrl+C, and paste it in the terminal window by right-clicking inside it and then clicking on Paste:
sudo apt-get update && sudo apt-get install cups
Enter your password when asked.
This should fix the problem (a reboot may be needed for some). If you have this printing problem but get the message cups is already the newest version. when you try the above, please wait a few hours and try again - the updated version may not have made it to your local Ubuntu update server (mirror).
Comment: [I have exactly the same problem](http://askubuntu.com/q/476320/148451) on 14.04, but this solution didn't work for me. Any ideas...?
Comment: didnt work for me


Add Spinner Hint that has data from json

Question: i populate spinner from json data, I want to set  hint so that user can under stand what has to be selected since when there is no internet connection spinner show no sign of what to be selected.Some answer have suggested to use prompt
<code> <Spinner
    android:layout_width="match_parent"
    android:id="@+id/spinner"
    android:prompt="@string/country_prompt"
    />
</code>
and other suggested the use of the use of last index of spinner as hint like here.How can i set something like hint or related to so that user can understand what spinner is all about even the moment app is off line. Below is my code snipe from  here
<code>    @Override
    protected Void doInBackground(Void... params) {
        // Locate the WorldPopulation Class
        world = new ArrayList<WorldPopulation>();
        // Create an array to populate the spinner
        worldlist = new ArrayList<String>();
        // JSON file URL address
        jsonobject = JSONfunctions
                .getJSONfromURL("http://www.androidbegin.com/tutorial/jsonparsetutorial.txt");

        try {
            // Locate the NodeList name
            jsonarray = jsonobject.getJSONArray("worldpopulation");
            for (int i = 0; i < jsonarray.length(); i++) {
                jsonobject = jsonarray.getJSONObject(i);

                WorldPopulation worldpop = new WorldPopulation();

                worldpop.setRank(jsonobject.optString("rank"));
                worldpop.setCountry(jsonobject.optString("country"));
                worldpop.setPopulation(jsonobject.optString("population"));
                worldpop.setFlag(jsonobject.optString("flag"));
                world.add(worldpop);

                // Populate spinner with country names
                worldlist.add(jsonobject.optString("country"));

            }
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void args) {
        // Locate the spinner in activity_main.xml
        Spinner mySpinner = (Spinner) findViewById(R.id.my_spinner);

        // Spinner adapter
        mySpinner
                .setAdapter(new ArrayAdapter<String>(MainActivity.this,
                        android.R.layout.simple_spinner_dropdown_item,
                        worldlist));

        // Spinner on item click listener
        mySpinner
                .setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

                    @Override
                    public void onItemSelected(AdapterView<?> arg0,
                            View arg1, int position, long arg3) {
                        // TODO Auto-generated method stub
                        // Locate the textviews in activity_main.xml
                        TextView txtrank = (TextView) findViewById(R.id.rank);
                        TextView txtcountry = (TextView) findViewById(R.id.country);
                        TextView txtpopulation = (TextView) findViewById(R.id.population);

                        // Set the text followed by the position
                        txtrank.setText("Rank : "
                                + world.get(position).getRank());
                        txtcountry.setText("Country : "
                                + world.get(position).getCountry());
                        txtpopulation.setText("Population : "
                                + world.get(position).getPopulation());
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> arg0) {
                        // TODO Auto-generated method stub
                    }
                });
    }
}
</code>
Answer: Add your hind in ArrayList 0 index first it will be get displayed:
<code>    worldlist = new ArrayList<String>();
    worldlist.add("Your first hint");
</code>
For last hint add after for loop your hint:
<code>try{
    for(......){

  }
  worldlist.add("Your last hint");
 }catch(Exception e){ }
</code>
Answer: <code>@Override
protected void onPostExecute(Void args) {
    // Locate the spinner in activity_main.xml
    Spinner mySpinner = (Spinner) findViewById(R.id.my_spinner);

//add a check if worldlist is empty. Initialize it where you have declared it.
if(!worldlist.size() > 0){
    worldlist.add("select country");
}

// Spinner adapter
mySpinner.setAdapter(new ArrayAdapter<String>(MainActivity.this,
        android.R.layout.simple_spinner_dropdown_item, worldlist));

//your rest of the code here. . .
</code>
}
Answer: try this
<code>    @Override
        protected Void doInBackground(Void... params) {
            // Locate the WorldPopulation Class
            world = new ArrayList<WorldPopulation>();
            // Create an array to populate the spinner
            worldlist = new ArrayList<String>();
            worldlist.add("Selct Country");
            // JSON file URL address
            jsonobject = JSONfunctions
                    .getJSONfromURL("http://www.androidbegin.com/tutorial/jsonparsetutorial.txt");

            try {
                // Locate the NodeList name
                jsonarray = jsonobject.getJSONArray("worldpopulation");
                for (int i = 0; i < jsonarray.length(); i++) {
                    jsonobject = jsonarray.getJSONObject(i);

                    WorldPopulation worldpop = new WorldPopulation();

                    worldpop.setRank(jsonobject.optString("rank"));
                    worldpop.setCountry(jsonobject.optString("country"));
                    worldpop.setPopulation(jsonobject.optString("population"));
                    worldpop.setFlag(jsonobject.optString("flag"));
                    world.add(worldpop);

                    // Populate spinner with country names
                    worldlist.add(jsonobject.optString("country"));

                }
            } catch (Exception e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return null;
        }

@Override
    protected void onPostExecute(Void args) {
        // Locate the spinner in activity_main.xml
        Spinner mySpinner = (Spinner) findViewById(R.id.my_spinner);

        // Spinner adapter
        mySpinner
                .setAdapter(new ArrayAdapter<String>(MainActivity.this,
                        android.R.layout.simple_spinner_dropdown_item,
                        worldlist));

        // Spinner on item click listener
        mySpinner
                .setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

                    @Override
                    public void onItemSelected(AdapterView<?> arg0,
                            View arg1, int position, long arg3) {
                        // TODO Auto-generated method stub
                        // Locate the textviews in activity_main.xml
                        if(position > 0){
                        TextView txtrank = (TextView) findViewById(R.id.rank);
                        TextView txtcountry = (TextView) findViewById(R.id.country);
                        TextView txtpopulation = (TextView) findViewById(R.id.population);

                        // Set the text followed by the position
                        txtrank.setText("Rank : "
                                + world.get(position).getRank());
                        txtcountry.setText("Country : "
                                + world.get(position).getCountry());
                        txtpopulation.setText("Population : "
                                + world.get(position).getPopulation());
                            }
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> arg0) {
                        // TODO Auto-generated method stub
                    }
                });
    }
}
</code>
Answer: update with this code,add your hint on arrays 0 posotion.
<code>@Override
    protected Void doInBackground(Void... params) {
        // Locate the WorldPopulation Class
        world = new ArrayList<WorldPopulation>();
        // Create an array to populate the spinner
        worldlist = new ArrayList<String>();
        worldlist.add(0,"your hint");
        // JSON file URL address
        jsonobject = JSONfunctions
                .getJSONfromURL("http://www.androidbegin.com/tutorial/jsonparsetutorial.txt");

        try {
            // Locate the NodeList name
            jsonarray = jsonobject.getJSONArray("worldpopulation");
            for (int i = 0; i < jsonarray.length(); i++) {
                jsonobject = jsonarray.getJSONObject(i);

                WorldPopulation worldpop = new WorldPopulation();

                worldpop.setRank(jsonobject.optString("rank"));
                worldpop.setCountry(jsonobject.optString("country"));
                worldpop.setPopulation(jsonobject.optString("population"));
                worldpop.setFlag(jsonobject.optString("flag"));
                world.add(worldpop);

                // Populate spinner with country names
                worldlist.add(jsonobject.optString("country"));

            }
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void args) {
        // Locate the spinner in activity_main.xml
        Spinner mySpinner = (Spinner) findViewById(R.id.my_spinner);

        // Spinner adapter
        mySpinner
                .setAdapter(new ArrayAdapter<String>(MainActivity.this,
                        android.R.layout.simple_spinner_dropdown_item,
                        worldlist));

        // Spinner on item click listener
        mySpinner
                .setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

                    @Override
                    public void onItemSelected(AdapterView<?> arg0,
                            View arg1, int position, long arg3) {
                        // TODO Auto-generated method stub
                        // Locate the textviews in activity_main.xml
                        TextView txtrank = (TextView) findViewById(R.id.rank);
                        TextView txtcountry = (TextView) findViewById(R.id.country);
                        TextView txtpopulation = (TextView) findViewById(R.id.population);

                        // Set the text followed by the position
                        txtrank.setText("Rank : "
                                + world.get(position).getRank());
                        txtcountry.setText("Country : "
                                + world.get(position).getCountry());
                        txtpopulation.setText("Population : "
                                + world.get(position).getPopulation());
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> arg0) {
                        // TODO Auto-generated method stub
                    }
                });
    }
}
</code>


How many save files can you have in The Legend Of Zelda: Spirit Tracks?

Question: I am debating whether or not to buy Spirit Tracks for Christmas, but it depends on if you can have multiple save files on the same DS. My sister wants to play it, too, so I probably won't buy it if I can not have separate save files.
How many save files can you have in The Legend of Zelda: Spirit Tracks?
Answer: Spirit Tracks has two save slots, just like Phantom Hourglass does.
Comment: Which reminds me, I need to continue my current game of Spirit Tracks.  I got sidetracked by Tri Force Heroes and never finished it.


Relax void * casting in C++

Question: In C, it's not an error to cast pointers to and from void *.
A major obstacle in porting to C++ is the need to cast pointers when returning from functions dealing with generic pointers such as malloc, and functions declared in my own code such as void *block_get(Blkno const blkno);.
My code however is intended to be compiled by C and C++ compilers successfully. If I provide explicit casts everywhere for the sake of C++, they must be C-style casts and I may be masking bugs due to casting non-pointer types to and from pointer types from both languages.
My reference error is the following:
struct Cpfs *cpfs = calloc(1, sizeof(*cpfs));

which in MSVC produces:

Error  2   error C2440: 'initializing' : cannot convert from 'void *' to 'Cpfs *'  e:\src\cpfs\cpfs.c  179

Evidently I can't use new or static_cast which I'd naturally use if I was no longer using C. What's the best way to provide maximum type safety surrounding void *for each language with minimal verbosity?
Comment: Why do you need to port to the common subset of C and C++? As you've discovered it severely limits what C (alternatively what C++) you can use. Almost all environments that have C++ available also have C available and also allow you to link C++ and C object files together. I can't see what gain you get by porting to the common subset.
Comment: I'd like to know the rationale for trying to write a program that compiles for two different languages. That's typically something left for puzzles.
Comment: 9 times out of 10, `static inline` in header files is bogus premature optimization.
Comment: For *type safety in C* (which is a bit hard), make a function for each struct whose job is to allocate and return a pointer to a new struct. Likewise, make a function for freeing the struct.
Comment: BTW, in C++, you should be using `static_cast` to cast to/from `void*`.
Comment: @GMan: the times I've done it have always been `static inline` (or implementation-defined equivalent, in the case of C89) functions in headers relating to a library mostly written in C, but used by both. When things get too hairy trying to work in the intersection, you can give up on that function being `static inline`, and just write it in C.
Comment: @R. Fortunately, I've only done it 10% of the time, and I know my code base better than you do.
Comment: possible duplicate of [When convert a void pointer to a specific type pointer, which casting symbol is better, static\_cast or reinterpret\_cast?](http://stackoverflow.com/questions/5013596/when-convert-a-void-pointer-to-a-specific-type-pointer-which-casting-symbol-is)
Answer: I'd suggest either simply using C style casts, or wrapping the cast in a macro that either expands to nothing (in C), or a static_cast in C++.
Comment: A `reinterpret_cast` from `void*` is not the best cast. `static_cast` is sufficient and less likely to silently cast an invalid source to a pointer type.
Answer: If your compiler supports decltype(), you can use some macro magic to avoid having to explicitly repeat the type name (and, thanks to sizeof, the element size):
#ifdef __cplusplus
#define my_calloc(VAR, COUNT) \
    static_cast<decltype(VAR)>(std::calloc(COUNT, sizeof *VAR))
#else
#define my_calloc(VAR, COUNT) calloc(COUNT, sizeof *VAR)
#endif

Example usage:
#ifdef __cplusplus
#include <cstdlib>
#else
#include <stdlib.h>
#endif

struct Cpfs *cpfs = my_calloc(cpfs, 42);

The cleaner solution would probably be to just use a C compiler and link the object files, though...
Comment: @Matt: you could use MinGW to compile the C part of your project and still use MSVC for the C++ part (see eg http://stackoverflow.com/questions/2096519/from-mingw-static-library-a-to-visual-studio-static-library-lib )
Comment: decltype looks similar to typeof, using a c compiler isn't an option, msvc has no c99 support. c++ compiles it better than a half-assed c compiler
Comment: @Matt Joiner: programming to the intersection of C99 and C++ isn't substantially different from just programming C89, it's just more awkward and annoying. You're writing to a half-assed version of C as it is, using a half-assed C compiler isn't any worse, and at least C89's a standard.
Answer: make a replacement allocator function that you can define differently for C and C++ builds :- Something like this in a header file:
#ifdef __cplusplus
template<typename TypeT>
TypeT* MyAlloc(TypeT** pOut,size_t cb){
  *pOut = static_cast<TypeT*>(malloc(cb)); //aint c++ pretty.
  return *pOut;
}
#else
  extern void* MyAlloc(void** ppv, size_t cb);
#endif

Now you have, in c++ builds, a function that can infer the type of thing its dealing with, and in C builds, its a regular function that returns a void*.
The only problem is the need to pass in the pointer to allocate - the c++ compiler wont try to deduce a template parameter based only on the return type of a function afaik. So you could call it agnostically like this :-
int *p;
if(MyAlloc(&p,sizeof(int)*n)){
  ...

Comment: @Chris: Uh, yeah. That's not even a new idea, it's relatively old. (As in, we've been in a "modern C++" era, where you don't manage your resources manually. Wrap them up (`std::vector`, `shared_ptr`, etc.); it's scope-bound resource management (SBRM) more known as it's ugly name RAII) Any time you have to manually free something, you've done something wrong. Again, this tangent is a red-herring. The code you said was ugly in your post is only ugly because it's not idiomatic C++, replying with some *other* code is irrelevant.
Comment: `new` is even worse as c++ compilers dont deduce class template parameters from the constructor call. So I had to write something like this the other day: `SomeClass* pWrapper = new SomeOtherClass(this,&SomeOtherClass::method);`
Comment: @Chris: You're using `new` without putting it in a wrapper, your point is moot to me. C++0x has `auto`, and your response is a red-herring anyway.
Comment: "//aint c++ pretty." Yeah, when you use `new`.
Comment: Its now a best practice to always bundle calls to new in a wrapper? `auto` only solves half the problem. and new is no more pretty than malloc() especially if the recommended way to avoid the ugliness is to wrap it.
Answer: The only solution I know is to do explicit casting:
struct Cpfs *cpfs = (Cpfs*)calloc(1, sizeof(*cpfs));

Here both compilers are satisfied.
Also that remember, that for older compilers malloc may return char*.
hth
Mario
Answer: Maybe something like this? (untested, no compiler available, not using macros very often):
#ifdef __cplusplus
    #define pointer_cast(type, pointer) reinterpret_cast<type>(pointer)
#else
    #define pointer_cast(type, pointer) (type)(pointer)
#endif

Comment: Why not just avoid the useless cast entirely when `__cplusplus` is not defined?
Comment: I ended up creating a VOID_CAST macro that cast only when necessary.

Relax void * casting in C++


java bytecode optimization, how to handle exception

Question: Consider the following Java class with no concurrent access.
class C{
 int x;
 public void m1(int y){
  this.x = y;
  m2(y);
 }
 public void m2(int y){
  System.out.println("m2"); <- or anything else that does not affect this.x
 }
}

+edit
Since m1() has only read-read relation on y, Can jit compiler optimize m1() by changing the order of execution to the following? does it break the java model consistency?
-edit
 public void m1(int y){
  m2(y);
  this.x = y;
 }

in case m1() can be optimized, what if m2() throws an exception in the optimized code, is the affectation still be executed?
I didn't understand the javase7 specs, what happens in such scenario?
oracle.com/javase/specs/jvms/se7

A Java Virtual Machine may permit a small but bounded amount of execution to occur before an asynchronous exception is thrown. This delay is permitted to allow optimized code to detect and throw these exceptions at points where it is practical to handle them while obeying the semantics of the Java programming language.
  [...]
  Exceptions thrown by the Java Virtual Machine are precise: when the
  transfer of control takes place, all effects of the instructions
  executed before the point from which the exception is thrown must
  appear to have taken place. No instructions that occur after the point
  from which the exception is thrown may appear to have been evaluated.
  If optimized code has speculatively executed some of the instructions
  which follow the point at which the exception occurs, such code must
  be prepared to hide this speculative execution from the user-visible
  state of the program

I understood the roll back behavior, but I didn't understand what will happen to the "not executed" instructions. technically the affectation was not "executed" because of the optimization, does this mean that it won't be executed ever?
Comment: @user The JIT is not allowed to break code, except within the restrictions described in the memory model. The spec doesn't explicitly list everything the VM can't do because that would be infinite.
Comment: What optimization are you talking about? You do realize that you are working with primitives, right?
Comment: @MuratK. I fully understand that, but the jit compiler can always optimize the bytecode: it can change the order of execution of instructions
Comment: The JIT can not *always* reorder bytecode, there are restrictions related to volatile fields, synchronized blocks and the cited exception guarantees. If speculatively executed code would throw an exception, that exception would need to be held pending and only be actually thrown when the execution flow reaches a point where the throwing instruction is no longer speculative. If a control flow change occured before that, the pending exception would need to be rolled back as well.
Comment: @Durandal I agree with you, at least that's the logical way things should be executed, unfortunately nothing is mentioned in oracle's docs, but on the other side it could be the developer's fault as well and jit allows itself to break the code, the developer didn't use the try,catch,finally block or for not passing this.x to m2() instead of y. that way he will force JIT to affect this.x before passing it to m2() since write comes before read so JIT can't flip the order of execution (the last one is documented in the jdk7 specs).
Answer: You are throwing together two concepts whose only thing, they have in common, is that you didn't understood them.
Reordering is an optimization that is in no way allowed to modify the outcome of a code execution. It is therefore obsolete to ask questions like "is the JVM allowed to reorder this code in a way that it breaks it?". Of course not. The only thing that is possible, is that the result may appear to materialize in a different order to a different thread, in the absence of proper synchronization.
Besides, you should ask yourself why you think
public void m1(int y){
    m2(y);
    this.x = y;
}

is an optimization over
public void m1(int y){
    this.x = y;
    m2(y);
}

What's the improvement?
The other thing you have picked from the specification are asynchronous exceptions, a special thing that only applies to two scenarios:

– The stop method of class Thread or ThreadGroup was invoked, or
– An internal error occurred in the Java Virtual Machine implementation

These are obviously very special conditions and it should be obvious that optimized code should not be required to constantly poll for these conditions. The cited paragraph describes the circumstances under which such an exception could be delayed, but it should be clear that these restrictions do not lift the other existing restrictions, i.e. that optimizations may not alter the result of an execution.

In other words, it's pointless to look at isolated instructions and think, a JVM has nothing better to do than shuffling them around. The general rule of optimizations is that they must not change the observable effect and we can't tell what is observable in your application from that isolated snippet. E.g. if the variable x is never read, it might be that it will never written at all. It might be even the case that the instance of C which holds the variable x is never created, as it is not needed for producing the side effect of printing that message. It's all about changes you won't notice…
Comment: thank you for your reply, sorry I couldn't come up with a more meaningful example. I totally understand the general rule of optimization you mentioned, but unfortunately there are couple of exceptions documented, RAV optimization and [John Regehr](http://blog.regehr.org/archives/161) I was just wondering if this case can be another exception as well since nothing is documented about the java optimization process.
Comment: You can find a lot of papers regarding optimizations used in specific JVMs, e.g. OpenJDK/Oracle in the internet. However, there is no standard optimization process as each implementation is free to optimize in which way it likes as long as the semantics as specified in the JVM are maintained. The article from John Regehr already explains that Java differs from C/C++ regarding non-termination handling and you can generalize this to "Java has no '*undefined behavior*' at all". Even in the case of data races, threads will never read "out of thin air" values (besides possible word tearing).


How can I download an entire website?

Question: I want to download a whole website (with sub-sites). Is there any tool for that?
Comment: what exactly are you trying to achieve? the title and the content of your question are not related, and the content is not specific.
Comment: N.B., only following links (e.g., using `--convert-links` in wget) will not reveal sites that are only revealed by submitting a form, among other things.
Answer: Try example 10 from here:
wget --mirror -p --convert-links -P ./LOCAL-DIR WEBSITE-URL

–mirror : turn on options suitable
for mirroring.
-p : download all files that are necessary to properly display a given
HTML page.
--convert-links : after the
download, convert the links in
document for local viewing.
-P ./LOCAL-DIR : save all the files and directories to the specified
directory.
Comment: You might consider using the `--wait=seconds` argument if you want to be more friendly to the site ; it will wait the specified number of seconds between retrievals.
Comment: Also `--no-parent` to "never ascend to the parent directory" taken from [here](https://superuser.com/a/487206/372305).
Comment: Gotta love stackoverflow's oneliner accepted answers <3
Comment: is there any way to download only certain pages (for instance, several parts of an articles that is spread over several html documents)?
Comment: @Private Yes, although it's probably easier to use python or something to get the pages (depending on the layout/url). If the url of the pages differs by a constantly growing number or you have a list of the pages, you could probably use wget in a bash script.
Comment: the above works, but for joomla the parameterized url creates files that are not linked locally.
The one worked for me is wget -m -k -K -E http://your.domain.com
from here: https://vaasa.hacklab.fi/2013/11/28/howto-make-a-static-copy-of-joomla-site-with-wget/
Answer:
httrack is the tool you are looking for.

HTTrack allows you to download a World Wide Web site from the Internet to a local directory, building recursively all directories, getting HTML, images, and other files from the server to your computer. HTTrack arranges the original site's relative link-structure.
Answer: With wget you can download an entire website, you should use -r switch for a recursive download. For example,
wget -r http://www.google.com

Answer: WEBHTTRACK WEBSITE COPIER is a handy tool to download a whole website onto your hard disk for offline browsing. Launch ubuntu software center and type "webhttrack website copier" without the quotes into the search box. select and download it from the software center onto your system. start the webHTTrack from either the laucher or the start menu, from there you can begin enjoying this great tool for your site downloads
Answer: I don't know about sub domains, i.e, sub-sites, but wget can be used to grab a complete site. Take a look at the this superuser question.
It says that you can use -D domain1.com,domain2.com to download different domains in single script. I think you can use that option to download sub-domains i.e -D site1.somesite.com,site2.somesite.com
Answer: I use Burp - the spider tool is much more intelligent than wget, and can be configured to avoid sections if necessary. The Burp Suite itself is a powerful set of tools to aid in testing, but the spider tool is very effective.
Comment: Isn't Burp Windows Only? The closed-source licence agreement for Burp is also quite heavy. Not to mention the price tag $299.00:
Comment: @KatAmsterdam Regarding specifically the compatibility question: [According to Wikipedia](http://en.wikipedia.org/wiki/Burp_suite), Burp Suite is a Java application, so it *should* run fine on Ubuntu.
Comment: from the licence:
WARNING: BURP SUITE FREE EDITION IS DESIGNED TO TEST FOR SECURITY FLAWS AND CAN DO DAMAGE TO TARGET SYSTEMS DUE TO THE NATURE OF ITS FUNCTIONALITY. TESTING FOR SECURITY FLAWS INHERENTLY INVOLVES INTERACTING WITH TARGETS IN NON-STANDARD WAYS WHICH CAN CAUSE PROBLEMS IN SOME VULNERABLE TARGETS. YOU MUST TAKE DUE CARE WHEN USING THE SOFTWARE, YOU MUST READ ALL DOCUMENTATION BEFORE USE, YOU SHOULD BACK UP TARGET SYSTEMS BEFORE USE AND YOU SHOULD NOT USE THE SOFTWARE ON PRODUCTION SYSTEMS OR OTHER SYSTEMS FOR WHICH THE RISK OF DAMAGE IS NOT ACCEPTED BY YOU.
Comment: For what it does, the price tag is amazingly cheap - I would recommend buying it for a wide range of security testing. And it is very easy to configure it to test exactly as you want - safer than AppScan in some instances:-)
Comment: Kat - it runs just fine on various flavours of Linux. The warning on the licence is the same as any tool you can use for security assessments.
Answer: You can download Entire Website
Command :
wget -r -l 0 website

Example :
wget -r -l 0 http://google.com

Comment: Can you please explain how this command works? What it does?
Comment: @KazWolfe `-r` turns on recursive retrieving with a default depth of 5 levels. `-l` specifies the maximum recursion depth which is in this example 0.
Answer: If speed is a concern (and the server's wellbeing is not), you can try puf, which works like wget but can download several pages in parallel. It is, however, not a finished product, not maintained and horribly undocumented. Still, for to download a web site with lots and lots of smallish files, this might be a good option.

How can I download an entire website?


help with interfaces and abstract classes

Question: I'm recently getting a bit confused with interfaces and abstract classes and I feel I dont fully grasp it like I thought I did. I think I'm using them incorrectly. I'll describe what I'm doing at the moment, the problem I have faced, and then hopefully it be clear what I'm doing wrong if anything.
I wanted to write some classes that do some parsing of xml. I have different user types that have different parsing requirements.
My logic went as follows.
All parsers share a "parse" function in common and must have at least this function so I made an Interface with this function defined named IParse;
I start out with 2 user types, user type A and user type B. User type A & B share some basic functions but user type B has slightly more functions than A so I put the functions to parse what they share in an abstract class that both will extend called "ParseBase".
So now I have
// Interface

    public interface IParser
     {
      function parse(xml:XML):void;
     }

// Base Class

public class ParseBase()

{
  public function getbasicdata():void{}

public function getmorebasicdata():void{}

}

//User type A

public class userTypeA extends ParseBase implement IParse

{
    public function parse(xml:XML):void
{
       getbasicdata()

       getmorebasicdata()

}

}

//user type B

public class userTypeB extends ParseBase implement IParse

{
    public function parse(xml:XML):void
{
       getbasicdata()

       getmorebasicdata()

}

   public function extraFunctionForB():void
{

}

  public function anotherExtraFunctionForB():void
{

}

}

The problem I have come up against now which leads me believe that I'm doing something wrong is as follows.
Lets say I want to add another function UserTypeB. I go and write a new public function in that class. Then In my implementation I use a switch to check what Usertype to create.
Var userParser:IParser

if(a)

{
userParser= new userTypeA();
}else if(b)

{
userParser= new userTypeB();
}

If i then try to access that new function I can't see it in my code hinting. The only function names I see are the functions defined in the interface.
What am I doing wrong?
Answer: You declare the new function only in userTypeB, not in IParser. Thus it is not visible via IParser's interface. Since userParser is declared as an IParser, you can't directly access userTypeB's functions via it - you need to either downcast it to userTypeB, or add the new function to IParser to achieve that.
Of course, adding a function to IParser only makes sense if that function is meaningful for all parsers, not only for userTypeB. This is a design question, which IMO can't be reasonably answered without knowing a lot more about your app. One thing you can do though, is to unite IParser and BaseParser - IMO you don't need both. You can simply define the public interface and some default implementation in a single abstract class.
Oher than that, this has nothing to do with abstract classes - consider rephrasing the title. Btw in the code you show, ParseBase does not seem to be abstract.
Comment: @dubbeat, I see. Never used AS3 myself, but it seems that at least it has (some) access qualifiers. So lacking `abstract`, you could make the BaseParser constructor(s) `protected` to achieve the same effect.
Comment: I thought an abstract class can be just one that defines functionality but is never directly instansiated?
Comment: @dubbeat, a tad more precisely, an abstract class is one that _can not be_ instantiated. You don't tell what language the example is in - to me it looks like Java or C# as well. Java has the `abstract` keyword, and I believe C# too - you should use it :-)
Comment: Ah Sorry. Its actually AS3. I think its the only language that doesnt have an "Abstract" Keyword. My Bad... i should of said
Comment: I get what an interface is for but I just don't know how to use them properly. I think I'll rid my self of the interface and just extend a base class instead
Answer: In order to access functions for a specific sub-type (UserTypeB, for example) you need the variable to be of that type (requires explicit casting).
The use of interfaces and abstract classes is useful when you only require the methods defined in the interface. If you build the interface correctly, this should be most of the time.
Comment: In your opinion do you think I should be even using a interface for my purpose?

How could I achieve explicit casting in the part of my code where I check for user type A or B?
Answer: As Peter Torok says (+1), the IParser declares just one function parse(xml). When you create a variable userParser of type IParser, you will be allowed to call ony the parse() method. In order to call a function defined in the subtype, you will have to explicitly cast it into that subtype.
In that case IMO your should rethink the way you have designed your parsers, an example would be to put a declaration in your IParser (Good if you make this abstract and have common base functionality in here) that allow subtypes (parsers) to do some customization before and after parsing.
You can also have a separate BaseParser abstract type that implemnts the IParser interface.
Comment: What exactly do you mean by "put a declaration" in IParser
Comment: Define additional method(s) that you think are absolutely needed by "most" subtypes.


Two instances of application and dll it loads

Question: I have an executable(VC++) which is run twice with different command line parameters, so basically there are two instances running. This executable loads an C# dll ,First thing i want to know is if two instances of the dll will be loaded to two different instances. If yes then I have a static class in the dll, how will this be instantiated i.e., will there be two instances of static class or will it be shared between the two process.
When i try to run the two instances of the executable, only one instance is successful in loading the dll.
Answer: Process is loaded in its own AppDomain and nothing is shared among them even the DLLs are loaded in respective AppDomain. So there would be two separate instances of your static class in each process. Secondly, DLL is loaded in a host process. If you have Private DLL, then they are loaded separately in the process no sharing whatsoever.
The process space will be different so, for example, global variables in the DLL will be specific to each separate process. It is possible that the code in memory will be shared (Windows typically uses reference counting to make that part more efficient).


Is there any equivalent of na.rm in Python

Question: In R we can use na.rm=True so that our function will exclude na values.
What is the equivalent in the case of Python?
There is a column in my dataset called Route which has information about where the flight stopped like this 'BOM → GOI → PNQ → HYD'
The data is in string format, but this column has some nan. I have created a function to extract the in-between airports.
train['In_Between_Stops'] = train.apply(lambda x: x.Route.split('→')[1:-1],axis=1)
but this is not working as there is nan and this is the error it is showing
AttributeError: ("'float' object has no attribute 'split'", 'occurred at index 9039')
The output I want is to make a new column In_Between_Stops which have the in-between Airports like ['GOI','PNQ'].
Comment: For anyone who happes to know Python but not R, some more explation of what what should be excluded from exactly would lead you to an answer sooner.
Comment: i think it has nothing to do with R. The problem lies with splitting the string correctly inside pandas. Could you explain what exactly is the intended output?
Comment: @StupidWolf my code is getting me the output I want. I have tried it on an element of the column Route. The problem is that there are missing values present in this column which causing a problem.
Comment: hmmm you wrote "but this is not working as there is nan and this is the error it is showing".. how are we supposed to interpret this?
Comment: @StupidWolf The error is showing at index 9039 and I have seen the Route is nan there
Answer: I'm assuming you're using pandas if you're looking for some equivalents to R functions. DataFrame objects in Pandas will have methods which often have a skipna argument (like for instance the .mean() method). You can also remove NA values from the dataframe with .dropna().


Can I create an application in Mono for Android with Arduino?

Question: Is it possible to create an application with Mono for Android and control Arduino without using Eclipse but using Visual Studio and C#?
I checked some examples but everyone uses Java and Eclipse.
Answer: Simply put, the answer is yes, it is possible. The real question is: How? I'm going to assume you've already written you first Android app with Mono.
Next, you need to decide how you will connect your Android device to the Arduino. Bluetooth? Wi-Fi? Web?
Next, it's simply a matter of using the appropriate Android API. Check out the Xamarin documentation for Android.
Update
Much more than what I present below is available with the ported MonoDroid sample applications. Specifically, you would be interested in the BluetoothChat example.
Make sure you also take a look at adding permissions to the manifest file, and of course, the Android Developer Guide for Bluetooth.
That said, here's a tiny something to get you started, based on Android Quick Look: BluetoothAdapter:
<code>txtStatus.Text = "Getting Bluetooth adapter...";
BluetoothAdapter bluetooth = BluetoothAdapter.DefaultAdapter;
if( bluetooth == null )
{
    txtStatus.Text = "No Bluetooth adapter found.";
    return;
}

txtStatus.Text = "Checking Bluetooth status...";
if (!bluetooth.IsEnabled )
{
    Toast.MakeText(this, "Bluetooth not enabled. Enabling...",
        ToastLength.Short).Show();
    bluetooth.Enable();
}

if (bluetooth.State == State.On)
{
    txtStatus.Text =
        "State: " + bluetooth.State + System.Environment.NewLine +
        "Address: " + bluetooth.Address + System.Environment.NewLine +
        "Name: " + bluetooth.Name + System.Environment.NewLine;
}
else
{
    txtStatus.Text = "State: " + bluetooth.State;
}
</code>
Comment: thank you fro the answer. Yeah i already working an application in mono with data transfer with a server. i prefer to connect with bluetooth...i checked the classes  and i noticed [Android.Bluetooth](http://androidapi.xamarin.com/index.aspx?link=root%3a%2fMonoAndroid-lib) class(i dont know if  i need another classes for my connection yet  . but my "fear" is  created because i cant find any example in google. thats why i am asking if you ever tried and worked a project with mono +arduino
Comment: I know this isn't what you're looking for, but perhaps you might want to look into how to use the Android APIs (Java), and what the equivalent code would be in C#. I can post example code in a few hours, if you'd like. Have you used Bluetooth with Arduino yet?
Comment: didnt try it yet. i already control it as .exe(windows form application) and manually with LCD screen on it , and my next step is to control it with bluetooth honestly. but because i am using C# already to create the connection , i wonder if i can do the same as android application with mono droid..(so any  example  it would be really usefull). thank you in advance
Comment: It depends on how well you separated the control and connection code in your previous C# application. Once you have the Bluetooth connection set up, it boils down to sending and receiving bytes, just like a serial connection from PC to Arduino. What bytes you send and what you do with those that you receive should be transparent of you medium of communication (i.e. Bluetooth or RS-232). In most cases, on the Arduino side of things you won't change much at all.