How do I convert a 14-30R to a 6-20R?

Question: I recently bought a home with a shop. The shop is full of these (I think it is a NEMA 14-30R):

But I have a compressor and band saw that need these (I think it is a 6-20R):

A picture of the box and labels:

I am going to be changing the receptacles that correspond with positions 15-18 and 45-48 in the box, so both 40 A breakers. I have done a little research and am fairly certain I understand in principle how to wire the 6-20R with the wires being used on the 14-30R, although I would welcome a sanity check. I plan to wire the hot poles with the red and black wires, ground to green with the bare copper, and cap the white wire and curl up in the box.
I gave it a try today and ran into an issue. The wire is a very heavy gauge stranded wire - not sure the size (6/3? 4/3? No idea). It is so large that I can't wrap it around the screws and the small strands of the individual wires keep breaking.
My questions are:
1- is my understanding of the receptacle types correct?
2- Is my understanding of how to wire the smaller receptacle with the X/3 wire correct?
3- do I need to change the breakers from a 40A to a 20A or something else?
4- how do I connect such a large wire to a small receptacle? Do I need to use ring connector terminals or something?
Obviously I am not an electrician but I am not uncomfortable learning and doing. Just need some direction to see if I am in the ballpark. Thank you.
Answer: Nothing easier, buy a UL Listed adapter.
The difference between a UL Listed one and a cheap Cheese one is that the UL-listed one will include a fuse to provide the protection a 20A device needs.
And is also made of thick enough contact bars, and the plastic is safety-rated to resist fire and not emit toxic smoke.
40A breakers don't play with 30A sockets
30A receptacles (and I agree those are NEMA 14-30) are not allowed to have anything but a 30A breaker.  NEC 210.21.
40A breakers require 50A sockets. (NEMA refuses to define 40A socket sizes, because they are running out of possible pin configurations).
Now motor rules are weird, and welder rules are weirder. Often when a circuit is dedicated to a particular motor or welder load, the breaker is allowed to be oversized (owing to small duty cycle on lighter-duty welders, and some motors have overcurrent protection onboard and don't need it from the breaker).  However, this allowed oversizing does not apply to general-purpose receptacles. The lack of "Miller M1234 Welder Only" stickers on these outlets makes them general-purpose receptacles.
Use wire nuts or ILSCO Mac Block Connectors to step down

gave it a try today and ran into an issue. The wire is a very heavy gauge stranded wire - not sure the size (6/3? 4/3? No idea). It is so large that I can't wrap it around the screws and the small strands of the individual wires keep breaking.

Yes, that's going to happen.  Actually that indicates the wires are larger than #10, which is a blessing - they are legal on 40A breakers and only the socket was wrong.

8 AWG copper or 6 AWG aluminum is allowed 40A if it's NM or UF type cable.  Otherwise 8 AWG is allowed 50A.
6 AWG copper or 4 AWG aluminum is allowed 55A if NM or UF.  Otherwise 65A.
4 AWG copper is allowed 70A if NM or UF, otherwise 85A.
The higher ampacity requires terminals rated 75°C thermal.
Aluminum requires terminals rated for aluminum but is otherwise fine. ALL terminals should be torqued to spec, the difference is when an aluminum terminal burns up from mistorquing, aluminum gets blamed unfairly.
NEMA 6-20 receptacles are not rated for aluminum, but most larger ones are.

Do not attempt to directly attach wires >#10 to a NEMA 6-20 receptacle.  You must pigtail to 12 AWG wires.  To pigtail, you can use a wire nut (if it is listed for wires that large) or for wires up to 6 AWG, you can use the ILSCO Mac Block Connector, which is a "mini Polaris".
The ILSCO Mac Block or larger Polaris is your only option for aluminum wire. Do not use purple wire nuts - they do not work.
Questions
Honestly, I'd change the sockets to NEMA 14-50 type, and then use UL-Listed adapters to get NEMA 6-20 out of them.   Now to your questions:

1- is my understanding of the receptacle types correct?

Yes.

2- Is my understanding of how to wire the smaller receptacle with the X/3 wire correct?

Yes.

3- do I need to change the breakers from a 40A to a 20A or something else?
Comment: This seems like an easy fix. I like the idea of keeping the breakers I already have with the 14-50r. I am having a hard time finding the UL listed adapter with the 20 A fuse. I can only find the cheap ones, but I want the 20 A protection. I started on Amazon but have branched out and still can't find it. Any suggestions?
Comment: @nijonew All the major marketplaces having 3rd party sellers, like eBay, DealExtreme, Wish.com, Etsy and Amazon Marketplace will be flooded with the cheap dangerous stuff from overseas.  A reputable RV supply ought to have a UL Listed one.  Note that the fuse is not visible or replaceable.
Comment: That helps a lot. I was able to find one once I started looking for RV plugs. Thanks for all the help.
Comment: I changed the receptacle to the 14-50, got an adapter 14-50 to 6-20 with a 20A breaker, plugged my 12 AWG 16-ft extension cord into that, and then the band saw into that.  The breaker in the adapter trips immediately when I power up the bandsaw.  Any suggestions?
Comment: @nijonew Sounds like the breaker on the adapter is not tolerant of motor loads. Since you've already put the 20A breaker in the panel you might as well just change the outlet to NEMA 6-20. They make duplex 6-20 that takes the normal cover plate or domed cover.
Comment: That may be the case. For clarification the breaker that is tripping is the one in the adapter. I got two adapters because I need this in two locations and it does the same thing with both. So I still have the 40A breakers on the panel. This is the adapter that I purchased:      https://acworks.com/products/s1450cb620-1ft-50a-14-50p-plug-to-6-20-outlet?_pos=1&_sid=0dfe4d868&_ss=r
Comment: @nijonew Yes, I understood that. I would send it back as motor loads are perfectly reasonable loads.  (presuming your motor is not *broken*).   It is illegal to have a 20A breaker on a 50A socket, so go all-in on 20A, or all-in on 50a.
Comment: Gotcha. I think that is the next step. Thank you.
Answer: You need to change the breakers to match the receptacles. There are certain exceptions (e.g., 15A receptacles on 20A breaker) but in general both the receptacles (exact match except where code allows specific exceptions) and the wire (wire can be larger than breaker but breaker can't be larger than wire).
As far as the receptacle terminals not accepting the large wire, that is not surprising. Get an appropriate size wire nut, such as an Ideal WT54 Blue to pigtail a 12 AWG wire to the 6 AWG wire.
Comment: Oversized breakers are bad, @GeorgeAnderson. And bad in code means "it killed enough people to get into code." It's neat and tidy and WRONG as shown, and Your suggested appoach does not address the WRONG. There are other ways that would be just as neat and tidy and RIGHT, one of which is in this answer. If keeping any at 40A, the correct receptacles should be swapped in on those.
Comment: @GeorgeAnderson I very much disagree. The *primary* sizing determination for breakers is to match the wire. **But the device matters too.** A device may have wiring (internal for sure, but even the cable from the back of an oven to junction box, for example) that is smaller than the normal wiring required for NEC for a particular current rating. But that's OK as long as it is designed appropriately and approved by UL/ETL/etc. That being said, a device will have recommended breaker/circuit sizing based on expected current requirements and other design factors. That *must* be followed.
Comment: When you plug a tool calling for a 20A breaker into a 40A or 30A outlet, A failure of the tool has not been tested by an NRTL (UL, ETL, etc.) to trip that size breaker, and it may merrily arc and burn without tripping, or for an excessively long time before tripping.
Comment: When there are no specific requirements, there are standard calculations (e.g., the continuous derate, very specific calculations for cooktops/ovens, etc.) that are used instead. So for example, when my electrician did my heavy-up, the AC outside unit was previously installed with a 30A circuit and 10 AWG wire. He checked the nameplate rating and determined that a 25A breaker was correct (16.1A x 1.25 = 20.125 - round up to 25A) and installed that in the new panel. No issue of the wiring (it could truly handle 30A) but right-sizing the breaker to fit the device.
Comment: I will update the breakers and pigtail the wires. Thanks for the suggestions and for recommending a wire nut.
Comment: That looks like a beautiful installation.  People may beat me up for this, but what would so bad about buying a plugs that fits the existing 14-30R (30 amp, 240v) and the outlets needed for the band saw and compressor connected by a short length of 10/3 type SJ cable? I think the breakers are oversized for the 14-30R which is rated for 30 amps, but other than that, I'd leave everything intact and just go with a short (like 12") length of SJ to from the plug that fits the 14-30R to the one that feeds the tools.    I'd welcome friendly feedback.
Comment: If the breakers were resized for the 14-30Rs that would correct the WRONG. I did mention that the breakers were oversized.

  Let's face it as we all know, breakers are to protect INSTALLED wiring, nothing more.  Devices plugged in or hard wired usually have much smaller wires. Good appliances and tools have their own over-current protection.  Most table lamps have 18ga wire that can be plugged into a 15 or 20 amp circuit. Extension cords are also often 16 or 18 ga (not that I approve of that). So I see a parallel with down sizing the breakers to match the outlets and make the adpator cord
Comment: I'm going to be easy going on this.  So I respect the comments. I have a shop where my band saw, compressor, table saw, jointer, dust collector all operate at 240 / 20 amp circuits, all of them have over-current protection built into the motors and are socket/plug connected to the exact configuration for 240/20.  So I guess the only correct approach is to pigtail (as someone suggested) to be able to fit into the 240/20 amp outlet and downsize the breakers, pig-tailing on both ends probably, bc a 20 amp breaker probably won't take an 8 ga wire.   Maybe, maybe not, can't know until you try.
Comment: @George your idea won't work because you'd need a 20A fuse. **But UL approves adapters which do exactly that**.
Comment: I'm not sure I completely understand your comment. I did say the breakers needed be downsized twice in 2 comments. So what are you saying?  I said pigtails might need to be used to fit the 20 amp breakers already, so what are you getting at?

How do I convert a 14-30R to a 6-20R?


AC Soft Start and Portable Generator

Question: I am having an interlock and power inlet installed for a portable generator to plug into for my home.
I asked my electrician about adding an AC soft start kit to reduce the amount of start up watts and thus reduce the size of generator I need to run the AC in an emergency.
He advised me that even with the soft start kit, the 4 ton AC would draw at least half the 12,000 running watts from the generator, thus requiring the large generator versus getting a 9500 running watts generator.
On other forums and also on YouTube I see ppl running their 4 ton AC with a soft start kit and a 7,000 running watt generator.
What is correct here? I would like to save myself a few thousand dollars and be able to get a smaller generator if possible.
Comment: Are the youtube people using anything else with the generator?  You might want your fridge at least, maybe a microwave/coffee maker/tv/lights.  AC should have a label with volts amps needed(watts).
Comment: Well just don't run those things at the same time as the A/C.  You can't go by neighbors' experience with 4 ton A/Cs because A/C efficiency has dramatically improved in recent years, and their 4-ton may take a lot less electricity than yours, or vice versa.  Modern split systems also use inverter drive and are soft-start by design.
Answer: If you can afford it, then go for a larger generator.  I would suggest a diesel one as it requires less maintenance (unless you are able to service it yourself).
There are generator rental companies around.  If not too expensive, you could rent one and try it out.
We are rural, I had a 5KVA (loosely 5000 watts) generator first.  It required a pull start which my wife could not operate and it definitely did not cope with my 5KVA AC units.
In the new house, I have an 11KVA generator with auto-start.  We have three 5KVA heat pumps.  When the power fails, I flick two of them off manually, just to be safe.  And I can run the whole house on it (except the oven and induction tops).  It powers my electric water heater, all the lights, water pump, septic system, microwave, washing machine, all lights, 3 fridges, 2 freezers, computers for 4 people, and the media room.
Answer: Soft starts have a broad diversity, and motor quality varies, but I would expect AC nameplate would spec "minimum circuit ampacity" of around 15A, soft start needing 1.5x the nameplate, you are landing 5400w plus fan motor for air handling unit needing another 500w.
So you have 3800w left over if you get the 9600w. How frugal do you want to be? If you have lots of kids, an uncooperative spouse, it might not work for you. I personally prefer to go a little small for generators, they tend to be easier to start, to be quieter, use less fuel, and are easier to move and lift.
But I'm a little confused 9.5kw versus 12kw transfer switch? Most people are installing main panel breaker interlock style transfer switches, if you are I don't see a real downside to sizing for 12kw. To get the full capacity of a 9500w you would need a 40A breaker, likely same cost as 50A. Wire size for a 50A breaker should be one size larger than the 40A if he uses using NM cable, no change in wire size if using any 75°C rated wire. Receptacle for 40A is the same as 50A. I might get some disagreement, but even if you decide on the 9.5kw the only down side is you may have to make your cord if the 40A generator only has a 30A receptacle. Tell your electrician to go ahead and size the xfer breaker for 12kw.
Answer: I say go for it.
At a previous house I had an old-school 1-speed central A/C for the whole house that was rated at 5 tons (60,000 BTU/hr) and which used a 40 amp 2-pole breaker. I successfully ran this A/C with a 5000 watt diesel generator that had a 6250 watt surge rating.
How I did it:
I installed a hard-start kit on the A/C compressor, a 3-second time delay relay on the condenser's fan motor, and I set the inside air handler's 2-speed blower motor to low speed / constant fan. Lacking any of those three adaptations, it wouldn't run or would blow the generator's breaker, but with all three it ran just fine.

AC Soft Start and Portable Generator


I can't see my weapons! What's going on?

Question: Anyone ever have the issue of their weapons disappearing?
Comment: i get it very often on a round start, just double swap fix it for me most of the time
Answer: In order to clear up HUD issues such as radars being stuck, weapons not showing, killfeed stuck, etc., the easiest way to do so is to refresh the HUD by creating a demo, then stopping it.
By running the command below in the developer console:
record DEMO_NAME_GOES_HERE; stop;

You are forcing the game to record a demo, forcing it to refresh and redraw HUD elements.  Unless you specify the game to stop recording right away, it will continue to record whatever you are playing and will take up memory.
The name of the demo can be anything you want, so you could simply say record a; stop;, and that would be sufficient enough to redraw the HUD.
Alternatively, from my own experience, switching weapons to another weapon, then back to the "missing" weapon will fix the issue most of the time.  This solution is much more preferred as creating a demo and stopping it will freeze the game for a short period of time.
Comment: I knew about the record part, I just forgot that you can do the stop; afterwards.
Comment: Is the record feature similar to the replay system in TF2?
Comment: @ShadowZ. both run on Source, so yes. Albeit, CS:GO runs on a different version of Source compared to TF2
Answer: Anyone who has played CS:S and CS:GO has dealt with invisible weapons. (Not entirely sure about CS 1.6). We all think it is the worst thing ever, cause we can't sometimes see that sexy skin we got. Well, truth be told, there is an easy fix for it.
Before you do any of this, you will need to know how to enable and open Developer Console.
Follow these instructions:

Press esc
Go to Options
Go to Keyboard
Click Advanced
Click "Enable Developer Console"
And then press 'esc' until you get back into the game. From there, press the tilde key, or (~)

Now all you have to do, is open up console, and type in the following command:
record 1

Now after you type this, you will have a recorded dem file in your csgo folder, so if you want, you can go and delete it.
If I have confused anyone, please let me know, and I will try to make it more clear.
Comment: So a gameplay Record fix it? Never heard about this kind of fix
Comment: I think you have your order of operations mixed up; you should be listing how to get to the developer console first.


Grid Horizontal Scroll Bar (Floating)

Question: I use Magento for my website store.
The problem I face is the default horizontal scroll bar displayed within admin grids are useless when the number of rows extends further than the page displayed within a browser.
This makes accessing the scroll bar for practical use difficult.
For example, when i navigate to "Manage Products" in my admin backend. The products grid horizontal bar only shows once the user scrolls all the way down to the bottom of the page.
I want to be able to scroll horizontally from the very first row, therefore being able to view product attributes which are displayed further to the right (out of page view).
I've found a jquery solution here: http://jsfiddle.net/cowboy/45rEs/show/
But I don't know how to implement it into my store.
If you view the above url, you will see that the horizontal scroll bar appears anywhere that a horizontal overflow is established.
Comment: anyone know a solution? The current horizontal scroll is very frustrating
Answer: skin/adminhtml/default/default/boxes.css --> .hor-scroll class --> remove overflow: auto;
Comment: Good stuff man!! thanks for putting in the effort to help me :)

Grid Horizontal Scroll Bar (Floating)


R: Use raster package to calculate the number of consecutive TRUE values

Question: I am trying to find the number of consecutive days that a certain criteria is met for a stack of rasters. In this case I am trying to figure out if there are 10 consecutive days without rain for each 30 day period of the year.
Because the extensive amount of data I am using I need to come up with an efficient way to do this. ie trying to avoid using a loop through all raster cells.
I found one function that might make things easier but I can't figure out how to efficiently apply it to all raster cells. Here is an example of how it might be done easily. Here is a way to very quickly calculate the number of consecutive TRUEs.

z <- c(TRUE, TRUE, FALSE, FALSE, TRUE, FALSE, TRUE, TRUE, TRUE) rle(z)
  max(rle(z)$lengths)>=3

Now the issue is how (if possible) to apply that to all cells efficiently. stackApply? calc? Not sure.
Here is an example raster stack to help:
<code>   set.seed(42)
    require(raster)
    r1 <- raster(nrows=10, ncols=10)
    r2=r3=r4=r5=r1
    r1[]= runif(ncell(r1))
    r2[]= runif(ncell(r1))
    r3[]= runif(ncell(r1))
    r4[]= runif(ncell(r1))
    r5[]= runif(ncell(r1))
    rs=stack(r1,r2,r3,r4,r5)<.25
</code>
Comment: Why are you using `raster` objects instead of simple matrices (or 3D `arrays` if necessary)?  Beyond that, are you separating the year into 12 nonintersecting 30-day blocks, or do you want to run a rolling test over each 30-day sequence?
Comment: They are read in as .tif files, so keeping them as raster stacks seems natural (just a multidimentional array) but willing to switch. Eventually I am going to have it rolling over each 30-day period.
Comment: I keep it as a raster but loop over cells using extract.
Comment: use `calc(rs, fun)` where fun is your function (that works on a vector values, representing a single cell
Answer: Although I am sure there is a better way to do it. Here is one possibility:
<code>threeconsecutive = function(rasterin){
     s = rasterToPoints( rasterin )
     X = s[,'x']
     Y = s[,'y']
     s = s[,3:dim(s)[2]]
     s  = apply(s,MARGIN=1, function(x){max( rle(c(x))$lengths[rle(c(x) )$values==T], na.rm=T )>=3} )
     return(rasterFromXYZ( data.frame(x=X,y=Y,true=s) ))
 }
out = threeconsecutive(rs)
plot(out)
</code>
Comment: Hi could you please help me with a related question. http://stackoverflow.com/questions/40467967/calculating-number-of-three-consecutive-values-above-a-threshold-in-raster-stac


Data frame column names after split

Question: When executing the following code
data <- data.frame( A = c("foo", "foo", "bar", "bar"),
                    B = c("foo","bar", "foo", "bar"),
                    C = c("bla", "foo", "bla", "bar"),
                    D = c(1, 2, 3, 4 ),
                    E = c(5, 6, 7, 8 ))

ds <- split(data, list(data$A, data$B, data$C), drop=TRUE)
write.table(ds[1], file="foo.csv", append=FALSE, row.names=FALSE)

foo.csv looks like this:
 "bar.bar.bar.A","bar.bar.bar.B","bar.bar.bar.C","bar.bar.bar.D","bar.bar.bar.E"
 "bar","bar","bar",4,8

i.e., the column names contain the contents of the columns used to split. How do I change does names back to the original ones in a generic way? (I don't want to assign column names like "A", "B",....)
Answer: The output of split is a list. ds[1] returns a list, while ds[[1]] returns the value within that first list item.
Example:
ds[1]
# $bar.bar.bar
#     A   B   C D E
# 4 bar bar bar 4 8

ds[[1]]
#     A   B   C D E
# 4 bar bar bar 4 8

To get the output properly written as a CSV file, you need to extract the actual data.frame, so you need to use the ds[[1]] approach.
write.table(ds[[1]], file="foo.csv", append=FALSE, row.names=FALSE)

If you wanted to write all of the data.frames to separate CSV files, you can do something like:
lapply(names(ds), function(x) {
  write.table(ds[[x]], file = paste(x, ".csv", collapse = ""),
              append = FALSE, row.names = FALSE)
})

This will create four CSV files (named bar.bar.bar.csv, bar.foo.bla.csv, foo.foo.bla.csv, and foo.bar.foo.csv) in your working directory.
Comment: Awesome, thanks! Writing to separate files is exactly what I want to do!

Data frame column names after split


the following packages have unmet dependencies(KDE)

Question: I'm new to Ubuntu but I failed to solve this error. I had searched for this problem but I didn't find the perfect solution. Please help me. I'm finding this error. Please give me a perfect solution because this error doesn't let me to install any software. The error is:
the following packages have unmet dependencies:

software-properties-kde: Depends: python3 (>= 3.2.3-3~) but 3.3.1-0ubuntu1 is to be installed
                         Depends: python3-pyqt4 but it is not going to be installed"

Answer: Open Terminal and issue this command
sudo apt-get update && sudo apt-get upgrade
sudo apt-get install -f

Comment: i get it solved by changing sources.list but got now new error.Failed to fetch http://ppa.launchpad.net/upubuntu-com/xampp/ubuntu/dists/raring/main/binary-i386/Packages  404  Not Found
Comment: It may be outdated link.
Answer: with the launchpad error, have you tried changing the selected 'other software' in Software Updater?
It's probably been selected by some program as a source there, so uncheck entries that refer to launchpad.


Kaiser windowed sinc filter for mip mapping

Question: These older but informative article talks about how a Kaiser windowed sinc filter is a good way to generate mips.
The Inner Product - Mipmapping - Part 1 | Jonathan Blow
The Inner Product - Mipmapping - Part 2 | Jonathan Blow
Unfortunately, the source code it mentions isn't anywhere to be found.
Can anyone explain how a kaiser windowed sinc filter is calculated and/or give the kernel weights to use for convolution?
Comment: I've not used a Kaiser windowed sinc, but I did find with (some) other windowed sincs that you can get some very strange behaviour once you'd normalised all the non-zero sample weights. In particular, if you plot the weight applied to the "centre" sample as the centre of the window moved from being located on the centre weight to being just off it, the magnitude would increase (rather than decrease as you'd expect with a sinc).
Comment: One issue with using a sinc filter for mip-mapping has to do with the hardware texture units. Mipmaps are usually built in a way that the next level sample falls 'between' the previous level samples. That is as if the samples are located at half-integer coordinates and the origins of all the levels coincide. Sinc filter downsampling, on the other hand, filters the data and then throws away every other pixel. This results in a visible half pixel shift. If you try to average those pixels instead of subsampling, then you arrive at a 2x2 box filter essentially.
Answer: I was curious so I tried it. I used the Kaiser Window from Wikipedia: $\frac{I_0\left(\alpha\sqrt{1-x^2}\right)}{I_0\left(\alpha\right)}$
This page has a slightly different formulation using $\pi\alpha$ instead of $\alpha$. Given the comments in the page you linked about the Kaiser window being very similar to Lanczos and how they even overlap in the graph, I suspect they also used the former formula. You can see how close they are if you plot both on Wolfram.
This left me wondering if that's what Mitchell originally meant as it's not "noticably better". I could not see the difference at all with my test texture (it's there, just not noticeable). However, using the second formula, the difference in the plots is much more striking. And there is a noticeable difference in the resulting images. Whether it's better is a matter of interpretation and depends on the filter size.
With $x \in \left[-1,1\right]$ , I used this C++ windowing function:
#include <boost/math/special_functions/bessel.hpp>
float bessel_i0( float x )
{
    return boost::math::cyl_bessel_i( 0, x );
}

float window_kaiser( float x )
{
    const float alpha = 4.0f * M_PI;
    float k =
        bessel_i0( alpha * sqrtf( 1.0f - x * x ) ) /
        bessel_i0( alpha );
    return k;
}

This is the second version. Remove the M_PI to get the first version which is more like Lanczos.
The modified Bessel function of the first kind seems to be a C++17 / boost thing. If you have neither, this quick hack will do:
float bessel_i0( float x )
{
    float r = 1.0f;
    float term = 1.0f;
    for( int k = 1; true; ++k )
    {
        float f = x / float(k);
        term *= 0.25f * f * f;
        float new_r = r + term;
        if( new_r == r )
            break;
        r = new_r;
    }
    return r;
}

Just don't consider that a general replacement for a proper bessel function. However, it's fine for computing the window as far as I could tell.
As the second wikipedia page I linked shows, that window_kaiser can be used on a symmetric filter with $N$ weights by using $x = \frac{2n}{N-1}-1$, where $n$ is $0, 1, 2 \dots N-1$.
Computing the weights of the sinc filter itself is another thing entirely as it depends on filter size, how much you're resizing, etc. I suggest posting a separate question if you don't know how do to that.


Math Contests: How to Solve Equation with $x$ in the Denominator

Question: Okay, I realize this seems like a really stupid question, but on a math contest (without calculators) I got down to this equation:
$$\frac{26}{672-x} + \frac{24}{372-x} = \frac{50}{480-x}$$
whereupon I spent 15 minutes trying to solve for $x$ until I eventually gave up. Especially, on a math contest, this is not an ideal situation. $x$ ended up being 48, but I don't recall how to do this type of algebra without a calculator. For those curious, the problem appeared on the AMC 12A.
Comment: I'd probably let $2u=372-x$. Then the equation is:$$\frac{13}{150+u} + \frac{12}{u} =\frac{25}{54+u}$$ That might be easier to solve.
Comment: It becomes a linear equation because 13+12=25, so the quadratic terms cancel.
Comment: $x=48$ of course
Answer: $$\frac{26}{672-x} + \frac{24}{372-x} = \frac{50}{480-x}$$
We could just go ahead and start solving this, but it will make the terms smaller if we let $2u=372-x$
$$\frac{26}{300+2u} + \frac{24}{2u} = \frac{50}{2u+108}$$
factoring a two out of top and bottom, we get
$$\frac{13}{u+150} + \frac{12}{u} = \frac{25}{u+54}$$
We then want to get common fraction on the left
$$\frac{13u(u+54)}{u(u+150)(u+54)} + \frac{12(u+150)(u+54)}{u(u+150)(u+54)}-\frac{25u(u+150)}{u(u+150)(u+54)}=0$$
$$\frac{13u(u+54)+12(u+150)(u+54)-25u(u+150)}{u(u+150)}=0$$
$$13u(u+54)+12(u+150)(u+54)-25u(u+150)=0$$
$$13u^2+(13)(54)u+(12u+(12)(150))(u+54)-25u^2-(150)(25)u=0$$
$$13u^2+(13)(54)u+12u^2+(12)(150)u+(54)(12)u+(54)(150)(12)-25u^2-(150)(25)u=0$$
$$(13)(54)u+(12)(150)u+(54)(12)u-(150)(25)u=-(54)(150)(12)$$
Now comes the mental math part;
$$u[(13)(54)+(12)(150)+(54)(12)-(150)(25)]=-(54)(150)(12)$$
Can you get it from here?
Comment: Okay, thank you so much. I can't believe I forgot the basic algebra skills. Hopefully I'll remember them on the AMC 12 next week! Thanks again!
Comment: @JunlinYi Sure thing, glad I could help! Just remember on these problems to always get rid of fractions if you can... it's not the fastest strategy in most cases (there are faster ways to solve the problem than I showed), but it works pretty much every time. The substitution is also a bit unnecessary, and serves only to help with the mental math. If you have time to multiply  the 3-4 digit number by hand then finding a substitution may not be worth it. If you do, remember to plug back in the solution for $u$ (or whatever variable you chose) to get an answer in terms of the original variable!


How to seal gap around bottom of shed, between ground and planks?

Question: We started building a shed in our garden. Now we would like to close the sides using wooden planks. To keep the wood in a good state as long as possible we want to leave a gap between the lowest plank and the ground, but don't want water to run into the shed. How could we close that gap? Any ideas what material would be best to use?
We thought about trying to build a concrete lip all the way around but this would be difficult for us and we aren't sure if it's the best way.
Comment: You could use cement board (eg "HardiePlank") for the bottom course and it would never rot. (Go for a thicker one, as the thin -- 1/2" or so -- are really delicate.)
Comment: Even with a plank going down to the ground you wouldn't get that really waterproof. Can you make the shed's floor higher than the ground around the shed? Also take care of that small space between your wall and the neighbor's wall. This is a great place for all kinds of weed to grow as it likes.
Answer: I'd install 2x4's horizontally at about 24" on center to the exterior side of the posts. (The bottom horizontal 2x4 should be pressure treated.) Then I'd install a cheap wall sheathing (if required for seismic active area or high wind area.)
If not required, then install a moisture barrier directly to the 2x4's. The reason we install a moisture barrier is because we know the siding will leak. Wind and rain will "push" moisture into the wall system and cause dryrot.
Then I'd install the siding (the boards you described) vertically letting them span from horizontal 2x4 to horizontal 2x4. I'd make sure the boards lap the bottom horizontal 2x4 by about 1". This will give a "drip" so water can't "wick" back up into the wall.
Summary:
Installing horizontal  2x4's allows a moisture barrier to be installed to protect the existing posts, etc.  The posts are not pressure treated (no incising) but may be decay resistant if it's cedar or redwood, but they will eventually rot. For added protection, you can add a metal strip (called "Z-flashing ") to the very bottom of the wall to protect the end grain of each vertical board from water and pests.
Answer: I see no reason you could not use treated lumber, it appears to me to be the simplest solution. It would probably blend better than any other type of material.
Answer: I encountered a similar problem when I built a greenhouse about fives years ago. I framed walls that housed reclaimed windows. The walls were built overtop of cinder blocks and it left a gap about the size of the cinder block all the way around the greenhouse.
My building aesthetics manager (wife) insisted that it be "pretty". I ended up using corrugated galvanized metal, which was pretty cost effective. I cut the metal to size using circular saw with a metal cutting blade (at the time, it was the best tool I had for the job).
I buried dirt up to the corrugated metal inside and outside to provide some extra insulation. The metal has held up surprisingly well, above the soil surface it still looks new and under the soil there is little rust in some locations.
Here you can see the gap under the windowed wall.

Here you can barely see the metal skirt around the greenhouse. And the leftover metal was used for the raised beds in the background.


remove an entire array

Question: i am trying to remove records of an employee that contains "?"(null values).  the employee database looks like
34,45,56,?,34
45,67,34,56,56
23,45,67,?,90
using the following code i replaced the entire row that contains "?" with "0".
public void doRemoval(String filename)
{
        contents = new Vector();
        inputstream = new FileInputStream(filename);
        br = new BufferedReader(new InputStreamReader(inputstream));
        String string = "";
        while((string = br.readLine())!= null)
        {
            String[] split = string.split(",");
            Vector vector = new Vector();
            for(int i=0; i<split.length; i++)
                vector.add(split[i].trim());
            if(vector.contains("?"))
            {
                for(int i=0; i<split.length; i++)
                    split[i] = "0";
            }
            contents.add(split);
        }

the output is
0,0,0,0,0
45,67,34,56,56
0,0,0,0,0
now i want to remove the rows containing "0".  i don't have an idea of how to do it.  can anyone help me.  all that i want to do is to remove the rows that contain null values.  is there any other way to perform it?
Answer: Write this:
public void doRemoval(String filename)
{
    contents = new Vector();
    inputstream = new FileInputStream(filename);
    br = new BufferedReader(new InputStreamReader(inputstream));
    String string = "";
    while((string = br.readLine())!= null)
    {
        String[] split = string.split(",");
        Vector vector = new Vector();
        for(int i=0; i<split.length; i++)
            vector.add(split[i].trim());
        if(!vector.contains("?"))
        {
            contents.add(split);
        }

    }

You don't remove them, you just don't add them.
Comment: and can you tell me is that possible to replace the null values by mean value of that particular column?
Comment: Yes it is and that is not hard, too. Try to think about it a bit. Tip: first iterate once to compute the mean(actually the number of non-'?' values and their sum) value and then iterate second time to replace the '?'-s. Take care on the case when all values are '?'.
Comment: actually i don't have an idea of how to  read it column vise.
Comment: Go over split before inserting it into contents. At this point you can access separate elements. You may use Integer.ValueOf to convert string to Integer.
Answer: If you don't need to have the intermediate step with all zeros, you can:
if(!vector.contains("?")) {
    contents.add(split);
}

instead of the block with:
if(vector.contains("?"))
{
    for(int i=0; i<split.length; i++)
    split[i] = "0";
}
contents.add(split);

remove an entire array


What's the most compact way to add "events" to a JavaScript class in a Node.js module? (in ES6 and above env.)

Question: Have been looking for the universal way to handle events in a class. To be exact, I'm making a node.js module and I want to be able to add multiple callbacks to certain events. Say, my source looks something like this:
class Example {
    constructor(...args) {
        // ...
    }
    doSomething(earg) {
        setTimeout(() => {
            // I want an event call here.
            // this.callEvent(eargs) or something like that, to pass
            // down arguments to callbacks.
        }, 3000);
    }
    on(event, callback, watch) {
        // ...
    }

    once(event, callback, watch) {
        // ...
    }
}

const example = new Example();
example.on('doSomethingEnd', (earg) => console.log(':P', earg));

What's the most compact and modern way of achieving .ons and .onces in an ES6 and above environment and how to do "code editor autofill" for such? (For editors like Atom or VSCode, or any other that have syntax hinting).
Comment: Just to clarify things up, do you have any issues with the code or just trying to get a review? I'm personally not sure what does "*most compact and universal way* terms stand for, maybe more experienced users would know that topic. Maybe [this](https://stackoverflow.com/questions/43727516/how-adding-event-handler-inside-a-class-with-a-class-method-as-the-callback?rq=1)?
Comment: @Aleksandar Asking for an exact solution. Also just to clarify, I'm in a `node.js` environment with no document or html elements, I'm making a *node module*. I'll modify the question a little just so it's a little more clear.
Comment: @bouncytorch then why not just use https://nodejs.org/api/events.html?
Comment: @Bergi well I didn't know about it, thank you! That's why I asked this question, plus as far as I can tell there wasn't a similar question on Stack. If there was, someone could flag it as duplicate, cuz I can't.
Answer: Solved it, Node has a built in class for that (props to @Bergi):
const { EventEmitter } = require('events');

class Example extends EventEmitter {
    constructor(...args) {
        // ...
    }
    doSomething(earg) {
        setTimeout(() => {
            this.emit('<example>', 'arg0')
        }, 3000);
    }
}

const example = new Example();
example.on('<example>', (earg) => { /* ... */ });

Comment: The previous answer was removed because it was ChatGPT-generated, [which isn't allowed](https://meta.stackoverflow.com/questions/421831/temporary-policy-chatgpt-is-banned).


How to un-inline an inline class?

Question: As a bloody android beginner I am trying to put an inline class definition into its proper class. Here is the piece of code with the inline class:
imageView.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View arg0) {
        // actual code here
    }
});

Here is what I have tried but gives a compiler error:
public class TestClass extends View.OnClickListener {

    @Override
    public void onClick(View arg0) {
        // actual code here
    }
}

Error message: no interface expected here. I have no idea what this text means...
So how to proper un-inline an inline class, so that I can use it as follows in the actual code:
imageView.setOnClickListener(new TestClass());

Comment: Android and Java beginner?
Comment: Yes bloody beginner in both. Less than 10 years experience! Maybe in 10 years I know the basics...
Comment: I see.. Maybe not that long! Personally, Java 2 years, Android 1 year. But yeah, these "inline" classes are called [anonymous classes](https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html) and you `implements` an [`interface`](https://docs.oracle.com/javase/tutorial/java/concepts/interface.html) and [`extends`](https://docs.oracle.com/javase/tutorial/java/concepts/inheritance.html) a [`class`](https://docs.oracle.com/javase/tutorial/java/concepts/class.html)
Answer: There is issue in implementation
In java class must be extend and interface must be implements
View.OnClickListener is an interface so implement it.

Sample correct code

public class TestMe implements View.OnClickListener {

    @Override
    public void onClick(View arg0) {
        // actual code here
    }
}

Comment: Because `View.OnClickListener` is an interface but not a class?

How to un-inline an inline class?


How to transmit data via USB HID(/dev/hidg0)?

Question: I'm using Atmel sama5d3x serials. I implement device to USB HID device (as keyboard). Already try the configuration of kernel for both USB HID to g_hid.o(built-in_ or g_hid.ko module), then Windows can identify as keyboard, event device has interface (/dev/hidg0) there.
How can I transmit data via this interface?
Kernel version : 3.14
Answer: I guess your question is "how can i transmit data via the interface from the Linux".
From Linux userspace, you can open /dev/hidg0 with mode wb and then simply write to this file descriptor.
For instance in Python:
with open('/dev/hidg0', 'wb') as fd:
    fd.write(data_to_sent_over_hid)


Some confusion between ASP.NET 4.0 and 2.0

Question: I am trying to make a website in C# ASP.NET.  I have been given some code as well as visual studio 2010.  The code I was given was written in ASP.NET 4.0, so I obviously want to code in that, but my web hosting only supports ASP.NET 2.0.  If I upgrade to 4.0 what's the difference as far as compatibility issues with all browsers, or any draw backs to using 4.0.  I am using 1&1 hosting so it is a pretty commercial hosting, maybe there is a reason why they do not have 4.0 standard on their servers?  Thanks guys!
Answer: If your hosting company doesn't offer 4.0, your applications will not run.
The runtime is different, the configuration is different. There are too many differences for things to work out of the box.
Most hosts will let you have a virtual server for a higher cost, where you can install anything you want (within limit), so ask about that.
Answer: the browsers have nothing to do with asp.net compatibility.
asp.net 4.0 still does not have widespread availability because it is pretty new, but it is rock solid stable and it is generally recommended over asp.net 2.0
Comment: Even if you can't host it anywhere?


How do I prevent my imbecile son from being an heir?

Question: I have a daughter and two younger sons; they are all marrying geniuses.
My oldest son is inheriting everything and he is an imbecile. My oldest son isn't a traitor so I have no legal rights to imprison or execute him; he's just very unwanted.
How can I make my daughter or younger son an heir, instead of my oldest (imbecile) son?
Comment: Have you considered a tragic shaving accident?
Comment: Start a war and arrange a properly heroic death?
Comment: Is it impractical to change your succession law to Elective? Seems like the obvious solution.
Comment: it isnt because my son isnt a traitor and i have no legal rights to imprison or execute him, he's just very unwanted
Answer: I was once in a similar situation. Even if you could imprison and even banish your son, he would still be your heir. You could execute him, but I've found it to be an unpreferable choice due to the penalties (-10 Opinion from all vassals, -20 Piety).
It's possible, but there are no guarantees for success. Here's a few things you can do:

If your king is old, frail and likely to die soon, you could still
imprison and execute your son, even if you have no moral right to do
so. You will get severe penalties to the opinion of vassals and lose
a bunch of piety, but you will be certain it will work. Having your son excommunicated first will eliminate some of the penalties. Can be used
in emergencies.
Make him lead an army of only a handful of men, preferably not a very skilled troupe. Throw him against far superiour forces, and hope he gets himself killed. If he gets imprisoned, you could either refuse to ransom him out (in my experience, prisoners often die in custody) or bail him out and send him on more suicide missions.
Give your preferred son a whole load of powerful duchies. If everything goes well, this will start a succession war once you die. You will then play as the imbecile. Make sure you lose. This option will probably not work in gavelkind succession, since they prevent you from actively meddling with the succession too much this way.
You might also consider changing your succession law to elective, however that might backfire if you don't have enough votes or the ability to make vassals point at your favourite candidate. It might also be messy if you rule more kingdoms.
In old versions of the game (v1.x), you could disinherit anyone by appointing them bishops. This exploit has since been removed, but if your save game is very old, there might be hope still. This is definitely the easiest and most efficient way to disinherit someone.

You can also do the second option if he actually does inherit. If he dies as a ruler, his eldest brother will probably inherit, so long as your succession laws allow it and he hasn't fathered any child of his own.
Similarly, you can actually commit suicide, provided he has the depressed trait. If he hasn't fathered any children, your titles should go to one of his non-imbecile siblings.
None of these options are sure-fire, of course. The sooner you start working on the untimely death of your heir, the better.
Comment: As someone who has no idea what this game is, I like this question/answer. It's all about how to murder an imbecile without getting hated for it. It's great. :) lol
Comment: Making him a bishop also works. Free investiture comes handy.
Comment: Adding to the above: if you're Catholic, get your imbecile son excommunicated; Catholics care a *lot* less when horrible things happen to excommunicated people.  You'll still get Kinslayer, but you won't get the same opinion penalties.
Comment: @SMeznaric Ah. That's an even easier solution. I can't believe I hadn't thought of that.
Comment: I'm not sure if making him a Bishop worked on previous patches, but I've tried a few days ago and you get the message "you can't disown your heir by making him a Bishop".
Comment: @Lemmings19 Well, murdering an imbecile without getting hate for it pretty much *is* the game.
Answer: You can give your son a duchy or viceroalty, and then ask to retract one of his vassals. For a mere -10 global modifier (that expires within 10 years), he will rebel. Once you imprison him, you can execute him for treason.
Comment: I have issues with this approach as it will give you the ghastly kinslayer trait. I prefer using assassins to do the job, keeping my fingers crossed that I don't get discovered to be behind the deed


Uncaught TypeError: Cannot read properties of undefined (reading 'indexOf')

Question: I'm selecting all child divs of area_enInfantry and looping through to adjust the text of certain ones. cardArray is a global const and myId is defined within the parent function.
Uncaught TypeError: Cannot read properties of undefined (reading 'getAttribute')

var field = $("#area_en" + cardArray[myId]['type']).find("div");

field.each(function(a, element) {
  console.log("cC type:" + cardArray[myId]['type'] + "- index:" + a + " title: " + element[a].attr('title'));

  if (element[a].attr("title").indexOf("player") < 0) { // check this card isn't special player card
    doStuff;
  }
});

-1

-1

2

I read on this post that it may be because the contents of field/element may be DOM elements and that I should wrap them in $() so I did exactly that- changing both variables to $(element)[a].attr('title')
but now I get Uncaught TypeError: Cannot read properties of undefined (reading 'indexOf') instead, seemingly moving the error to the next line.
What am I doing wrong here?
Comment: Problem looks like that the first element in your .each is info_enInfantryScore
Answer: There's a couple of issues here. Firstly the variable element contains a Element object, not a jQuery object, so there is no attr() method available.
Secondly, once you correct that, attr('title') on the first div is not set so is undefined. Therefore you'll get an error because you're calling indexOf() on an empty value. You can use solve this by coalescing the value to an empty string if null.
Also note that I would assume you want to invoke the doStuff() function, so need to add the () at the end and it's better practice to use prop() over attr() where possible.
With that said, try this:

// mock data
let myId = 'foo';
let cardArray = { foo: { type: 'Infantry' } }

let doStuff = () => console.log('do stuff...');
var $field = $("#area_en" + cardArray[myId]['type']).find("div");

$field.each(function(i, element) {
  let $el = $(element);
  console.log("cC type:" + cardArray[myId]['type'] + "- index:" + i + " title: " + $el.prop('title'));
  if (($el.prop("title") || '').indexOf("player") < 0) { // check this card isn't special player card
    doStuff();
  }
});

-1

-1

2


Inequality problem

Question: What are the values of $B_1, B_2$, and $B_s$ so that the following inequality is satisfied with any value of $U_1$ and $U_2$? where $B_1, B_2, B_s, U_1$, and $U_2 \in \mathbb R^+$
$ B_1 U_1^2 + B_2 U_2^2 < B_s (U_1-U_2)^2 $
Comment: First try $U_1=\cosh^2(x)\quad U_2=\sinh^2(x)$.Hope it helps to clarify something .
Comment: Do you mean only $U_2\in\mathbb{R}^{+}$ ($B_1, B_2, B_s, U_1$ are real numbers)?
Comment: Yes, all the numbers are positive reals
Comment: What if $U_1 = U_2 > 0$ in your inequality?
Comment: It seems that $B_1$ or $B_2$ must be negative. I will review the problem
Answer: Hint: If $U_2 \neq 0$, consider the quadratic inequality
$$ (B_s - B_1) (\frac{U_1}{U_2} )^2 - 2 B_s (\frac{U_1}{U_2} ) + (B_s - B_2) > 0 $$

 This has no real roots, so the necessary and sufficient condition is
 1. $B_s - B_1 > 0 $,
 2. $(2B_s)^2 - 4 (B_s - B_1)(B_s - B_2) < 0 $.
 Can you proceed from here?

$ $

 Deal with $U_2 = 0 $ separately

Conclude that the necessary and sufficient conditions are:
$$B_sB_1 + B_sB_2 - B_1B_2 < 0, B_s > B_1, B_s > B_2$$
Comment: Thanks!!
A single small detail:
Comment: Thanks!!
A single small detail:
In the line
$ (2B_s)^2 - 4 (B_s - B_1) ( B_s - B_2) < 0 $
Hence,
$ B_s(B_1+B_2) - B_1 B_2 < 0 $
Comment: @JonattanSarmiento Ah yes indeed. Fixed.

Inequality problem


rabbitsvn deleted **all** my folders?

Question: I was working with rabbitsvn and trying to export a file from an older revision, when suddenly all programs in the background just shut down. I go to my "Home"-folder to find out that all (!!) my folders and data except a single one has been deleted.
Not only that, many of my programs have also been deleted (like Dropbox) + Firefox was reset, so I lost all my bookmarks and active logins. My Unity-launcher was also reset.
How on earth is this possible? What should I do to get my stuff back?!? I'm really close to jumping out the window!!!!!!
They are not present in the trash and not hidden.
Comment: I am not sure how this is possible but can you check if they are at least present in the trash, or may be hidden(press ctrl + h to unhide), or moved to some other location?
Comment: Unfortunately, your best bet next  is to use a data recovery software before you try to add/remove/modify data on your system now: http://www.cgsecurity.org/wiki/TestDisk_Step_By_Step
Answer: You can use Testdisk to recover you lost data. Go to Here for more details.

rabbitsvn deleted **all** my folders?


multiple stopwatch in jquery

Question:
I want to make multiples stopwatches in jquery, but the problem is i want the stopwatch the respective stopwatch to sun when we hit the corresponding button, and should stop when we hit button for another stopwatch and that respective stopwatch should start simultaneously, please see the image for reference, i know the question is not so clear, sorry for inconvenience.
thanks in advance.
Comment: There doesn't appear to be any question, let alone it being unclear
Comment: Welcome to StackOverflow! Please read [ask], and remember to always include a [mcve] in your questions.
Answer: try this one:
<code>$(document).ready(function() {

    (function($){

        $.extend({

            APP : {

                formatTimer : function(a) {
                    if (a < 10) {
                        a = '0' + a;
                    }
                    return a;
                },

                startTimer : function(dir) {

                    var a;

                    // save type
                    $.APP.dir = dir;

                    // get current date
                    $.APP.d1 = new Date();

                    switch($.APP.state) {

                        case 'pause' :

                            // resume timer
                            // get current timestamp (for calculations) and
                            // substract time difference between pause and now
                            $.APP.t1 = $.APP.d1.getTime() - $.APP.td;

                        break;

                        default :

                            // get current timestamp (for calculations)
                            $.APP.t1 = $.APP.d1.getTime();

                            // if countdown add ms based on seconds in textfield
                            if ($.APP.dir === 'cd') {
                                $.APP.t1 += parseInt($('#cd_seconds').val())*1000;
                            }

                        break;

                    }

                    // reset state
                    $.APP.state = 'alive';
                    $('#' + $.APP.dir + '_status').html('Running');

                    // start loop
                    $.APP.loopTimer();

                },

                pauseTimer : function() {

                    // save timestamp of pause
                    $.APP.dp = new Date();
                    $.APP.tp = $.APP.dp.getTime();

                    // save elapsed time (until pause)
                    $.APP.td = $.APP.tp - $.APP.t1;

                    // change button value
                    $('#' + $.APP.dir + '_start').val('Resume');

                    // set state
                    $.APP.state = 'pause';
                    $('#' + $.APP.dir + '_status').html('Paused');

                },

                stopTimer : function() {

                    // change button value
                    $('#' + $.APP.dir + '_start').val('Restart');

                    // set state
                    $.APP.state = 'stop';
                    $('#' + $.APP.dir + '_status').html('Stopped');

                },

                resetTimer : function() {

                    // reset display
                    $('#' + $.APP.dir + '_ms,#' + $.APP.dir + '_s,#' + $.APP.dir + '_m,#' + $.APP.dir + '_h').html('00');

                    // change button value
                    $('#' + $.APP.dir + '_start').val('Start');

                    // set state
                    $.APP.state = 'reset';
                    $('#' + $.APP.dir + '_status').html('Reset & Idle again');

                },

                endTimer : function(callback) {

                    // change button value
                    $('#' + $.APP.dir + '_start').val('Restart');

                    // set state
                    $.APP.state = 'end';

                    // invoke callback
                    if (typeof callback === 'function') {
                        callback();
                    }

                },

                loopTimer : function() {

                    var td;
                    var d2,t2;

                    var ms = 0;
                    var s  = 0;
                    var m  = 0;
                    var h  = 0;

                    if ($.APP.state === 'alive') {

                        // get current date and convert it into
                        // timestamp for calculations
                        d2 = new Date();
                        t2 = d2.getTime();

                        // calculate time difference between
                        // initial and current timestamp
                        if ($.APP.dir === 'sw') {
                            td = t2 - $.APP.t1;
                        // reversed if countdown
                        } else {
                            td = $.APP.t1 - t2;
                            if (td <= 0) {
                                // if time difference is 0 end countdown
                                $.APP.endTimer(function(){
                                    $.APP.resetTimer();
                                    $('#' + $.APP.dir + '_status').html('Ended & Reset');
                                });
                            }
                        }

                        // calculate milliseconds
                        ms = td%1000;
                        if (ms < 1) {
                            ms = 0;
                        } else {
                            // calculate seconds
                            s = (td-ms)/1000;
                            if (s < 1) {
                                s = 0;
                            } else {
                                // calculate minutes
                                var m = (s-(s%60))/60;
                                if (m < 1) {
                                    m = 0;
                                } else {
                                    // calculate hours
                                    var h = (m-(m%60))/60;
                                    if (h < 1) {
                                        h = 0;
                                    }
                                }
                            }
                        }

                        // substract elapsed minutes & hours
                        ms = Math.round(ms/100);
                        s  = s-(m*60);
                        m  = m-(h*60);

                        // update display
                        $('#' + $.APP.dir + '_ms').html($.APP.formatTimer(ms));
                        $('#' + $.APP.dir + '_s').html($.APP.formatTimer(s));
                        $('#' + $.APP.dir + '_m').html($.APP.formatTimer(m));
                        $('#' + $.APP.dir + '_h').html($.APP.formatTimer(h));

                        // loop
                        $.APP.t = setTimeout($.APP.loopTimer,1);

                    } else {

                        // kill loop
                        clearTimeout($.APP.t);
                        return true;

                    }

                }

            }

        });

        $('#sw_start').live('click', function() {
            $.APP.startTimer('sw');
        });

        $('#cd_start').live('click', function() {
            $.APP.startTimer('cd');
        });

        $('#sw_stop,#cd_stop').live('click', function() {
            $.APP.stopTimer();
        });

        $('#sw_reset,#cd_reset').live('click', function() {
            $.APP.resetTimer();
        });

        $('#sw_pause,#cd_pause').live('click', function() {
            $.APP.pauseTimer();
        });

    })(jQuery);

});
</code>
DEMO HERE
OR
<code>$(function () {

    // Never assume one widget is just used once in the page. You might
    // think of adding a second one. So, we adjust accordingly.
    $('.stopwatch').each(function () {

        // Cache very important elements, especially the ones used always
        var element = $(this);
        var running = element.data('autostart');
        var hoursElement = element.find('.hours');
        var minutesElement = element.find('.minutes');
        var secondsElement = element.find('.seconds');
        var millisecondsElement = element.find('.milliseconds');
        var toggleElement = element.find('.toggle');
        var resetElement = element.find('.reset');
        var pauseText = toggleElement.data('pausetext');
        var resumeText = toggleElement.data('resumetext');
        var startText = toggleElement.text();

        // And it's better to keep the state of time in variables
        // than parsing them from the html.
        var hours, minutes, seconds, milliseconds, timer;

        function prependZero(time, length) {
            // Quick way to turn number to string is to prepend it with a string
            // Also, a quick way to turn floats to integers is to complement with 0
            time = '' + (time | 0);
            // And strings have length too. Prepend 0 until right.
            while (time.length < length) time = '0' + time;
            return time;
        }

        function setStopwatch(hours, minutes, seconds, milliseconds) {
            // Using text(). html() will construct HTML when it finds one, overhead.
            hoursElement.text(prependZero(hours, 2));
            minutesElement.text(prependZero(minutes, 2));
            secondsElement.text(prependZero(seconds, 2));
            millisecondsElement.text(prependZero(milliseconds, 3));
        }

        // Update time in stopwatch periodically - every 25ms
        function runTimer() {
            // Using ES5 Date.now() to get current timestamp
            var startTime = Date.now();
            var prevHours = hours;
            var prevMinutes = minutes;
            var prevSeconds = seconds;
            var prevMilliseconds = milliseconds;

            timer = setInterval(function () {
                var timeElapsed = Date.now() - startTime;

                hours = (timeElapsed / 3600000) + prevHours;
                minutes = ((timeElapsed / 60000) + prevMinutes) % 60;
                seconds = ((timeElapsed / 1000) + prevSeconds) % 60;
                milliseconds = (timeElapsed + prevMilliseconds) % 1000;

                setStopwatch(hours, minutes, seconds, milliseconds);
            }, 25);
        }

        // Split out timer functions into functions.
        // Easier to read and write down responsibilities
        function run() {
            running = true;
            runTimer();
            toggleElement.text(pauseText);
        }

        function pause() {
            running = false;
            clearTimeout(timer);
            toggleElement.text(resumeText);
        }

        function reset() {
            running = false;
            pause();
            hours = minutes = seconds = milliseconds = 0;
            setStopwatch(hours, minutes, seconds, milliseconds);
            toggleElement.text(startText);
        }

        // And button handlers merely call out the responsibilities
        toggleElement.on('click', function () {
            (running) ? pause() : run();
        });

        resetElement.on('click', function () {
            reset();
        });

        // Another advantageous thing about factoring out functions is that
        // They are reusable, callable elsewhere.
        reset();
        if(running) run();
    });

});
</code>
DEMO HERE
Comment: thanks but i want single interval and function for multiple stopwatches, i do not want to write functions and set intervals multiple times
Comment: SEE this link https://www.sitepoint.com/online-jquery-stopwatch/ @shivchhabra
Comment: thanks @Ivin raj using your answer i will try to code this myself, it was a help, thanks.
Comment: welcome sir @shivchhabra

multiple stopwatch in jquery


Character occurrence in string (Case Sensitive)

Question: A string is passed as input, an integer denoting the alphabetic position value, And a character 'u' or 'l' which denotes upper or lower case are passed as input. The output should give the number of N value alphabet (case sensitive) occurrence.
Code is working, 3 Hidden test cases passes and 3 Hidden test cases failed out of 6 hidden test cases. Please do help !! :(
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int N,Count=0,i,len;
    char Ar[26]={'a','b','c','d','e','f','g','h','i','j','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'},M,Str[1000];
    scanf("%[^\n]",Str);
    //printf("%s",Str);
    scanf("%d ",&N);
    //printf("%d",N);
    scanf("%c",&M);
    //printf("%c",M);

    len=strlen(Str);
    if(M=='L' || M=='l')
     {
        for(i=0;i<len;i++)
        {
            if(Str[i]==Ar[N-1])
            {
                Count++;
            }
        }
     }
    else if(M=='U' || M=='u')
    {
        for(i=0;i<len;i++)
        {

            if(Str[i]==toupper(Ar[N-1]))
            {
                Count++;
            }
        }
    }
    if(Count==0)
    {
        printf("-1");
    }
    else
    {
        printf("%d",Count);
    }

}

Comment: if you have failing test cases, then they should point you to the problem. What do you mean by "hidden" test cases ?
Comment: @VishnuPriya : I didn't downvote, nor am I here to do your work for you. If you have a specific question, you'll have a better chance of getting help.
Comment: In your array, the letters h, i and j are duplicated, so a test case where `N > 10` will not work. You should also check whether the index N is valid.
Comment: Sir, we're given chance to review the hidden test case with points. But, it's too complex. Can you please try to find what's wrong with the logic instead of down voting?
Comment: Could you provide a sample of input and expected output? What do you mean with "reviewing the test case with points"? Are the test cases too complex for you?
Comment: Please show at least some examples of input and expected and actual output.
Comment: Maybe not directly related to your problem: Instead of `char Ar[26]={'a','b','c','d','e','f','g','h','i','j','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'}` (which is wrong BTW, there is at least a duplicate h, unless it is intentional, but then you shoud put a comment), you should generate the array dynamically with 2 lines of code.
Answer: @VishnuPriya , I think the mistake is with your array char Ar[26] .Few characters are repeating in that array *('h','i','j')*.
Modify the array to :-
char Ar[26] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j','k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}

Make sure that none of characters are repeating.


How to configure log4net for WCF

Question: On my asp webforms app I would do the log4net initialization;
log4net.Config.XmlConfigurator.Configure();

on global.asax on Application_Start so that it is done once when the application starts.
What is the right way of configuring log4net for IIS hosted WCF apps(asking specifically about where to place this line which event to use etc) so that log4net gets initialized once on and there is no unnecessary initializations.
Answer: I usually do this in the constructor of my service class, but I check if log4net is already configured:
if (!LogManager.GetRepository().Configured)
{
  // configure log4net...
}

I think if you really want to avoid this you would have to write your own service factory and perform the configuration there.
Answer: Same thing: Application_Start. After all it is an ASP.NET application. For self hosting services you could configure log4net just before starting the host.
Comment: I added a global.asax and enabled ASPNetCompatibility through webconfig and service attributes. I currently get a hit on Application_BeginRequest and Session_Start but Application_Start never gets hit. Any idea why this would happen? I kill all w3wp before debugging to make sure application is starting for first time..
Answer: Adding:
XmlConfigurator.Configure();

to the constructor of each of service classes did the trick for me.
Comment: To improve the quality of your post, please include how/why this code will solve the problem.

How to configure log4net for WCF


Rails. a href=#page deactivates javascript

Question: I'm having trouble to find the correct way to do this. In my landing page I got a inner link like this:
Destacados

When I click on it, the page go to the #destacados id, but all the javascript stop working, so the carrusel just dies. I'm not sure if this can help, but when I click the link, the address bar change to /myapp/#destacados ... may be it has trouble routing that...  any idea??
Thanks
Answer: Can you show how you are binding the click event to your  ?
Just tested with JQuery (could be without)
Go To Destacados Section

The focus goes to the anchor and clicked is printed


Why doesn't my wallpaper show up

Question: I'm using ubuntu 13.10 x64, I don't know why but my wallpaper doesn't show up.
How can I fix this problem? Thanks.

I run this command: gsettings set org.gnome.settings-daemon.plugins.background active true and now I can see my wallpapter, but the system runs very slow, please see the top command:

It seems like the ibus using a lot of CPU recourse , is this normal?
Comment: Does the desktop work at all? Can you right click it?
Comment: Hi @Oli, I can not right click it, but I can run other programs OK, but program shows up very slow.
Comment: That suggests Nautilus isn't running. That's what normally manages the desktop. Does Nautilus work otherwise? Can you browse your files, etc?
Comment: I don't use Nautilus, I use nemo, because Nautilus run very slowly on my laptop, I can use Nemo to browse files, it works well.
Answer: Judging from your comments, you've removed Nautilus and as I explained in my comments, Nautilus is what manages the desktop (and wallpaper) in Ubuntu.
The easiest fix is just to reinstall Nautilus. You don't have to use it for anything but managing the desktop.
The harder route is getting Nemo to manage your desktop. This post seems to suggest that this is all that's required but I find it hard to believe:
gsettings set org.gnome.desktop.background show-desktop-icons false
gsettings set org.nemo.desktop show-desktop-icons true

Comment: Thanks @Oli, I tried those command, now it seems everything is OK.
Answer: Run the below command on terminal to enable desktop wallpaper,
gsettings set org.gnome.settings-daemon.plugins.background active true

Or
Install Ubuntu-tweak-tool.From that turn on desktop icons which in turn enables the desktop wallpaper.Run the below commands to install ubuntu-tweak-tool in Ubuntu 13.10,
sudo add-apt-repository ppa:tualatrix/ppa
sudo apt-get update
sudo apt-get install ubuntu-tweak

Why doesn't my wallpaper show up


Resize DIV from either side, not just the corner

Question: I want to resize a DIV, from anywhere, and not just from the corners.
I used css code:
resize: horizontal;

My div, look like this

But I want something, Like this (resize like sulime text)

Is there any way to do this, like some javascript function?
Answer: Try the following
resize: both;
overflow: auto;

It will let you resize the div both horizontally and  Vertically from Bottom Right Corner.
Hope this might help to some extent.
Comment: They want to drag and resize the div by the edges, not just one corner.


Prove that $\sum_{j=1}^{\infty} \frac{(-1)^{j+1} x^j}{j^2}$ is positive for $x \in (0,1)$

Question: If $x \in (0,1)$, then
$$\sum_{j=1}^{\infty} \frac{(-1)^{j+1} x^j}{j^2} >0. $$
How to prove this in an elementary way (without using properties of the polylogarithmic function $\text{Li}_2(-x) = - \sum_{j=1}^{\infty} \frac{(-1)^{j+1} x^j}{j^2}  $)?
Comment: For $x\in (0,1)$, you mean? (not arbitrary $x>0$). That's only an idea, but have you considered deriving the series to get a known and more "handlable" function as the derivative, something like $-\ln(1-x)$?
Answer: Notice that the series is absolutely convergent, so all rearrangements are equal.
$\sum_{j=1}^\infty a_j =\sum_{j=1}^\infty \frac{(-1)^{j+1} x^j}{j^2} = \sum_{k=1}^\infty \left( \frac{x^{2k-1}}{(2k-1)^2} - \frac{x^{2k}}{(2k)^2} \right) = \sum_{k=1}^\infty b_k$
Clearly $b_k > 0$ for each $k$, so $\sum a_j$ is a series of positive terms, therefore $\sum_{j=1}^\infty a_j >0$.
Answer: For $x\in (0,1)$ the sequence $a_j= \frac{(-1)^{j+1}x^j}{j^2}$ ist alternating and decreasing and $a_1>0$. Thus $\sum_{i=1}^\infty a_j>0$.


Trying to figure out 'C' wire

Question: I'm looking to upgrade my programmable thermostat to a wifi thermostat.  I purchased a basic Honeywell wifi thermostat but upon installation could not find a 'C' wire.  I started to investigate more closely to see if I had an extra wire or if I had to run a new one.
From the pictures attached, I investigated further and at the furnace there is a 'C' wire hookup with a wire, but I can't seem to tell where it ends on the thermostat.  if the 'red' 'C' wire from the furnace is the same 'red' wire down at the furnace that is split with the 'white' wire, you'll see that it connects:
Thermostat:
red -> blue
white -> black
Its a bit confusing since I would think the red wire is the 'C' wire but I don't know if I should disconnect it or run another wire to hook up to the thermostat.
help!
Answer: I'm not sure exactly what's going on with the wiring, since in the one photo there's a giant ball of wires and cables, and in another there's extra wires hooked up. Here's what I see in the photos you've posted.

In this photo, you'll notice the cable with a red and white wire. That cable should go between the furnace and the A/C unit. The white wire from the cable is connected to Y, while the red wire is connected to C.
The other cable I've labeled should go to the thermostat. The wires from that cable should be connected as follows:

White to W
Green to G
Yellow to Y
Red to R

It's difficult to tell if that's what's going on, due to the big mess of wires and cables in the middle of the photo.
Also take note of the blue and black wires, that are wrapped around the thermostat cable.

In this photo, the cable coming from the furnace looks completely normal. However, there seems to be an extra cable that comes from who-knows-where. It appears that the wires from this mysterious cable, are connected to the blue and black wires that at the furnace are wrapped around the thermostat cable.  Which if that's the case, they're doing nothing.
It's possible that you might be able to attach the blue wire that is wrapped around the thermostat cable, to the C terminal at the furnace. Then attach the blue wire at the thermostat, to the C terminal on the thermostat. Though without knowing what the mysterious cable at the thermostat is, there's no way to be sure.
I wasn't able to decipher the diagram on the wall behind the thermostat, so I'm not sure what that's all about. I'm sure it meant something to whoever drew it, but it's not helpful to me.
I'm not sure if you have multiple A/C units, and the extra cable is used to control that. You'll have to investigate further, to determine what exactly is going on with that.
Comment: Thank you! To answer some of your questions here is what I've deduced: At the furnace, the ball of mess is mostly extra wire.  Essentially there are 4 cables: 1. normal 18/5 2. 18/2 R/W and 3. black #1 going off to the right 4. black #2 going off to the right
Answer: If I had to guess I would say that the red/white pair go off to a separate (maybe replacement) transformer was added.  Kind of like the transformer you often see sitting around in an attic or crawlspace that powers a doorbell.  If you meter across those two wires, I'm guessing you will find around 24 volts AC.
Such a transformer is usually built into the furnace unit, but maybe that one went bad and somebody just made a MacGuyver style repair.
Here is some "supporting info" on C wire I wrote a while back.  Maybe it will help you sort things out...
(note that someone seems to have partially ignored the conventional wire coloring in your installation...fortunately, electrons are color blind)
The lowdown on C wire
This is my attempt to "demystify" the whole "C" wire thing for non-technical folks. This explanation intentionally ignores lots of details that are not relevant to a basic understanding of the concept.
An old-timey thermostat is mechanical in nature. You can think of it very much like 3 separate mechanical on/off switches. (the "switches" in this case are mechanically actuated by temperature using springs and tilting glass bulbs full of mercury and other old-timey mechanical mechanisms)
The circuit is actually VERY simple. The old-timey thermostat switches on and off the "juice" which comes in on the RED wire...separately on and off to each of the other 3 wires (often green for the fan, white for the heat, and yellow for the AC).
That's all the old-timey thermostat does. Hook or not hook the red wire to each of the other three as needed.
Modern thermostats control your HVAC system with the same connections. They do the same thing...hook the red wire up to the proper green/white/yellow to turn various parts of you HVAC on and off as needed.
Since the old-timey thermostats were mechanical in nature, they didn't need any juice of their own to operate. If you think of a modern thermostat as an old-timey thermostat plus a smart phone stuck to the wall right next to it...you need something to power the smartphone. (some "kind of modern" thermostats have batteries in them for this purpose...to power the "smarts")
The red wire brings juice into the thermostat...but there is no "ground wire". Our "smartphone stuck on the wall next to the old-timey thermostat" needs both a "hot wire" and a "ground" (or "common"). (again, this is simplified so as to not get lost in irrelevant details and confuse the non-technical readers this was written for)
The "C Wire" (often blue) is this additional "ground wire" needed in order to complete a circuit for the electronics (which old-timey thermostats didn't have). The "other end" of the C wire is hooked to the other side of the transformer that supplies juice to the R or red wire. It is the other wire needed by the electronics in the newer thermostats in order to power up their "smarts".
Hope this helps a few people understand what the C wire is about.
Comment: Any input on this diagram I did based on what I found? ![diagram](https://farm1.staticflickr.com/358/20183911732_8e4aa76354_b.jpg)
Comment: All possible disclaimers apply.  It is clear that your wiring has been "messed with" several times by different people.  Despite all the disclaimers, my "guess" would be that the "red" wire in the "red/white pair" could be used as a C wire.  Before trying that I would put a meter between the actual RED wire for the thermostat, and that red in the red/white pair and see if it is about 24V ac.  If it is, then run the system through all of its paces (heat cool fan etc.) and verify that it never changes that voltage significantly.  If you see that, it will probably work fine for you.

Trying to figure out 'C' wire


Nested Sections in web.config

Question: I need to create nested sections in my Web.config file, i can't find any examples that match my requirements.
<IPTests>
    <Environment environment="DEV">
      <Machine machine="Web01">
        <SiteIP site="Sitecore" ip="10.10.2.191">
        </SiteIP>
      </Machine>
    </Environemnt>
</IPTests>

This is used for a "Health Check" for different applications/sites. I need to check all of the resources that different sites use are working. I've done this already using DNS, however i now need to do it in our different environments for our different servers by hitting the different servers with an ip address.
Any help would be great!
This is what i have thus far.
public class IPTests : ConfigurationSectionGroup
    {
        [ConfigurationProperty("codeEnvironment")]
        public CodeEnvironmentSection CodeEnvironment
        {
            get { return (CodeEnvironmentSection)base.Sections["codeEnvironment"]; }
        }
    }

    public class CodeEnvironmentSection : ConfigurationSection
    {
        [ConfigurationProperty("environemnt")]
        public ValueElement To
        {
            get { return (ValueElement)base["environemnt"]; }
        }
    }

    public class MachineSection : ConfigurationSection
    {
        [ConfigurationProperty("machine")]
        public ValueElement To
        {
            get { return (ValueElement)base["machine"]; }
        }
    }

    public class SiteIPSection : ConfigurationSection
    {
        [ConfigurationProperty("site")]
        public ValueElement To
        {
            get { return (ValueElement)base["site"]; }
        }

        [ConfigurationProperty("ip")]
        public ValueElement To
        {
            get { return (ValueElement)base["ip"]; }
        }
    }

    public class ValueElement : ConfigurationElement
    {
        [ConfigurationProperty("value")]
        public string Value
        {
            get { return (string)base["value"]; }
            set { base["value"] = value; }
        }
    }

Comment: [What have you tried](http://mattgemmell.com/2008/12/08/what-have-you-tried/)?
Comment: i've been trying to use this previous example: http://stackoverflow.com/questions/5027284/nested-configuration-section-app-config  however i can't get it to work becuase of my multiple nests
Answer: Have a look at the Configuration Section Designer.  I used it to generate configuration classes and then spent some time understanding the APIs and design.
Answer: It looks like you're trying to store a database of information in your web.config. If this is likely to change at all then you shouldn't store it here.
The problem is that any change to the web.config will cause your website to restart and reset the users session cache, etc.
If you are committed to adding your own sections then you can do this by creating a custom ConfigurationSection class:

http://msdn.microsoft.com/en-us/library/system.configuration.configurationsection.aspx

You can search the web for more info on this as there are quite a few tutorials out there.
Comment: i'm running resource tests on different services, databases, folders ect. and i need to run these tests on different ips (it's a health check test if you will). And the information doesn't change that often, but if it does it needs to be easily changed, that's why it's in the web.config file.
Comment: fair enough, you could just put it in an xml file which easily supports nested elements - depends how annoyed you are with the `ConfigurationSection` class yet :)
Comment: very very annoyed lol, but i'm just a newbie intern, and this is how my supervisor wants it :/

Nested Sections in web.config


Lost Items through the Postmaster in Destiny?

Question: I just completed a strike mission and after returning to the tower the postmaster had an item for me, under the heading "Lost Items", a decoherent engram.
Did this engram drop during the strike and I just didn't notice it, is that why it is at the postmaster, or is it an extra reward for doing the strike? If it is because it dropped during the strike and I didn't pick it up, will all such engrams end up at the postmaster?
Answer: Yes, this item dropped during the strike and you missed it.
Any drop higher than green will be at the postmaster when you return to the tower if you missed them in the field, not just on strikes.
Answer: I believe that they are also items that you can't pick up. I found a color shader at the lost items once. I just got done with a raid and it showed I got two shaders. I checked my shaders and I had one new one and I was at full. Then I went to the tower and found a shader at the postmaster.


How to get Firebase Token in android activity?

Question: I am using setToken(FirebaseInstanceId.getInstance().getToken()) code to get the token but I am getting the following error
java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/android/gms/common/util/zzv;

build.gradle
dependencies {
    implementation 'de.hdodenhof:circleimageview:2.2.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.squareup.retrofit2:retrofit:2.4.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
    implementation 'com.squareup.okhttp3:okhttp:3.10.0'
    implementation 'android.arch.lifecycle:extensions:1.1.0'
    implementation 'com.google.firebase:firebase-auth:16.0.5'
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    annotationProcessor "android.arch.lifecycle:compiler:1.1.0"
    //noinspection GradleCompatible
    implementation 'com.android.support:recyclerview-v7:28.0.0-rc02'
    implementation 'pub.devrel:easypermissions:0.4.0'
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support:design:28.0.0-rc02'
    implementation 'com.google.firebase:firebase-messaging:11.8.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

    implementation 'net.bohush.geometricprogressview:geometricprogressview:1.1.1'
    implementation project(path: ':andoird-sdk')
    implementation project(path: ':opentok-android-sdk-2.16.3')

    implementation 'com.android.support:multidex:1.0.3'
}

apply plugin: 'com.google.gms.google-services'

The above code is my build.gradle. Help me to fix the issue.
Comment: I don't know what it is
Comment: Did you use latest version of `gms:google-services`? can you share `build.gradle` files?
Comment: @javadroid I have edited my question. Please look into it
Comment: Have you implemented a service tag in the Manifest file? @deluxan
Comment: Are you using proguard?
Answer: you need to use FirebaseMessagingService to get token .. you will get token into its own method
public class MyFirebaseMessagingService extends FirebaseMessagingService {

@Override
    public void onNewToken(final String token) {

/// you will get token here you
    enter code here

}

}

Comment: Now I am having new error `error: cannot access zzbfm`
Answer: First of all fix version of all firebase library to latest version.
you cant mix versions <= 12 and versions >= 15 of Firebase libraries as mentioned here
then check you have properly enable Multidex on your project. Enable multidex for apps with over 64K methods
then use build -> clean to cleanup your project and dependencies.
and for using token use the way of @sonali:


Where are Pey'j's shoes and desk?

Question: If anybody remembers playing Beyond Good & Evil a while ago, maybe you can help me.
I've just finished going through the Slaughterhouses, and am now told that I need to find the ship that Pey'j hid somewhere on the Home island.  I've found the two hidden consoles beneath the boards depicting blueprints for Pey'j's Jet Boots, but I don't have the codes.  Various elements seem to suggest that the codes are what was written on the bottom of Pey'j's shoes earlier in the game.

Upon reviewing my collection of Mdisks, I recalled that during the factory mission, a security camera picked up footage of the captive Pey'j.  A guard mentioned that his jacket and shoes had been confiscated, and placed in "The Locker".  However, when I returned to the factory, I found myself unable to find my way to any kind of locker at all.  How do I get Pey'j's shoes back?  Was this something I was required to do during my first visit to the Factory, before destroying the elevator, thus rendering it inoperable in future visits?  Did I somehow miss them, and now cannot complete the game?
In addition, the message given to Jade on an Mdisk indicated that "Check-Up" information regarding the Beluga (the ship) can be found on his desk.  Where is this desk?  I've been all over the Home Island with no success.
Comment: In case anyone is wondering, although this question is tagged 'spoiler', I am **not** asking for the codes themselves, merely how to proceed in the game.
Answer: You needed to pick them up whilst still in the factory. Sorry
They should be right after you find the Mdisk
His desk will be under the lighthouse, although I suspect they will be on the walls with the blueprints.
Comment: If you can't get back,  I think the codes change on every file, so load an old save
Comment: It turns out I already had them anyway, but thanks for the heads up, and thanks about the desk.  :P

Where are Pey'j's shoes and desk?


Does touchpad indicator work in Ubuntu 15.04?

Question: I have just tried to install touchpad indicator in Ubuntu 15.04 with these instructions:

Touchpad indicator is developed by atareao team, available in the PPA for Ubuntu 14.04, Ubuntu 13.10, Ubuntu 12.04. To install it, press Ctrl+Alt+T on keyboard to open terminal. When it opens, run the commands below one by one:

sudo add-apt-repository ppa:atareao/atareao
sudo apt-get update
sudo apt-get install touchpad-indicator

I get an error message after launching it....the app closed unexpectedly. Why is that? It is no longer supported?
Does anyone know of a working alternative in 15.04?
Comment: I'm currently evaluating whether or not to install touchpad-indicator. I may not run into problems immediately (using 14.04-based Mint), but this may be interesting in the future. *Have you tried again? Did you find a replacement?*
Comment: It works fine in 14.04. Seems to be working fine in 16.04 too.
Answer: This has been solved in Ubuntu 16.04. The configuration file was not being created so you need to created yourself. To make it work in 15.04, run:
mkdir ~/.config/touchpad-indicator
touch ~/.config/touchpad-indicator/touchpad-indicator.conf
echo '{}' > ~/.config/touchpad-indicator/touchpad-indicator.conf

You can find that bug here. It does not show as solved, because the person behind that program does not seem to use Launchpad very much. It seems he prefers his own website.


How to perform another DB query in the same transaction in case of unique constraint violation in Java Spring @Transactional method?

Question: I am struggling with handling exceptions during transactional methods with Spring @Transactional annotations. Currently, when my Dao insert method throws a unique contraint violation, I want to perform a read instead to get the existing item. However, this fails because the UniqueIdViolation causes the transaction to fail. How can I refactor this to work as intended whilst not doing a dodgy boolean return on the insert?
I have a DAO with an insert method, e.g.:
public class ItemDao {

  public void insertItem(Item item) {
    // insert into db via jooq
  }

  public Item fetch(String id) {
    // fetch from db
  }
  ...
}

If it violates a unique constraint I have an aspect that handles the DataAccessException and rethrows it as a UniqueIdException.
I have a service method that takes in some information and creates an Item, before returning that item.
If the dao throws a UniqueIdException, I want the service to catch this error and then call itemDao.find() to get the existing Item and return it.
public class MyServiceImpl implements MyService {

  @Transactional(isolation = SERIALIZABLE)
  public Item createItem(...) {
    Item item = new Item(...);
    try {
      itemDao.insert(item);
      return item;
    } catch (UniqueIdException ex) {
      return itemDao.find(item.getId());
    }
  }
}

The issue here is when itemDao.insert(item) throws an exception this causes the transaction to fail and therefore itemDao.find() doesn't run.
Answer: @Transactional is setup to rollback, by default, only when an unchecked exception is thrown.
Since DataAccessException is unchecked exception your transaction will be rolled backed.
A better strategy will be to first call fetch() if returned null then call insertItem
Comment: Ah okay so I can't catch the DataAccessException to prevent the rollback?
I was trying to avoid calling fetch() (or some exists() method) first as this increases the amount of unnecessary queries.


Behavior of the resolvent near the boundary of the spectrum

Question: My question is, in some sense, a continuation of the question below.
Isolated singularities of the resolvent
Suppose $T\in B(H)$ has no eigenvalues, pick $x\in H$, $x\neq 0$, and consider the analytic function $R(\cdot, x):\rho(T)\to H$ defined as $R(\lambda, x)=(\lambda I-T)^{-1}x$ (the evaluation of the resolvent operator at $x$). Is it true that for any $x\neq 0$, we can find $\mu\in\partial(\sigma(T))$ (boundary of the spectrum) such that $R(\cdot, x)$ is unbounded "near" $\mu$?
The answer is positive, I think, when the spectrum of $T$ is finite (or even when it is a convergent sequence). This follows from the answer to the question linked above and it actually holds even without the condition on the point spectrum.
Also I can easily construct a counterexample when $T$ has eigenvalues. Take a bounded operator with the spectrum the unit disk and $0\in\sigma_p(T)$. Then for $x\in\ker(T)$, $R(\lambda, x)=\lambda^{-1}x$ and this is bounded near any point on the boundary of the unit disk.
Answer: Let $H^{2}(D)$ be the Hardy space of holomorphic functions on the unit disk $D$. That is, $f \in H^{2}(D)$ iff $f = \sum_{n=0}^{\infty}f_{n}z^{n}$ has a power series expansion in $D$ with $\|f\|^{2}=\sum_{n=0}^{\infty}|f_{n}|^{2} < \infty$. The shift operator $S$ defined by $(Sf)(z)=zf(z)$ is an isometry, i.e., $\|Sf\|=\|f\|$; and the spectrum $\sigma(S)$ is the closed unit disk $\overline{D}$. $S$ has no point spectrum.
Let $L^{2}(T)$ be the Lebesgue measurable, square-integrable functions on the unit circle $T$, and define $(Uf)(z)=\frac{1}{2}zf(z)$ for all $z \in T$. Then $\sigma(U)=\frac{1}{2}T$ consists of the circle of radius $1/2$ centered at the origin in the complex plane.
Let $H=H^{2}(D)\times L^{2}(T)$ and let $V(f,g)=(Sf,Ug)$. The spectrum of $V$ is $\overline{D}$, and $V$ has no eigenvalue. Furthermore, $(V-\lambda I)^{-1}(0,(U-\lambda I)^{-1}f)$ is uniformly bounded for $|\lambda| > 1$, regardless of $f \in L^{2}(T)$, which supplies a counter-example to your conjecture.
Comment: Concerning the finite spectrum case ... If $\sigma(T)$ is finite, and if $T$ has no eigenvectors, then, for each $x$,  $(\lambda I -T)^{-1}x$ has either an essential singularity or a removable singularity at $\mu \in \sigma(T)$ because a pole of order $k > 0$ implies $(\mu I-T)^{k}x=0$ but $(\mu I-T)^{k-1}x\ne 0$, which gives an eigenvector $y=(\mu I-T)^{k-1}x$ with eigenvalue $\mu$. If $(\lambda I - T)^{-1}x$ has an entire extension, then, because $(\lambda I - T)^{-1}x$ vanishes at $\infty$, you'll end up with $(\lambda I-T)^{-1}x =0$ everywhere, which forces $x=0$. You're right about this.
Comment: Isn't the above true regardless of whether $T$ has eigenvalues? $(\lambda I-T)^{-1}x$ cannot have an entire extension, therefore some isolated singularity $\mu$ is either essential or pole. Either case gives that $(\lambda I-T)^{-1}x$ is unbounded near $\mu$. This should work in the case when spectrum is a convergent sequence (the limit becomes isolated if all other singularities can be removed), or, even more generally, when we can remove all isolated singularities in finite number of steps. Hope this makes sense. Thank you for your counterexample.
Comment: My essential singularity remark was tangential to the issue. The real issue, as you point out, is that $(\mu I-T)^{-1}x$ cannot have an entire extension unless $x=0$. So, if the spectrum is isolated, there are interesting implications of this fact. Another side issue which is related: if $\oint_{C}(\mu I-T)^{-1}\,d\mu=0$ for some simple, closed, rectifiable curve in $\rho(T)$, then the interior of $C$ must be in the resolvent $\rho(T)$.


How do I cover large gaps of floor from wall with baseboard?

Question: I just installed laminate floors in my basement.
One wall (drywall) is not perfectly straight, leaving an area of the floor with a space as big as 1 3/4 inches from the wall.
I don't like the idea of rip cutting a laminate floor piece to a thin and long triangle shape to fill the gap.
What's an easy way of covering the gap?
Comment: If it was 3/4" to 1" max, you could get away with base trim and shoe or quarter-round, but not 1-3/4" - that's a huge gap.  Only option there would be to cover it with a couch or TV stand.
Answer: The easy way to cover the gap is to use your same flooring material. In this case the laminate flooring would be cut in a strip to fit the gap. Measure the gap width every 16 or 24 inches and transfer that to a flooring piece minus the normal wall gap clearance. Then cut the strip along a line through the measurements points and fit the piece in place.
Any kind of other strange scheme you come up with to avoid making the long strip is going to look terrible.
Comment: I also though of a few additional choice words I could have used in place of "terrible".
Comment: @RolloR - What tool did you use to cut the flooring when other runs came up to the wall? Use the same tool. As far as cutting the piece you may be able to clamp it to a piece of plywood set across two saw horses. Another scheme may be to clamp it between two pieces of plywood that have the edges aligned along the cut line. You could then run the saw blade right along the edge of the plywood pieces. If you do this you may want to use double stick tape to keep the piece in place against one of the two pieces of plywood.
Comment: A laminate floor piece with the shape of a right triangle, 1.25 x 16 x 16 inches does not sound fun to cut. Not to mention "clicking" it in place after everything is laid out already. I have a circular saw, a jig saw and a dremel. What would be the best tool?