Three way switch circuit leaking voltage

Question: I have a hallway light fixture controlled by three switches (panel -> 3 way -> 4 way -> 3 way -> fixture). Lights in this fixture routinely burn out within 6 months (incandescent, cfl and led -- all name brand).
The other night I noticed the LED lights had a very faint glow even though the power to the lights had been turned off for hours. I've removed the bulbs from the fixture and measured around 40 volts of stray power at the socket with the power turned off. Flipping a switch returns the voltage to 120. I tried all 8 combinations of switch positions and had the same results.
All three switches are non-illuminated "dumb" switches.
I then removed each of the switches and tested resistance with my multimeter. These are regular n-way switches, not smart or illuminated. The wiring in the boxes is textbook. They each show near 0 and '--' for resistance depending on the switch position.
I'm nearly certain each of the switches are still good but don't know where to go next in troubleshooting. What would cause the stray voltage? Is this likely what is killing light bulbs? Is this dangerous? How can I fix the extra voltage?
Comment: Put 1 bulb back in the fixture. Does that make the mystery voltage go away?  If it does, it's phantom voltage.
Comment: @EdBeal, I am in a rural suburb in Utah, United States. There are only residential homes on the substation grid my home connects to. The phantom voltage of 40V is measured with no bulbs in the circuit, with one LED bulb, the phantom voltage is 20V.
Comment: Are any of the switches illuminated? Other than that I agree with phantom voltages being observed.
Comment: @EdBeal All three switches are non-illuminated "dumb" switches. Updated question.
Comment: @Harper-ReinstateMonica With a single LED bulb in a socket, the voltage drops to near 20V on the other socket.
Comment: Good observation on the 20V. I updated my answer. There's not enough space here in the comments.
Comment: Where are you located? Not only country but city, rural, country? Are there any industrial plants in the area ?  If you can find an incandescent lamp to test to reduce the phantom voltage would better because LED's have driver circuits and may not fully turn on to dampen any phantom voltages, cfl's have ballast if the lamp is not ignited again the phantom voltage will be there.
Comment: @EdBeal Could adding a large resistor between the live and neutral contacts of the light fixture ground the floating volts? If so, what size of resistor (ohms and watts) would be recommended?
Comment: Actually it should not take much a lightbulb is basically a short your voltage cut in half with very little current draw. knowing you are in the US really eliminates the chance of 240v in a residential setting. I would drop a 1k in and your 20v will be gone. want to play it safe use 1.47k that will put you at just over 1/4 watt with 20 v but I think it is phantom and you could probably put a 10" ohm in there and the resistor won't get warm. The lines of force crossing a conductor creates a voltage this is how transformers work but the wires are close with many winds that's how you get power
Comment: Where does power (always-hot and neutral) enter this arrangement at?
Comment: @psaxton shunting the light wth a resistor might work. That's the dummy load idea to pull down the phantom voltage. You have to watch out for the wattage rating of the resistor. Even a 1K resistor will dissipate 15W at 120V (light on). It's not the 20V that's the concern. A 1/4W shunt resistor will fail or start a fire.
Answer: The 40V you are measuring is a typical value for a "phantom voltage". It is caused by capacitive coupling between wires, through the insulation, and usually in long runs of parallel wires AFTER the switch.
These couplings are high impedance and usually when connecting any load, the voltage will read 0. However, LED units (bulb & regulator) are high impedance loads at voltages below their operating voltage (e.g. 40V), and so it is possible they consume a bit of power even when the source is a phantom voltage. Regulators are notoriously short lived if they don't have enough voltage to work properly. Ironically, the transistors can overheat.
You can confirm this effect as follows: replace one of the lights with an incandescent (or add an incandescent to the load), and the voltage with the switch OFF should drop to 0.
Also, what voltage do you measure at the socket, when you disconnect the 3-way switch? And the other 3-way switch?
Your other point about the 6 month longevity with all bulbs usually suggests they are running at 240V rather than 120V due to mis-wiring somewhere. So to be sure: you are measuring 120V at the socket, between live and neutral (not live and ground), right?
And another check: you don't have weird issues when switching a 240V appliance on that suddenly lights get brighter, or circuits that don't work start to work? (This means that one of your two phases is not working correctly)
Update based on your 20V measurement: Yes by adding a load the voltage would drop, and since it drops by half (which is a lot), the phantom voltage remains suspect number 1 for the "faint glow". If you screw in something of higher wattage (20W...40W) like an old inc. bulb, I would suspect it to drop to 0V.
Are your LED bulbs dimmable? I appreciate that with your simple on/off switching the bulbs don't have to be dimmable. But, dimmable ones deal better with under voltage, they deliberately switch entirely off below a certain threshold, and that might help you here.
Update based on the LEDs being dimmable: The last thing I can think of is to try a different bulb / unit. Without cutting new holes for recessed/regulated systems, you could try a replacement just by wiring it up without installing it just yet. Not all LED bulbs and drivers are made the same, and you could get lucky (electrically, I mean).
The next solution would be to add a dummy load to the circuit after the switch. This is silly if you are trying to save power, but inc. bulbs are impossible to find. This is why we want to check the voltage (n OFF position) with a regular bulb (if you have one), to make the load a bit higher than with just under-driven LED lights.
Can you measure the voltage between the neutral and the ground, or the neutral and a neutral elsewhere in the house (use an extension cord). Let's eliminate a poor neutral as a possible cause too, since you have mixed problems.
The phantom voltage seems to be coupled after the switch, and so far we have the following possible solutions:

Move the wiring after the switch: this is lots of work, likely involves drywall repair, so definitely a last resort
Replace the lighting: this is a bit of a draw of luck, but some LED bulb & box regulators or integrated LED bulbs may have a threshold shutoff below which the LED switches itself off, rather than leaving it on, "leaking" and leaving a glow.
Insert a relay in the circuit right at the socket.

The relay has 120V switching poles (say 5A) and a 120V coil, and must be placed inside an electrical box. It will be wired so that the switch side of the relay simply connects the relay's feed to the bulb. It works as follows: if the voltage is too low, the relay is off, and the LED is cut off from the low voltage. If the voltage is high enough, the relay is on, and the bulb is fed the hight voltage.
There is the possibility that the relay too will switch on as a result of the phantom voltage. Should this be the case, we can experiment with a resistor placed before the relay, so that the relay's feed voltage (but not the LED's) is lowered enough to not trigger on the phantom voltage. It requires a bit of experimentation. Should you like this option, I can sketch you a diagram.
Comment: I doubt any 120v incandescent bulb would last more than a second at 240v.  LED drivers MIGHT be more adaptable if designed for it, but I doubt it.   And while I agree with most of your answer, technically phantom voltages in long, parallel runs are caused by induction, not capacitance.
Comment: @EdBeal I've had a mis-wiring and the CFL bulb lasted days on 240V as a work light before the issue was resolved, and the bulb still survived. As for the coupling, unless you are at the OP's home, you can't tell which dominates. Capacitive is my first suspect, but in his case the type of coupling does not matter. Not sure why all this nitpicking that is not helping the OP's cause. Why not submit a useful answer instead and help him along with his issue?
Comment: Thank you for the prompt response. I did not try measuring the voltage at the socket with the switches removed, assuming it would be 0 with the circuit physically broken (I was assuming a bridged contact in one of the switches at the time). I definitely measured 120V from hot to neutral (not ground) at the socket and don't have any problems with 240V appliances starting or stopping. I will try measuring the socket voltage with a switch removed tomorrow as well as pairing an incandescent with an LED bulb.
Comment: @GeorgeAnderson capacitive coupling is not uncommon, and induction could be part of it too. Cause doesn't matter here. Also 120V bulbs (inc. & CFL)  don't die immediately, and depending on their usage and the casual mentioning of 6 months I cannot dismiss this possible cause. However, the OP's double checking now confirmed this is not an issue.
Comment: I agree with George that residential voltage and currents it is inductive coupling. Doubtful it is 240v If a light works more than a second it is probably a universal voltage 90-277 with the LED's I purchase. Power spikes in the area are more likely the cause of short life electronics where a hole house suppression system added at the main panel has saved my customers thousands compared to what they were spending.
Comment: @P2000 The LED bulbs I've used are dimmable. The CFL bulbs I had used previously were not.
Comment: @psaxton Oh too bad, that would have been a solution to the problems. Let's see what other have to say about mitigating the phantom voltage. I'll update my answer with another possible solution.
Comment: @psaxton  depending on your level of skill, you could also insert a relay at the socket. See my updated answer. If this is something that interests I can walk you through it. You get to keep the bulbs and the wiring.
Comment: I measured the voltage from neutral (outer ring of socket) to the fixture and found 0V. Thinking back now, I'm not certain that the fixture is grounded. I'll check that at my next opportunity. Adding a relay or resistor or other combination seems within my skillset, but I'm afraid of it negating the UL certification for the fixture. Maybe there is a listed fixture or other device made for this scenario?
Comment: As for UL certification, it's good you pay attention to that aspect. These relays come in UL versions. Another trick is to buy a UL wireless relay & switch to switch power in/at (not to) the socket. Also, "the National Electrical Code (NEC) requires the use of UL listed products when available". Note the "when available".
Comment: I thought of a way to bond the open traveler wire to neutral. Could you tell me if [this solution](https://diy.stackexchange.com/questions/206471) is legal?
Comment: @psaxton I think the 470nF shunt capacitor (the MLC) proposed by ThreePhaseEel is your next best option to drain away the phantom voltage. It's used with dimmers that cause a similar phantom problem.
Answer: In this case you would be well off and more money ahead to rewire the system.first check inside of any junction boxes to make sure that you don't have any skinned wires. Phantom voltage is leaking voltage through the insulation of The wires, it could be fine for 200 years or it could eventually hit a ground and short the breaker. It is best to have an electrician come out and inspect your problem.


Finding square centers from a picture

Question: After an Image Processing, from fft's, filters, and thresholding, I obtained the following image:

So, I'm wondering how to extract those centers. Does exist any function from OpenCV? (such as HoughCircles for detecting circles?) or Do I need to use clustering methods?
Maybe it is useful for you to know the code I used:
import cv2
import numpy as np
import scipy.ndimage as ndimage
from scipy.ndimage import maximum_filter

img = cv2.imread("pic.tif",0)

s = np.fft.fftshift(np.fft.fft2(img))

intensity = 20 * np.log(np.abs(s))
maxs = maximum_filter(intensity, 125)
maxs[maxs < intensity] = intensity.max()

ret, thresh = cv2.threshold(maxs.astype('uint8'),0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
imshow(thresh)

PS: So I have another question, it could be useful for some of you. The maximum_filter function gave me the "3 squares"(then I'll get a better visualization of them by using thresholding), so is there a way to use the maximum_filter function and to obtain "3 circles"? Then we can use HoughCircles to obtain the 3 centers circles.
Answer: You may need to use Image Moments.
As the pre-processing steps, threshold the source to create mask of squares, and then pass to findcontours.

Finding square centers from a picture


duplicate columns header in data frame in R

Question: I have 4 duplicate column names in my dataframe. When I read the file, R automatically appends .1 or .2 to my duplicate columns
Original table -
Date       Temp Press Probability Press Probability
11/4/2015   100   45      0.65      55     0.85

What R is currently doing -
Date       Temp  Press   Probability  Press.1  Probability.1
11/4/2015   100   45      0.65           55     0.85

I don't want R to add .1 to my duplicate columns. Is there a way I can avoid that and keep my parameter name as-is?
Please advise
Thanks
Comment: How do you want distinguish between the 'same-name-columns'?
Comment: You can use `check.names = FALSE`, but it is bad practise to use duplicate column names.
Comment: Hi @jogo, I have address name that I attach to the parameter name after reading the csv file..hence that is being taken care of later in the script
Answer: When calling data.frame(), you can specify the parameter check.names = FALSE. Like in :
data.frame(foo = 1:3, foo = 2:4, check.names = FALSE)

However, it is often better to avoid duplicates in column names.
Comment: Hi @jlesuffleur, I have address name that I attach to the parameter name after reading the csv file.. Hence the issue with duplicate column names is being taken care of later in the script


A simple code that worked fine under GC but started crashing in ARC

Question: I have the following simple "check whether my app is set to launch at login" code. It worked fine under garbage collection. However, since I started using ARC (and inserted the "__bridge" as necessary), the code started randomly and unpredictably crashing. According to the stack trace, the code crashes during some CFRelease. Any ideas what might be causing this to happen under ARC?
- (BOOL)loginItemExists
{
  NSString *appPath = [[NSBundle mainBundle] bundlePath];
  LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL,
                                     kLSSharedFileListSessionLoginItems, NULL);
  BOOL found = NO;
  UInt32 seedValue;
  CFURLRef thePath;
  CFArrayRef loginItemsArray = LSSharedFileListCopySnapshot(loginItems,
                                                              &seedValue);
  for (id item in (__bridge NSArray *)loginItemsArray)
  {
    LSSharedFileListItemRef itemRef = (__bridge LSSharedFileListItemRef)item;
    if (LSSharedFileListItemResolve(itemRef, 0, &thePath, NULL) == noErr)
    {
      if ([[(__bridge NSURL *)thePath path] hasPrefix:appPath])
        found = YES;
    }

    //docs for LSSharedFileListItemResolve say we should release the CFURLRef
    if (thePath != NULL)
      CFRelease(thePath);

    if (found)
      break;
  }

  CFRelease(loginItemsArray);
  CFRelease(loginItems);
  return found;
}

Answer: You'll get a double-free here the second time through the loop if the item doesn't resolve. Set thePath to nil at the beginning and also after releasing it and that will fix the crash.
Comment: The argument to CFRelease must not be NULL, the test is required.
Comment: Would you say my `if (thePath != NULL)` check is unnecessary? I mean, is `CFRelease(NULL)` allowed? If it is, my check is probably unnecessary.
Answer: you could disable ARC by adding a Compiler Flag -fno-objc-arc to the specific file
Comment: Thanks for your suggestion. However, in this case I would prefer not disabling ARC, and instead try to understand where the problem is.
Comment: Besides, nothing is being managed by ARC anyway, since I'm doing regular `__bridge`. That seems to imply that the same problem would occur under manual memory management. The problem seems to be that it's the GC -> non-GC transition that introduced the problem. Not ARC per se.


How to present an Android project when only the layout has to be done

Question: I have to make a new design for an Android App, but I only have to create the visual part (native Android). The app logic would be created by another guy based on what I present to him.
My question is? How would this be managed correctly? Do I have to make the XML's of each layout? How could I show the other person my progress?
What things should I consider when doing this?
Thanks
Comment: Google provides lots of resources for mocking up an app before coding it. There are photoshop docs, icons, UI mockups, etc. See http://developer.android.com/design/downloads/index.html
Answer: Things You will consider when doing visual part:-
You have to work on the resource folder of your application

Layout : All Layout you have to prepare.
Drawable : Images and drawable .xml.

Inside Values folder you will find
dimen.xml : For different devices dimen you can set.
string.xml : You can store string for hint or other purpose.
style.xml : For designing or theme or custom design.
color.xml : Color which are going to used in the application.
Answer: you could create layout XML files for all the Activities/screens, using resources (icons, etc as suggested by @NoChinDeluxe). However since you'd want to run the mock app, you might want to also create a "throw-away" Activity that allows you navigate to different screens of the app. Here you can add a number of buttons and when you click on each button, your app shows a specific activity. This way, you will be able to show your colleague all the screens you have created. I hope this helps.
Answer: This may not be what you want to hear, but creating Android layouts isn't a design task. They are closely tied to the code, and the design of them is going to depend on how the engineer chooses to implement the app.
Here's an example. You might have a grid with 4 cells. You could use a RelativeLayout, a LinearLayout, or GridLayout, or a GridViewLayout. Which will use choose?
I'd suggest providing your engineer with mockups and graphical assets where required. Let him / her take those and create the layouts. If you want to create layouts as a (visual-only) reference for engineering, great, but it's certainly a non-optimal tool for that task.
Answer: You need to mock the app first (create a prototype) as suggested by NoChinDeluxe. Then if you guys go ahead and decide to code it, the answer to your problem is separation of responsibilities. As Jeffrey said UI work is not only about layouts, but code as well. What I would suggest is that you and the other guy get together first and define some contracts (interfaces) that will allow you guys to split the work and work in parallel. Therefore, he can create the business logic of the app without worrying about the UI implementation. You, on the other hand, will have to mock that business logic he's implementing at the beginning so it doesn't block your UI work.


Combining strings to make the shortest output

Question: I was looking for help on some pseudo code for my programming homework. The details are found here but to some it up: I receive strings from a file then I need to combine all of them into the shortest possible string. For example ABC AAB CAB could turn into AABCAB because the letters in the strings overlap.
 ABC
AAB
   CAB
------
AABCAB

I have troubles understanding what logic I can use for this problem. I've thought of splitting the strings by their length-1 until I get a single character then look for that same character(s) in other strings but it wouldn't work that well.
Comment: Take a look at this (identical?) question. You can pretend the Python is pseudocode. http://stackoverflow.com/questions/4697508/python-combining-strings-into-the-shortest-possible-string?rq=1
Comment: I think this is different @rajah9, if you read the answer to that question, and the link that OP posted here there is a big difference in requirement
Comment: This is actually a difficult problem. If speed is not an barrier, then you can just brute force all possible overlaps.
Comment: @Cruncher good point, and you made me slow down and read the OP's link. In the post that I referred to, one response cites the Needleman-Wunsch algorithm. This could be helpful to the OP. Also, the accepted answer has the code to turn ['toad', 'dog', 'rabbit'] into 'rabbitoadog'; I believe this would be a pretty good response to the base pair subsequences becoming "GATCGGCAGC".
Answer: This is rather inefficient but this should work:
String findShortestOverlap(String total, ArrayList<String> stringsLeft)
{
    if(stringsLeft.size() == 0) return total;
    String shortest = "";
    boolean first = true;
    for(int i = 0 ; i < stringsLeft.size() ; i++)
    {
         //combine stringsLeft.get(i) with total and call it newTotal. That is find the biggest overlap between these 2 strings.
         newTotal = findShortestOverlap(newTotal, /*copy of stringsLeft with the ith string removed*/);
         if(first || newTotal.length() < shortest.length())
         {
             first=false;
             shortest=newTotal;
         }
    }
    return newTotal
{

I haven't tested this. I would also assume more efficient algorithms exist, but this was my brute force shot at it.
Finding the biggest overlap between 2 strings should be an easy problem, which is what this breaks the problem down to.
The first call to this method should have "" as total.
The easiest way to gain some easy efficiency on this is to save a "global" variable outside of this function holding the "shortest" string found so far. Then only call newTotal = findShortestOverlap(...) if newTotal is shorter than the shortest string you found so far. This can cut a lot of brances off of the tree, and if you find a near-optimal solution early in the algorithm, it should go pretty quick from there.
Comment: Thank you for your response, ill be testing the code soon and ill get back to you. I'm also looking at the "identical question," thanks again guys.
Comment: @KhalobC edited with a potential idea for speeding it up a little bit.
Comment: using your code i got this as my output:
GATCCAGCATCGGCAGTCGG
AAACGTATCGATGCATTATCGATGCATCGATCCTTGCTGAAACGTATCAGCTTGCTGAAACGTA
Comment: @KhalobC Could you provide the exact code you're using? (perhaps a pastebin link)
Comment: @KhalobC `newTotal = stringsLeft.get(i) + total;` is not a sufficient implementation of "combine stringsLeft.get(i) with total and call it newTotal. That is find the biggest overlap between these 2 strings."
Comment: I've been trying to understand what you meant. Here is the code i currently have, am i headed in the right direction? Sorry im not the best programmer..

http://pastebin.com/B1vn4GCh


I need to stack multiple randomly colored rectangles in html canvas

Question: I want to have hella stacked rectangles that go to the center of the canvas and have them all randomly colored, but my code is wrong and isn't working.
Here is the code i have:
var ctx = canvas.getContext("2d");
var cornerpad = 0;
var rectwidth = 790;
var rectheight = 590;

function drawrectangles() {
    ctx.beginPath;
    ctx.rect(cornerpad, cornerpad, rectwidth, rectheight);
    ctx.fillStyle = 'hsl(' + 360 * Math.random() + ', 50%, 50%)'
    ctx.fill();
    ctx.closePath;
}

while(rectheight > 5) {
    rectheight =- 10;
    rectwidth =- 10;
    cornerpad++;
    drawrectangles();
}

I am pretty sure I made the while loop wrong since the random color works and the drawing rectangles works. Please help and explain what I did wrong
Comment: That's just a typo `ctx.beginPath` this is a method, you need to call it ( add `()` )
Answer: You had some mistakes in your code. First of all, you have rectheight =- 10; instead of rectheight -= 10. Your line of code is actually equivalent to rectheight = -10, so you are just setting both of the variables to -10, not decrementing them by 10.
Then, you used fill instead of fillRect. There is a fine difference between them, you may read more here or here. fillRect is a "stand-alone" command that draws and fills a rectangle. So if you issue multiple fillRect commands with multiple fillStyle commands, each new rect will be filled with the preceeding fillstyle.
For a nicer effect, I recommend using strokeRect instead of rect, but that's your decision. Also, you may want to play with the condition from the while, to actually make them appear centered.

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext("2d");

var cornerpad = 0;
var rectwidth = 790;
var rectheight = 590;

function drawrectangles() {
  ctx.beginPath();
  ctx.rect(cornerpad, cornerpad, rectwidth, rectheight);
  ctx.fillStyle = 'hsl(' + 360 * Math.random() + ', 50%, 50%)';

  ctx.fill();
  ctx.stroke();
}

while (rectheight > 5) {
  rectheight -= 10;
  rectwidth -= 10;
  cornerpad += 10;

  //console.log(`(h, w)=(${rectheight}, ${rectwidth})`);
  drawrectangles();
}
canvas {
  border: 1px dotted black;
}

<canvas id="canvas" width="790" height="590">
This text is displayed if your browser does not support HTML5 Canvas.
</canvas>

Edit:
I added a version that draws them much nicer, check it out :)

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext("2d");

var cornerpad = 0;
var rectwidth = 600;
var rectheight = 400;
var middleLine = rectheight / 2;

function drawrectangles() {
  ctx.strokeRect(cornerpad, cornerpad, rectwidth, rectheight);
  ctx.fillStyle = 'hsl(' + 360 * Math.random() + ', 50%, 50%)'
  ctx.fillRect(cornerpad, cornerpad, rectwidth, rectheight);
}

while (cornerpad < middleLine) {
  rectheight -= 20;
  rectwidth -= 20;
  cornerpad += 10;

  //console.log(`(h, w)=(${rectheight}, ${rectwidth})`);
  drawrectangles();
}
canvas {
  border: 1px dotted black;
}

<canvas id="canvas" width="600" height="400">
This text is displayed if your browser does not support HTML5 Canvas.
</canvas>

Cheers!
Edit 2:
Because I was too absorbed by the =- 10 thing, I forgot to point out to actually use beginPath and closePath as functions and to call them as ctx.beginPath() and ctx.closePath(). Thanks to Kaiido for pointing that out and for the two working additional jsfiddles.
Comment: @ShutUp Great! I edited my psot with a much nicer version, maybe you'd like that too :) Just play along with the numbers to make your desired effect. Cheers!
Comment: fill was just fine, the problem was that they didn't call beginPath
Comment: @Kaiido thanks for poiting that out. I added an edit to my post.
Comment: No, you didn't get it. beginPath works with fill(): https://jsfiddle.net/dyzm3wbu/ fillRect has its own [beginPath()rect()] and if you wish to stroke, you just have to call stroke https://jsfiddle.net/dyzm3wbu/2/
Answer: I believe your problem is laying in this expressions =- what you mean is -=. what you are doing now is setting rectheight value to -10 instead of reducing it by 10, thus your while loop just gets executed once.
Comment: thx for reply, i tried that and it did make the one rectangle that appears on screen bigger, but its still only one rectangle and i want hella
Answer: You missed some closing brackets and had the =- around the wrong way. I also change the rect to fill straight away.

var ctx = canvas.getContext("2d");
var cornerpad = 0;
var rectwidth = 790;
var rectheight = 590;

function drawrectangles() {
    ctx.fillStyle = 'hsl(' + 360 * Math.random() + ', 50%, 50%)'
    ctx.fillRect(cornerpad, cornerpad, rectwidth, rectheight);

}

while(rectheight > 5) {

    rectheight -= 10;
    rectwidth -= 10;
    cornerpad++;
    drawrectangles();
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

  <canvas id='canvas' height=590 width=790></canvas>

Comment: also thank u i just saw the other guys post first but u helped too


Why is everything taking so long to craft nothing?

Question: My workshop, as well as Nyok's house, is taking about two days to craft nothing. It doesn't tell what's being crafted and doesn't have a status bar above it. What's up with that?
Answer: This seems to happen when you change your device's system time. As a result of turning the time forwards, items speed up. Turning time backwards makes everything take longer. This concept is found in many games for handheld devices.


django rest detail_route testing

Question: Good day!
I have a view with detail_route like this:
class PostView(viewsets.ModelViewSet):
    queryset = Post.objects.all()
    serializer_class = PostSerializer

    @detail_route(methods=['POST'])
    def like(self, request, pk=None):
        post = self.get_object()
        post.like(request.user)
        return Response({'result': 'success'})

So, url for like function is /api/posts/{id}/like
I try testing it with django.test.TestCase like this:
post = Post.objects.first()
url = reverse('api:post-detail', args=[post.id])
url = urljoin(url, 'like')
response = self.client.post(url, content_type='application/json', follow=True)

I have to use follow=True because I get code 300 redirect, but redirect return me GET request when I need POST.
I have tried use APIClient and APIRequestFactory and got same error or myapp.models.DoesNotExist
Tanks for your attention!
Answer: The fact that you get a 300 at all should be a sign that you're doing something wrong.
Rather than reversing the main URL and then joining the detail route extension manually, you should reverse directly to the full URL you want. As the docs for detail_route show, that decorator gives you a named route in the form <model>-<detail-method>. So:
url = reverse('api:post-like', args=[post.id])
response = self.client.post(url, content_type='application/json')

django rest detail_route testing


URLs Not Allowed: Facebook PHP login

Question: I keep getting the following error

Given URL is not allowed by the Application configuration.: One or
  more of the given URLs is not allowed by the App's settings. It must
  match the Website URL or Canvas URL, or the domain must be a subdomain
  of one of the App's domains.

when I try to login a user with my PHP code snippet (see below). My Facebook settings are as follows:
App Domains: myappname-mynamespace.rhcloud.com www.myappname-mynamespace.rhcloud.com

Site URL: http://myappname-mynamespace.rhcloud.com/

Canvas Page: http://apps.facebook.com/myappname

Canvas URL: http://myappname-mynamespace.rhcloud.com/

Secure Canvas URL: https://myappname-mynamespace.rhcloud.com/

I've read similar questions here, here, here, here and here and they all seem to say the same thing: my Site URL (Website with Facebook Login) is incorrect.
But my Openshift URL is like this
http://myappname-mynamespace.rhcloud.com

so that's what I put in Facebook Site URL field. I have the following PHP code (index.php) in the root of my Openshift gear:
<?php
    require 'php-sdk/facebook.php';
    $facebook = new Facebook(array(
        'appId'  => 'xxxx',
        'secret' => 'xxxx'
    ));
?>
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Facebook PHP</title>

Hello World!

<?php
    // get user from facebook object
    $user = $facebook->getUser();

    if ($user): // check for existing user id
        echo '
User ID: ', $user, '
';
    else: // user doesn't exist
        $loginUrl = $facebook->getLoginUrl(array(
            'display' => 'popup',
            'redirect_uri' => 'http://apps.facebook.com/myappname'
        ));
        echo '
login
';
    endif;
?>

What am I doing wrong?
When I enter my Facebook app's URL (http://apps.facebook.com/myappname), Hello World! and my login link is display on top of my Facebook's app's iframe. However when I click on the login link, I get the above mentioned error. Any assistance will be greatly appreciated!
EDIT
I entered the following urls in my browser and Hello World and the login link were both displayed.
http://myappname-mydomainname.rhcloud.com/
https://myappname-mydomainname.rhcloud.com/

Comment: Everything looks fine. But just a shot in the dark: when I compare your configuration to mine, I would say you need to add a slash at the end of `http://myappname-mynamespace.rhcloud.com` as for the Site URL.
Comment: Some time its happen that whatever you make changes in FB settings will affect after some hours. so keep checking once you done changes.
Comment: @anthony I would suggest trying amazon AWS EC2. You need to know linux thought, but its very powerful and they give you a micro instance for free for a year, no obligations. I bet it is related to openshift, they have some funky redirects going on.
Comment: +1 Thank you for your reply @StéphaneBruckert I double checked my Site URL and I have a forward slash `http://fbtest-projectkohana.rhcloud.com/`. I'll correct my question. I may have put the `/` after writing this question but it still does not work. This is the second test app I'm writing which had produced this error. Is this problem related to my use of Openshift? Openshift uses shared SSL certificates for free accounts like mine.
Comment: +1 yes, I saw that message when I updated my facebook app. But it's been days now. Oh boy @Chandresh this has been a real challenge for me. I suspect it has to do with OpenShift shared SSL certs, I don't know. I'm trying to figure out another cloud provider I can use for free to test this out.
Answer: A while back I was tinkering with Facebook's API for whatever reason, I kept on getting the same error. Turns out some urls with http were supposed to be https, not that facebook made a point of leaving correct instructions.
I would suggest changing Site URL: http://myappname-mynamespace.rhcloud.com to Site URL: https://myappname-mynamespace.rhcloud.com. If this doesn't help I would suggest looking at the other URLs and changing them.
Good Luck
Comment: +1 Thank you so much for your reply. I changed my site URL (in FB configuration) to `https://fbtest-projectkohana.rhcloud.com/` saved it, then refreshed but I got the same error. However in the url of my browser, I noticed that the redirect uri had http, not https `...redirect_uri=http%3A%2F%2F...`. I changed the above mentioned script to use https instead and git pushed it to the Openshift server successfully and now I'm seeing `...redirect_uri=https%3A%2F%2F...` but I'm still getting the same error. Is this error caused by the shared ssl certificate  my free Openshift account/app uses?

URLs Not Allowed: Facebook PHP login


Mockito verify method was called with set, that contains specific value

Question: I want to be sure that mocked is called with specific set of strings as parameter.
For example, I have the following code:
public class SomeLogic {
    @Autowired
    private SpecificService specificService;

    public void action() {
        Set<String> args = fillArgsMethod();
        specificService.handleArgs(args);
    }
}

And my current try to test it is the following
@Mock
private SpecificService specificService
@InjectMocks
private SomeLogic someLogic;

@Test
public void testAction() {
    someLogic.action();
    verify(specificService).handleArgs(anySet());
}

But I want to be sure, that handleArgs() will receive the exact set of strings, that I expect. How can I modify verifying to check that handleArgs is called with set "first","second"?
Thanks
Answer: Isah gave a valid answer, but I want to turn your attention to a more general feature of Mockito which is ArgumentCaptor
In you case you would do something along the following lines:
Class<HashSet<String>> setClass = (Class<HashSet<String>>)(Class)HashSet.class;
ArgumentCaptor<Set<String>> setCaptor= ArgumentCaptor.forClass(setClass .class);

verify(specificService).create(setCaptor.capture());
HashSet<String> capturedSet = setCaptor.getValue();

//do whatever test you want with capturedSet

Comment: In this case it is probably overkill, but you get the general idea of how this is a more general solution :)
Answer: Prepare your Set parameters before calling the test method
    @Test
    public void testAction() {
        Set<String> expectedParams = new HashSet(Arrays.asList("first", "second");
        //call tested method
        verify(specificService).handleArgs(expectedParams);
    }

Comment: Thanks, I thought that I need Hamcrest methods, but the solution appeared to be much more simplier
Comment: You're welcome. I use Hamcrest because it has better matchers and better reporting when a test fails.
Answer: isah's solution is perfect for you if you want to confirm that the set contains exactly the two items you specify; Mockito compares using .equals by default, and Set.equals is defined as refer to equal elements in any order.
For a more-flexible "contains" test that matches your question title, that allows for set members beyond your expected values, you can also use the Hamcrest contains matcher:
someLogic.action();
verify(specificService).handleArgs(argThat(contains("first", "second")));

At least, that's how it should look. Unfortunately, argThat infers its return type from the Matcher, which infers its return type from the arguments, so Java assumes your first argument is not a Set<String> but a Iterable<capture#1-of ? extends String>. You'll need to cast explicitly and suppress warnings to get it to work:
// requires @SuppressWarnings("unchecked")
verify(specificService).handleArgs(
    (Set<String>) argThat(contains("first", "second")));


Deciphering Affine/Projective Transformation Code

Question: I've spent about 2 days trying to understand this piece of code (from here) that applies an affine/projective transformation to an image. I will link bits of the code that I'm struggling to understand and add comments on what I think it's trying to do. In particular, the author's original comments I'll label as //.
//      COMPUTE NEW BASIS
// X1, Y1 : upleft corner
// X2, Y2 : upright corner
// X3, Y3 : downleft corner
// sx     : x-size of output image
// sy     : y-size of output image
x12 = (X2-X1)/(float)(*sx);
y12 = (Y2-Y1)/(float)(*sx);
x13 = (X3-X1)/(float)(*sy);
y13 = (Y3-Y1)/(float)(*sy);

Q1. I can see that this part as the comment says, finds a new normalized basis but I'm unsure exactly why we need to find one to model an affine transformation?
// x4, y4 : downright corner (for projective transform)

if (y4)
{
    xx=((x4-X1)*(Y3-Y1)-(y4-Y1)*(X3-X1))/((X2-X1)*(Y3-Y1)-(Y2-Y1)*(X3-X1));
    yy=((x4-X1)*(Y2-Y1)-(y4-Y1)*(X2-X1))/((X3-X1)*(Y2-Y1)-(Y3-Y1)*(X2-X1));
    a = (yy-1.0)/(1.0-xx-yy);
    b = (xx-1.0)/(1.0-xx-yy);
}
else
{
    a=b=0.0;
}

After doing some internet search, I manage to find equations from here that the xx and yy equations solve for the "intersection point of two line segments in 2 dimensions". An image will be linked below.
START IMAGE.

END IMAGE.
Q2. I don't understand how he uses the xx and yy equations to solve for a & b?
Q3. I am unsure of what a and b are. My best guess is that they are the bottom row of a projective transformation matrix shown below:
$$
\begin{bmatrix}
a_{11} & a_{12} & a_{13} \\
a_{21} & a_{22} & a_{23} \\
a & b & 1 \\
\end{bmatrix}
$$
This is because the code sets a = b = 0.0 if we're not doing a projective transform, which should then make it an affine transformation matrix.
Now is where the main loop happens:
for (x=0;x<sx;x++)
    for (y=0;y<sy;y++) {
        fx = (float)x + 0.5;
        fy = (float)y + 0.5;
        d = a*fx/(float)(*sx)+b*fy/(float)(*sy)+1.0;
        xx = (a+1.0)*fx/d;
        yy = (b+1.0)*fy/d;
        xp = X1 + xx*x12 + yy*x13;
        yp = Y1 + xx*y12 + yy*y13;
    }

Q4. Why does he add 0.5 to the original x and y coordinate? My best guess is that the code's trying to map the centre of each pixel rather than the edge to the new image:

Q5. In
d = a*fx/(float)(*sx)+b*fy/(float)(*sy)+1.0;
xx = (a+1.0)*fx/d;
yy = (b+1.0)*fy/d;

what are they trying to accomplish here? My best guess is that d is the third component of the output homogeneous coordinate:
$$
\begin{bmatrix}
xx\\
yy\\
d\\
\end{bmatrix}
$$
calculated from the dot product of the third row of the (now normalised) transformation matrix from earlier and the input homogeneous vector:
$$
\begin{bmatrix}
\frac{a}{sx} & \frac{b}{sy} & 1 \\
\end{bmatrix}
\begin{bmatrix}
fx\\
fy\\
1\\
\end{bmatrix}
=
a*fx/sx+b*fy/sy+1.0
$$
Then the division
xx = (a+1.0)*fx/d;
yy = (b+1.0)*fy/d;

would just transform the homogeneous coordinates back to Euclidean coordinates, corresponding to the output image pixel location. I noted that if a=b=0.0 (so not projective), then (a+1.0)=(b+1.0)=d=1.0. I'm however not sure about why we have to multiply by (a+1.0) or (b+1.0). But again, I do not know if I'm on the right track or not as I do not have anyone to help me with this code.
Q7. The final operation
xp = X1 + xx*x12 + yy*x13;
yp = Y1 + xx*y12 + yy*y13;

I suppose is literally the dot product of the first two rows of the transformation matrix with the Euclidean coordinates as so:
$$
\begin{bmatrix}
x12 & x13 & X_{1} \\
y12 & y13 & Y_{1}
\end{bmatrix}
\begin{bmatrix}
xx\\
yy\\
1\\
\end{bmatrix}
=
\begin{bmatrix}
xp\\
yp\\
\end{bmatrix}
$$
Which brings me to my question, how does this achieve an affine transformation?
I suspect my lack of formal training could be why I'm not understanding how the code models an affine transformation. I'd appreciate some light shed on this piece of code!
Cheers!
Comment: An affine transformation is is any transformation that preserves points, lines and planes. This can be translation, skewing and rotation - and combinations thereof.
Comment: Hi @beyond, thanks for your input. Are you able to shed some light on the code?
Comment: To be honest, the code seems a bit elaborate for something as simple as applying an affine transformation to an image. The projection bit I don't get, so an example of input/expected output/actual output would be ideal.
Answer: Your understanding of the matrix structure in Q3 is correct. This code just does not construct a matrix explicitly and the matrix multiplication is applied implicitly. I think this part might cause your confusion.
Instead of deciphering the code, I would rather derive the transform and compare it with the code.
The affine (6 degrees of freedom) and projective matrix (8 dof) map points to points. So you can build a system of equations for each pair of points in different frames. You will need to solve this system for the components of the matrix (Q1).
Let $M$ be the transform matrix, then
$$
\begin{align}
M (0,0,1) &= (X_1,Y_1,1) \\
M (1,0,1) &= (X_2,Y_2,1) \\
M (0,1,1) &= (X_3,Y_3,1) \\
\end{align}
$$
Each of above lines gives you two equations. Now you have 6 equations and the affine matrix can be derived.
For the projective matrix, we need extra two equations using the point $(X_4,Y_4)$:
$$
\begin{align}
H_4 &= M (1,1,1) \\
\frac{H_4}{H_4.z} &= (X_4,Y_4,1)
\end{align}
$$
Note that I have to divide the homogeneous part for the transformed point.
Solve this linear system you can get an expression for your matrix $M$. Perform $M (f_x,f_y,1)$ you will see how it transforms the point. I believe this solves your Q2, Q3, Q5 and Q7.
For Q4, I think it is just a convention of pixel position and your understanding should be correct.

Appendix: maple code to verify the answer
with(ListTools):
# affine matrix
m:=<m11,m21,0|m12,m22,0|m13,m23,1>;
# Build equations
E:=[convert(m.<0,0,1> - <X1,Y1,1>,list),convert(m.<1,0,1> - <X2,Y2,1>,list), convert(m.<0,1,1> - <X3,Y3,1>,list)];
# E=[[m13 - X1, m23 - Y1, 0], [m11 + m13 - X2, m21 + m23 - Y2, 0],[m12 + m13 - X3, m22 + m23 - Y3, 0]]
# Solve E=0
sol:=eliminate(Flatten(E),indets(m));
# Plug the solution back to m:
subs(sol[1],m);
                           [-X1 + X2    -X1 + X3    X1]
                           [                          ]
                           [-Y1 + Y2    -Y1 + Y3    Y1]
                           [                          ]
                           [   0           0        1 ]

# projective matrix
p:=<m11,m21,a|m12,m22,b|m13,m23,1>;
# Compute transformed points
U0:=p.<0,0,1>;
U1:=p.<1,0,1>;
U2:=p.<1,1,1>;
U2:=p.<0,1,1>;
U3:=p.<1,1,1>;
# Build equations
E:=[convert(U0/U0[3]-<X1,Y1,1>,list),convert(U1/U1[3]-<X2,Y2,1>,list),convert(U2/U2[3]-<X3,Y3,1>,list),convert(U3/U3[3]-<X4,Y4,1>,list)];
# Sove E=0
solp:=eliminate(Flatten(E),indets(p));
# copy their code for xx and yy:
xx:=((X4-X1)*(Y3-Y1)-(Y4-Y1)*(X3-X1))/((X2-X1)*(Y3-Y1)-(Y2-Y1)*(X3-X1));
yy:=((X4-X1)*(Y2-Y1)-(Y4-Y1)*(X2-X1))/((X3-X1)*(Y2-Y1)-(Y3-Y1)*(X2-X1));
# Verify our a and b, compare ours with their expressing using xx and yy
subs(solp[1],a);
subs(solp[1],b);
simplify(subs(solp[1],a)-(yy-1)/(1-xx-yy));
# It is 0 as expected
simplify(subs(solp[1],b)-(xx-1)/(1-xx-yy));
# It is also 0


Better way to get int from FragmentActivity in a Fragment?

Question: Hi im trying to get an int from my FragmentActivity and i have a way to do this but the code get very cluttered and long and i did this to shorten the problem and i don't get any errors while in the editor but when i run the app it eminently crashes. Any suggestions?
An example of the code that doesn't work
MainActivity mainActivity = ((MainActivity)getActivity());

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.upgrades_fragment, container, false);

    TextView AirFreshenersCost = (TextView) view.findViewById(R.id.AirFreshenersCost );

    if(mainActivity.amountAirFresheners == 5){
        AirFreshenersCost.setText("5");
    }

    return view;
}

LogCat
10-27 22:16:37.333: E/AndroidRuntime(5593): FATAL EXCEPTION: main
10-27 22:16:37.333: E/AndroidRuntime(5593): java.lang.NullPointerException
10-27 22:16:37.333: E/AndroidRuntime(5593): at com.free.dennisg.clickingbad.fragments.UpgradesFragment.onCreateView(UpgradesFragment.java:40)
10-27 22:16:37.333: E/AndroidRuntime(5593): at android.support.v4.app.Fragment.performCreateView(Fragment.java:1478)
10-27 22:16:37.333: E/AndroidRuntime(5593): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:927)
10-27 22:16:37.333: E/AndroidRuntime(5593): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
10-27 22:16:37.333: E/AndroidRuntime(5593): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
10-27 22:16:37.333: E/AndroidRuntime(5593): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1460)
10-27 22:16:37.333: E/AndroidRuntime(5593): at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:472)
10-27 22:16:37.333: E/AndroidRuntime(5593): at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
10-27 22:16:37.333: E/AndroidRuntime(5593): at android.support.v4.view.ViewPager.populate(ViewPager.java:1068)
10-27 22:16:37.333: E/AndroidRuntime(5593): at android.support.v4.view.ViewPager.populate(ViewPager.java:914)
10-27 22:16:37.333: E/AndroidRuntime(5593): at android.support.v4.view.ViewPager$3.run(ViewPager.java:244)
10-27 22:16:37.333: E/AndroidRuntime(5593): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
10-27 22:16:37.333: E/AndroidRuntime(5593): at android.view.Choreographer.doCallbacks(Choreographer.java:562)
10-27 22:16:37.333: E/AndroidRuntime(5593): at android.view.Choreographer.doFrame(Choreographer.java:531)
10-27 22:16:37.333: E/AndroidRuntime(5593): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
10-27 22:16:37.333: E/AndroidRuntime(5593): at android.os.Handler.handleCallback(Handler.java:730)
10-27 22:16:37.333: E/AndroidRuntime(5593): at android.os.Handler.dispatchMessage(Handler.java:92)
10-27 22:16:37.333: E/AndroidRuntime(5593): at android.os.Looper.loop(Looper.java:137)
10-27 22:16:37.333: E/AndroidRuntime(5593): at android.app.ActivityThread.main(ActivityThread.java:5289)
10-27 22:16:37.333: E/AndroidRuntime(5593): at java.lang.reflect.Method.invokeNative(Native Method)
10-27 22:16:37.333: E/AndroidRuntime(5593): at java.lang.reflect.Method.invoke(Method.java:525)
10-27 22:16:37.333: E/AndroidRuntime(5593): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
10-27 22:16:37.333: E/AndroidRuntime(5593): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:555)
10-27 22:16:37.333: E/AndroidRuntime(5593): at dalvik.system.NativeStart.main(Native Method)

An example of the code that work
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.upgrades_fragment, container, false);

    TextView AirFreshenersCost = (TextView) view.findViewById(R.id.AirFreshenersCost );

    if(((MainActivity)getActivity()).amountAirFresheners == 5){
        AirFreshenersCost.setText("5");
    }

    return view;
}

Answer: You could store the int as a static variable on the MainActivity. Then, you could reference that instead of referencing a public instance variable.
if (MainActivity.AIR_FRESHENER_COUNT == 5) { ...
I think the reason for the crash is that you are holding a reference to the activity, and the activity can get created and destroyed even while your fragment lives on, so that reference might be null (it's hard to tell what exactly the NPE is on without knowing the line numbers from your original file).
Comment: Thanks, it's easier than `((MainActivity)getActivity()` :D
Comment: The answer of @atroutt is not a good idea really. It makes class design broken down.
Answer: I think you should define an interface to encapsulate your activity and fragment. As the concept of oop the activities should not know the details of her fragments and also the fragments should not know her mother activities.
Dummy:
Interface IGetNumber { int getNum();}

class MyActivity : IGetNumber

class MyFragment {
          IGetNumber mNumGetter;

         onAttach(activity){
                If activity is an IGetNumber {
                           mNumGetter = (IGetNumber)activity;
                 }
        }

        any method(){
                If mNumGetter is valid {
                         Call mNumGetter.getNum();
                 }

}


Fading particles and transition

Question: I'm trying to render a particle simulation. I want each particle to leave a trace. To achieve this I'm using a framebuffer and two textures. On each frame the algorithm goes like this:

Render to a framebuffer previously rendered screen texture with opacity * 0.9;
Render current particles at updated positions;
Switch to main display and render current content of the framebuffer;

This works fine, and I get nice looking particle trails:

Problem
I want to allow users to pan and zoom canvas with these particles, similar to a map interface. This is achieved by applying a transformation matrix to each particle.
I want to keep particle's state, but I don't want the pan/zoom to leave a particle trace:
Bad
Here I'm dragging canvas up and down with mouse cursor. See how particles leave a trace?

Good
Here I'm also dragging the canvas up and down, but particles remain on their trajectory, without leaving a pan trace:

I'm wondering what is a proper way of achieving this? I got a basic solution working by applying a transformation to a previous frame's texture, so that it approximately matches what will be rendered in the current frame, but I there still a few artifacts:

When zooming in, the updated texture "explodes":

I assume this is because I'm using fixed point size for a particle (regardless of the zoom level), but when we scale texture, we scale rasterized image, and thus all particles rendered on it also get bigger.

When a particle enters the scene (crosses the border of visible area), it is also very likely to leave a trail:

I'm not sure why this one happens. My screen/back textures are the same size, I'm just translating back texture. I thought it might be related to clamp_to_edge setting, but I don't know how to prove or validate this. I've got a workaround by extending canvas beyond visible area (say by 2%) and in the fragment shader I check that if particle is closer than 2% to the border - I give it transparent color. This kind of "fixes" the problem, but I feel uncomfortable not knowing why it's happening.

Finally, if transformation is very-very small (think kinetic movement), I also observe artifacts:

I'd appreciate if you could explain some of these artifacts, suggest possible solutions, or general practices used to solve this problem.
Comment: What do you expect to happen for #1? Your assumption is correct. If you're scaling the accumulation texture but not the particles, then it's going to get larger (or smaller) than the particle. What is the problem with #3? I don't see anything odd about it.
Comment: in #3 the original particle is not moving. So, when panning translation is applied, I expect both textures to have synchronized transformation, and no fading trail should appear. Yet you can see when translation is very small at the end - there is a fading trail around particle, as if transformations slightly misaligned
Answer: I made a visualization a little like yours years ago, and used a similar technique, because it's the natural approach to the problem. After I spent a few years writing drivers for modern GPUs, I wouldn't use this approach at all, because it creates a dependency from one frame to the next, which introduces pipeline stalls and/or false sharing.
Today, I'd keep the path of the particle as part of its state, and render the whole trail each frame, instead of reusing the old FBO. It's conceptually a little more difficult, and you have to be careful that the way you draw the past path is exactly the same each frame. For example, if you represent the path with some kind of cubic spline, you can't just move the final control point forward, because it'll change the whole curve slightly. A circular buffer of (x, y) positions would be much easier to get right.
What you get in exchange for this extra complexity is (a) reduced frame time, memory use, and power consumption (which might be important if you're on mobile), and (b) you won't have your current problem at all. Maybe the frame time advantage won't be as big in WebGL, because you'll end up doing extra work in Javascript, which is slow, but memory bandwidth is more of a bottleneck on most systems. Just make sure that the co-ordinates you store are in the space of your simulation, and transform them into screen co-ordinates when you draw them, just like you would with a 3D scene.
Comment: Thank you! I'm actually computing position of a particle on a GPU and encode it into texture. The formulas to find next particle position are quite involved, and I want to support 100k - 1,000k particles. If I'd have to recompute positions for last N steps, I'm worried that would impact frame rate a lot.
Comment: I was assuming you'd save the positions each frame rather than recomputing. An array of particle positions is much less state to pass around than a framebuffer.
Comment: Dan, but I don't think I'm passing a framebuffer. I just use two textures and constantly swapping them. Does this mean I'm passing a framebuffer? Also I tried to re-render last 10 -15 steps and take into account transforms - performance was not acceptable.. Maybe I'm doing something wrong
Comment: Dan, here is the project that I was working on: https://anvaka.github.io/fieldplay/ I can finally share it. The source code is here https://github.com/anvaka/fieldplay - this is vector field explorer/simulation. Maybe playing with it would give you better ideas of what I'm trying to do? If you don't have time for this - no worries!

Fading particles and transition


Django: Converting uuid value to a string in django template engine

Question: I have this code of line that I need to be up and running.

    {% if msg.sent_by_id == request.user.public_id|string %}
        {% if request.user.role == 'administrator' %}Admin Replied
        {% elif request.user.role == 'user' %}Your reply
        {% endif %}
    {% endif %}

The problem is that these two values are the same, BUT both of them are other format. msg.sent_by_id is a string, neither request.user.public_id, this value is in uuid format. What is the correct way of 'converting' an variable to a string and then comparing the two values?
Comment: `str (uuid)` in your view and pass the str version into your template
Comment: I'm passing the whole json object -`return render(request, 'service_desk/ticket_status.html', {'ticket': Ticket_obj, 'ticket_messages': Ticket_obj_messages})`
Answer: You could use the string format template tag https://docs.djangoproject.com/en/3.0/ref/templates/builtins/#stringformat
{% if msg.sent_by_id == request.user.public_id|stringformat:"s" %}


Private comments in JIRA issues

Question: I want to enable my team to add comments to issues that can only be seen by my team for the purpose of private conversations related to the issue. For example, to facilitate conversation about the technical requirements for fulfilling the request, or to allow new team members to comment "Hey Joe, I don't know how to do this, can you show me?", without the reporter being able to see those comments. I had this at a former employer, so I know it can be done, but I don't know how to set it up myself.
Comment: Isn't that a feature of Jira Servicedesk?  I don't believe the facility is available in Jira core or Jira Software.   Maybe a plugin: https://marketplace.atlassian.com/search?application=jira&category=&cost=&hosting=&marketingLabel=&q=comments
Answer: You can do this by setting the viewing restrictions while creating a comment. Your admin may also need to configure the comment visibility settings first.
Answer: I fixed this by creating a new Role of "Team Members", giving that Role the permissions to Comment, and then going into my project and defining that Role as my team's group. Now, when they comment they get the little open padlock icon under the comment that they can click and select "Team Members", and then only we can see the comment.

Private comments in JIRA issues


Minecraft [any version] - Flashing/Graphical Glitches?

Question: I recently reset my PC, and have noticed that since I have done so, Minecraft has been acting strangely. Whenever I play, the entire game window [GUI and all] flashes white for an instant. Or, the GUI will act up. It can be seen in this video. My specs are as follows.
Windows 8.1 Update 1
Intel i5-4200u processor
Embedded Intel HD Graphics 4400
8GB DDR3 RAM, ~7.88 usable
Java version 7 Update 67 [32- and 64-bit are both installed]
Also, Minecraft is currently set to use no more than 4GB of RAM.
Has anyone else had this problem, or have a solution? I really want to play but I fear something might irreversibly mess up or something.
Comment: My guess is there is something wrong with the drivers. Which ones are you using, the ones from Intel or from Acer?
Comment: @crayzeedude are the drivers not the standard ones you got with the pc?
Comment: People are going to ask for your Java version information as well.
Comment: I think they're Acer, but I'm not quite clear on it.
Comment: I don't believe they're not standard. I haven't done anything with my installed graphics drivers since the reset.
Answer: So, after a long hiatus, I finally decided to update my graphics drivers. This worked, and I can now play Minecraft like normal again.


Prestashop backoffice started loading very slow

Question: today my prestashop back office started loading really slow.
The information page in advanced parameters isn't even loading. It keeps trying to load and after a time it just timesout.
I enabled debug mode and noticed that TraceableFirewallListener takes a really long time to finish.
I disabled the api calls in class/tools.php but that did nothing to help.
    public static function addonsRequest($request, $params = array())
    {
        return false;

My prestashop version is 220.127.116.11
Answer: Remember that on 1.7 there's a second call to Addons API in src/Adapter/Addons/AddonsDataProvider.php you might want to disable it here as well.
Overall it would be extremely hard to help you without debugging your store directly


How to write a service class to return any implementation class object which implements interface

Question: I have a requirement to update number of records into a table in a single call from Java program. Simply it is JDBC batch update.
For this, I have this following code snippet at interface and implementation which is perfectly working.
interface TableABatchUpdater extends Logic<TableADTO> {
   void updateBatch(List<TableADTO> list)
}

class TableABatchUpdaterImpl extends AbstractLogic<TableADTO> implements TableABatchUpdater {
   @Autowired DAOClass dao;

   TableABatchUpdaterImpl(){
     super("TableA");
   }

   @Override
    void updateBatch(List<TableADTO> list) {
        dao.updateBatch(list)
    }

}
interface TableBBatchUpdater extends Logic<TableBDTO> {
   void updateBatch(List<TableBDTO> list)
}

class TableBBatchUpdaterImpl extends AbstractLogic<TableBDTO> implements TableBBatchUpdater {
   @Autowired DAOClass dao;

   TableBBatchUpdaterImpl(){
     super("TableB");
   }

   @Override
    void updateBatch(List<TableBDTO> list) {
        dao.updateBatch(list)
    }

}

interface TableCBatchUpdater extends Logic<TableCDTO> {
   void updateBatch(List<TableCDTO> list)
}

class TableACatchUpdaterImpl extends AbstractLogic<TableCDTO> implements TableABatchUpdater {
   @Autowired DAOClass dao;

   TableCBatchUpdaterImpl(){
     super("TableC");
   }

   @Override
    void updateBatch(List<TableCDTO> list) {
        dao.updateBatch(list)
    }

}

public class MyServiceClass {

  @Autowired TableABatchUpdater tableA;
  @Autowired TableBBatchUpdater tableB;
  @Autowired TableCBatchUpdater tableC;

  public void updateTables() {
     tableA.updateBatch(tableAList);
     tableB.updateBatch(tableBList);
     tableC.updateBatch(tableCList);
   }

}

The problem here is, when I would like to add batch update statements for another table called "TableD", MyServiceClass class dependencies are increasing and the complexity is very high interms of unit testing..etc. So, I tried to use one interface instead of independent interface for each table as follows. But, still I have to write many implementation classes for each table which I don't want.
interface BatchUpdater extends Logic<?> {
       void updateBatch(List<?> list)
}

I tried to write the implementations by using factory and composite patterns. But, none of them worked out.
Is there any other way in Spring to write a separate service class which will return as the following.
public class MyServiceClass {

    @Autowired BatchUpdaterService batchUpdaterService;

    public void updateTables() {
        batchUpdaterService.getTableUpdater("TableA").updateBatch(tableAList);
        batchUpdaterService.getTableUpdater("TableB").updateBatch(tableBList);
        batchUpdaterService.getTableUpdater("TableC").updateBatch(tableCList);
    }

}

Any response is highly appreciated
Comment: To understand , there are multiple implemenations of `BatchUpdater` and the requirement here is to programmatically call the corresponding implemenation based on the type of list , is it ? Also ,  within `MyServiceClass.updateTables()` how is `TableA`  bean and `tableAList` mapped ?
Answer: Well, I use a factory pattern with HashMap and reflections to instantiate like
public static class Factory{
    final static HashMap<String,Class<? extends MyAbstractClass>> supportedVersions = new HashMap<>();
    static{

        supportedVersions.put("v1", ClassV1.class);
        supportedVersions.put("v2", ClassV2.class);

    }

    public static MyAbstractClass getInstanceFor(String type) {
        try {
            return supportedVersions.get(type)
                    .getConstructor().newInstance("params");
        } catch (IllegalAccessException e) {
            throw new CustomException(HttpStatus.INTERNAL_SERVER_ERROR, "Something went wrong");
        } catch (InstantiationException | InvocationTargetException | NoSuchMethodException e) {
            throw new CustomException(HttpStatus.BAD_REQUEST, "Unsupported Version");

        }
    }
}


When should I spend money in Forza 3 Motorsport?

Question: I am getting by with just riding the gift cars, but it is really boring. I have 115k CR right now and at the start of season 2. When can I spend money such that I can buy a new car, and not have a good one for a while? In other words, when can I buy a car such that I can devote my entire time and earnings to it?
E.G. We can race class C cars now and I want an Acura NSX which is c class. But I dont want to buy it if next season I will be racing b-cars only.
Answer: With each season, you'll generally move on to the next class of cars for the championship events.
I'd suggest spending credits upgrading cars you win, rather than buying new ones. If there's a axe you really want though, then buy it and even if you don't get suitable races in the season play you may find some in event list. World tour, endurance, etc. races typically allow any car in a class to play.


R - use simsem within map

Question: I have a list of more than 100 SEM models computed in lavaan. For this example, I'm going to use just two models:
fit.model1.cfa <- '
    ind60 =~ x1 + x2 + x3
    dem60 =~ y1 + y2 + y3 + y4
    dem65 =~ y5 + y6 + y7 + y8
    ind60 ~~ ind60
    dem60 ~~ dem60
    dem65 ~~ dem65' %>%
       sem(PoliticalDemocracy)

fit.model2.cfa <- '
    ind60 =~ x1 + x2
    dem60 =~ y1 + y2 + y3
    dem65 =~ y5 + y6 + y7
    ind60 ~~ ind60
    dem60 ~~ dem60
    dem65 ~~ dem65' %>%
       sem(PoliticalDemocracy)

It's not that much important what the models actually are. Now we will join them in a list:
models <- list(fit.model1.cfa, fit.model2.cfa)

I want to do post-hoc power analysis on my models and for that purpose I am using the following for loop:
pwr <- list()

for(i in 1:2){
   sim(nRep = 1000, model = models[[i]], n = models[[i]]@SampleStats@ntotal, generate = models[[i]]) %>%
       getPower() -> pwr[[i]]
}

However, I would like to avoid the for loop and instead use the map function. I was trying the following:
models %>%
   map(., sim, nRep = 1000, model = ., n = pluck(pluck(., "SampleStats"), "ntotal"), generate = .) %>%
   map(getPower)

However, that is not working. So what am I doing wrong?
Comment: From which package comes the `sim` function?
Comment: @rdornas from the `simsem` package
Answer: This is the first time I heard about lavaan, simsem and its models, but I'm trying to help you with the purrr map. I made a simple solution with nRep = 10 just to test and you can replicate it with nRep = 1000. Also, lots of warnings and progress were returned, but I deleted them in the example below for the sake of cleanliness.
library(tidyverse, verbose = F)
library(lavaan)
library(simsem)

fit.model1.cfa <- '
    ind60 =~ x1 + x2 + x3
    dem60 =~ y1 + y2 + y3 + y4
    dem65 =~ y5 + y6 + y7 + y8
    ind60 ~~ ind60
    dem60 ~~ dem60
    dem65 ~~ dem65' %>%
  sem(PoliticalDemocracy)

fit.model2.cfa <- '
    ind60 =~ x1 + x2
    dem60 =~ y1 + y2 + y3
    dem65 =~ y5 + y6 + y7
    ind60 ~~ ind60
    dem60 ~~ dem60
    dem65 ~~ dem65' %>%
  sem(PoliticalDemocracy)

models <- list(model1 = fit.model1.cfa, model2 = fit.model2.cfa)

power <- map(models, function(x){

  n <- x@SampleStats@ntotal

  z <- sim(model = x, nRep = 10, n = n, generate = x)

  getPower(z)

})

power

#> $model1
#>    ind60=~x2    ind60=~x3    dem60=~y2    dem60=~y3    dem60=~y4    dem65=~y6
#>          1.0          1.0          1.0          1.0          1.0          1.0
#>    dem65=~y7    dem65=~y8 ind60~~ind60 dem60~~dem60 dem65~~dem65       x1~~x1
#>          1.0          1.0          1.0          1.0          1.0          1.0
#>       x2~~x2       x3~~x3       y1~~y1       y2~~y2       y3~~y3       y4~~y4
#>          0.5          1.0          1.0          1.0          1.0          1.0
#>       y5~~y5       y6~~y6       y7~~y7       y8~~y8 ind60~~dem60 ind60~~dem65
#>          1.0          1.0          1.0          1.0          1.0          1.0
#> dem60~~dem65
#>          1.0
#>
#> $model2
#>    ind60=~x2    dem60=~y2    dem60=~y3    dem65=~y6    dem65=~y7 ind60~~ind60
#>          1.0          1.0          1.0          1.0          1.0          1.0
#> dem60~~dem60 dem65~~dem65       x1~~x1       x2~~x2       y1~~y1       y2~~y2
#>          1.0          1.0          0.4          0.4          0.8          1.0
#>       y3~~y3       y5~~y5       y6~~y6       y7~~y7 ind60~~dem60 ind60~~dem65
#>          1.0          1.0          1.0          1.0          0.9          1.0
#> dem60~~dem65
#>          1.0

R - use simsem within map


Set grid to 75% of parent grid

Question: I don't know how to do this in WPF. Here is my code:
<ScrollViewer Grid.Row="2">
    <Grid>
        <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>

        <Grid Grid.Row="0" HorizontalAlignment="Left" Margin="10,5,0,0" Width="500">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
            </Grid.RowDefinitions>

            <Grid Grid.Row="0">
                <Grid.Background >
                    <ImageBrush ImageSource="Public\Images\chat_green-textarea.png"/>
                </Grid.Background>

                <TextBlock Padding="5" Foreground="White" FontSize="15" TextWrapping="Wrap">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</TextBlock>
            </Grid>

            <Grid Grid.Row ="1">
                <Image Source="Public\Images\chat_green-textarea-tail.png" Height="20" Width="30" HorizontalAlignment="Left" Margin="10,-4,0,0"/>
            </Grid>
        </Grid>
    </Grid>
</ScrollViewer>

I am displaying a Text in a Grid, but I want its max width to be set equals to the 75% of its parent grid. Thanks!
Answer: Put in it another grid with two columns with column definitions
<ScrollViewer>
    <Grid>
        <Grid.ColumnDefinitions>
            <columndefinition Width="3*"/>
            <columndefintiion Width="1*"/>
        </Grid.ColumnDefinitions>

        <Grid Grid.Column="0">
            ... <snip> ...
        </Grid>
    </Grid>
</ScrollViewer>

Put your target grid in the first column of the wrapper grid and now it
will have 75% width of it's parent.
Comment: I realized the true meaning of the * sign. Haha. Thanks!

Set grid to 75% of parent grid


Zoho CRM Client Script: How to access "modify time" of loaded page

Question: I'm writing a Zoho CRM Client script for the Account-Edit-onSave event. I'd like to access the "modify time" property such as it was when the user loaded the page, is this possible?
I've tried using $Page.record._Modify_time but it looks like this returns what is on the server when the user presses "save", not what it was when the user loaded the page, so if someone else had modified the same record while the user was looking at the page, I'd get the updated "modify time", not the original one.
Answer: You can use $Page.record._Last_Activity_time, it same as the Modified Time.
Comment: This returns what is on the server when the user presses "save", not what it was when the user loaded the page.


Objective-c enum getting error "... is not convertible to 'NativeObject'" in Swift

Question: I have a typedef defined in my objective-c files:
typedef enum : long{
    tb_closed_k = 0,
    tb_open_k
 } MyState;

Now I create a member of this type in my Swift class:
@objc class myClass {
    var activeState: MyState = tb_closed_k

   func testState( state:MyState ){
       if state != activeState{
         ..do something
       }
    }
}

so the line comparing the states gives me the error "MyState is not convertible to 'NativeObject'. I am using xCode 6-Beta3. Any Ideas.
thanks
Reza
Answer: Your enum is not directly importable into Swift because it does not use the NS_ENUM macro. Either rewrite the enum in Swift (using Int, not long) or incorporate NS_ENUM. In any case, using long here is a really bad idea in any case, because it won't come into Swift as a native type, whereas NSInteger will come in as Int.
Comment: just need to remember to use MyState.tb_closed_k when using the enum


Spring Roo errors in Roo_Service_Impl.aj

Question: In the domain model, Category that has a ManyToOne relation with Tag entity, and Tag has ManyToOne with OfferingDetail.
I'm getting these errors in the TagServiceImpl_Roo_Service_Impl.aj file:
<code>The method setTag(null) is undefined for the type OfferingDetail
</code>
Similar errors with a couple of other entities.
The setter/getter is .aj source file. Surprisingly, the error shows up only for the first setTag below, not the second! Why does this error occur, and how do I resolve this? I've tried reindex JDT weaving.

<code>@Transactional
public void TagServiceImpl.delete(Tag tag) {
    // Clear bidirectional many-to-one child relationship with Category
    if (tag.getCategory() != null) {
        tag.getCategory().getTags().remove(tag);
    }

    // Clear bidirectional one-to-many parent relationship with OfferingDetail
    for (OfferingDetail item : tag.getOurPlay()) {
        item.setTag(null);
    }

    // Clear bidirectional one-to-many parent relationship with UseCase
    for (UseCase item : tag.getUseCases()) {
        item.setTag(null);
    }

    getTagRepository().delete(tag);
}
</code>
Answer: The error was because I'd changed a property name in the entity, but Roo shell apparently did not pick up the change and modify other files.


Using Ninject dynamically to connection to different databases

Question: I have an MVC application using Ninject to connect to a single database. Now I need to support multiple databases. Currently, my global.asax.cs file has the following definition for ninject:
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        RegisterRoutes(RouteTable.Routes);

        //Using DI for controllers - use the Ninject custom controller factor
        ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory()); // Repository config is defined in ninject controller
    }

And here is what my Ninject controller class looks like:
public class NinjectControllerFactory : DefaultControllerFactory
{
    private IKernel kernel = new StandardKernel(new EriskServices());

    protected override IController GetControllerInstance(RequestContext context, Type controllerType)
    {
        if (controllerType == null)
            return null;
        return (IController)kernel.Get(controllerType);
    }

    private class EriskServices : NinjectModule
    {
        public override void Load()
        {
            Bind<IRisksRepository>().To<MySql_RisksRepository>()
                .WithConstructorArgument("connectionString", ConfigurationManager.ConnectionStrings["mydb1"].ConnectionString);
        }
    }
}

I also have a login page that handles user authentication. It is done through LDAP and does not require database connection.
My question is: Can I bind the ninject connectionString after the user authentication login page? The user would have a dropdown list for database they want to connect to, for example "mydb1" or "mydb2" or "mydb3". Each connection string would be defined in the web.config file.
Please help! Thank you!
Comment: I suppose another way to ask my question is - how can I use Ninject (dependency injection) to dynamically set my connection string after the login page?
Comment: Please visit below link

http://stackoverflow.com/questions/6632592/mvc3-ninject-and-ninject-mvc3-problem/8446194#8446194
Answer: No, you can't bind "after" - for one thing, web applications are stateless and you have no control over the order of events, but more importantly, Ninject modules define your IoC container and this configuration happens before almost anything else in the application or request lifecycle.
If you're saying that the user would pick this from a drop-down, then the act of choosing the repository is part of your application logic, not part of your IoC configuration. The way to deal with this is to create a factory interface. The implementation can be a thin wrapper around the Ninject kernel itself.
public interface IRisksRepositoryFactory()
{
    IRisksRepository GetRepository(string name);
    // Optional: add a GetRepositoryNames() method for populating dropdowns, etc.
}

public class NinjectRisksRepositoryFactory
{
    private readonly IKernel kernel;

    public NinjectRisksRepositoryFactory(IKernel kernel)
    {
        if (kernel == null)
            throw new ArgumentNullException("kernel");
        this.kernel = kernel;
    }

    public IRisksRepository GetRepository(string name)
    {
        return kernel.Get<IRisksRepository>(name);
    }
}

For this particular implementation you'd want to make sure you use named bindings (although generally speaking you could also use the metadata system), and do each binding explicitly:
Bind<IRisksRepository>()
    .To<MySqlRisksRepository>()
    .InRequestScope()
    .Named("mysql")
    .WithConstructorArgument("connectionString", GetConnectionString("mydb1"));
Bind<IRisksRepository>()
    .To<OracleRisksRepository>()
    .InRequestScope()
    .Named("oracle")
    .WithConstructorArgument("connectionString", GetConnectionString("ordb1"));
Bind<IRisksRepositoryFactory>()
    .To<NinjectRisksRepositoryFactory>();

It's also possible to do this without creating each binding explicitly, particularly if all targets are the same type (i.e. you only have a MySqlRisksRepository), by passing the connection string or related symbol as a parameter to the Get call and binding to a contextual method instead of a type - but I'd recommend against it, since it's really swimming against the current as far as DI in general goes.
One more thing: Don't worry that this resembles the "service locator" anti-pattern, because that's all it is - a superficial resemblance. When objects need to be able to create dependencies on the fly, creating special-purpose factories around the IoC container is the recommended solution, as it minimizes kernel exposure to a single class which could be easily replaced if you switched to a different framework.
Comment: Thanks for the response! I am kind of following what you are saying but still a little fuzzy on how the named bindings are working. Would you have an example site or something just for some background info?
Comment: Specifically - I'm not sure where the binding is supposed to happen. Right now its in the Application start, but would this be done in the login? Also, this is support multiple repositories, I just listed one for sake of simplicity.
Comment: @jjlee316 the bindings are done at the same time you create the kernel, normally in a `NinjectModule` that you load into the kernel. You can do it in `Global` if you want, although if you're using MVC3 and NuGet, it will install a bootstrapper in `App_Start` which is a little cleaner. Either way, bindings are one of the very first things to happen in an app, certainly long before any actions are executed.


c++ allocate *new Object() to reference

Question: I have a question about allocating in c++.
I have this code:
vector<unsigned char> &v = *new vector<unsigned char>();

Now the question is, is it generally a good idea to dereference the object and assigning it directly to a reference?
In my opinion, that makes it easier to use the object, because now you can just do:
v.push_back('a');
v[0];

instead of
v->push_back('a');
(*v)[0];

finally, I can do
delete &v;

to free my heap
Just because of the amount of (same) nice answers:
I know I can just use a stack-variable
but in my case, I need it on the heap!
But the question of using a heap or stack-variable is another one.
So I kept this example simple and especially did not asked if I should allocate the variable at all.
Comment: You know what would be even easier? Just `vector v;`.
Comment: Why have it on the heap in the first place then?
Comment: Seems strange that you actually have to do this in the first place. Why do you need to "new" a vector?
Comment: Well it's possible, but you I doubt you could free the object the way you want to, meaning you have a memory leak. Why not simple use a pointer if you want an object on the heap?
Comment: @JoachimPileborg There's no problem freeing the object; he shows how to do it.
Answer:
Is it generally a good idea to dereference the object and assigning it directly to a reference?

No, not at all.
If you don't need dynamic allocation, because the object only needs to last as long as the current scope, then make an automatic variable instead:
vector<unsigned char> v;

If you do need a dynamic object, then trying to disguise it is a good way to forget that it needs deleting. The best thing is to use a smart pointer so you don't need to remember to delete it at all; failing that, use a pointer.
Comment: What about something like `Base& obj = *(condition ? new Derived1 : new Derived2);` (with the necessary casts)?  (I suspect that the fact that you can't use a smart pointer is a valid enough reason, since it means that you have to enclose all of the following code in a `try...catch` block.)
Answer: It's purely a stylistic issue.  None of the places I've worked
have used this convention, so it might deroute new people in
your organization, but it is a valid convention.
It should be part of a larger definition of when you use
pointers, and when you use references.  (And you'll find a lot
of variation in this; I've used at least three different
conventions in different firms.)
Answer: It's not a good idea to store a heap object primarily in a reference variable, for the reason Joachim Pileborg gives in his comment. You ultimately need to delete the object, and that is best done through a pointer variable (in a reference, people will always wonder whether the actual object lives elsewhere).
Comment: `delete &v`
actually does delete the object properly,
I tested it with valgrind and it said to me he didn't found any memory leaks
so it works and the handling is far more simple than
`(*v)[0]`

and sometimes you have to store objects in the heap,
think about a generator function that does some other things I omitted here to keep it simple:

`
vector& gen(){
 return *new vector();
}
`
Comment: @Martinv.Löwis But why is it confusing?  Only because you've never worked in a company that used this convention, or for some more fundamental reason.  (I know it surprises me, but I'm pretty sure that that's just because I've never worked in a company which used it.)
Comment: I didn't mean to suggest that you can't delete it, but that delete &v is confusing.
Comment: The typical usage convention of references is that they get initialized with an object managed elsewhere. Having the reference variable own the object is a violation of that convention.
Answer: You could just do:
...
{
    vector<unsigned char> v; // this allocates the vector in the stack
    v.push_back('a');
    v[0];
}
...

As far as I can see there is no need to allocate the vector in the heap.
You should read about heap and stack memory:

What and where are the stack and heap?
Stack, Static, and Heap in C++

c++ allocate *new Object() to reference


How to find Fragment which was changed dynamically?

Question: I have a layout with two Fragments in it. Second one loads dynamically.
Fragment fg = EmptyRightFrag.newInstance();
        getFragmentManager().beginTransaction().add(R.id.right_frag, fg)
            .commit();

Then this second frame  replaces with another 'Fragment'.
    Fragment fg = MyClass.newInstance();
    getFragmentManager().beginTransaction().replace(R.id.right_frag, fg)
                .commit();

Finally I need to initialize the second Fragment by calling:
MyClass field = ((MyClass)getFragmentManager().findFragmentById(R.id.right_frag));

But here I do get java.lang.ClassCastException stating EmptyRightFrag cannot be casted to MyClass.
Answer: Where are you calling findFragmentById()? Directly after you added it?
The docs for commit() says this:

Schedules a commit of this transaction. The commit does not happen
  immediately; it will be scheduled as work on the main thread to be
  done the next time that thread is ready.

This means that the Fragment will not be added for a while (at least not before your method has returned). Anyways you should probably not handle initialization this way, it's better to let the Fragment take care of that in onCreate() or something.
Comment: But what if I need to work with data within a fragment replaced dynamically?
Comment: Then it's okay to call methods on it but during initial construction it is probably better to use setArguments()
Answer: Just call getFragmentManager().executePendingTransactions(); before getFragmentManager().findFragmentById() and all will be fine.


How to remove leading zeros from numeric text?

Question: I am using this to remove leading zeros from my input string.
return a.replaceAll("^0+","");

But the above string even removes from any string which is alphanumeric as well. I do not want to do that. My requirement is:
Only the leading zeros of numeric numbers should be removed e.g.
00002827393 -> 2827393

If you have a alpha numeric number the leading zeros must not be removed e.g.
000ZZ12340 -> 000ZZ12340

Comment: @syb0rg That's not quite the same. In that post zeros were removed from all alphanumeric strings. Here they're only removed from numbers.
Comment: Clarification Requested: Alphanumeric characters can be anywhere in string or just after leading zeros?
Comment: @Harish You are not able to find an answer for this question till now?
Comment: See [this](http://stackoverflow.com/questions/2800739/how-to-remove-leading-zeros-from-alphanumeric-text)
Answer: You can check if your string is only composed of digits first :
Pattern p = Pattern.compile("^\\d+$");
Matcher m = p.matcher(a);

if(m.matches()){
  return a.replaceAll("^0+", "");
} else {
  return a;
}

Also :

consider making your pattern static, that way it will only be created once
you may want to isolate the part with the matcher in a smaller function, "isOnlyDigit" for example
Answer: You can also try this:
a.replaceAll("^0+(?=\\d+$)", "")

Notice that the positive lookahead (?=\\d+$) checks to see that the rest of the string (after the starting 0s, matched by ^0+) is composed of only digits before matching/replacing anything.

System.out.println("00002827393".replaceAll("^0+(?=\\d+$)", ""));
System.out.println("000ZZ12340".replaceAll("^0+(?=\\d+$)", ""));

2827393
000ZZ12340
Comment: @MikeRylander: No, [this](http://www.ex-parrot.com/pdw/Mail-RFC822-Address.html) is a scary looking regex.
Comment: That is some scarey looking regex
Comment: @ColinDeClue Oh Dear God, WHY!
Answer: Test if the incoming string matches the numeric pattern "\d+".  "\d" is the character class for digits.  If it's numeric, then return the result of the call to replaceAll, else just return the original string.
if (str.matches("\\d+"))
    return str.replaceAll("^0+", "");
return str;

Testing:
public static void main (String[] args) throws java.lang.Exception
{
   System.out.println(replaceNumZeroes("0002827393"));
   System.out.println(replaceNumZeroes("000ZZ1234566"));
}

yields the output
2827393
000ZZ1234566

Answer: Logic:
it will convert the string to char array and start from i=0; As soon as it hits the first the first numeric value it breaks from the for loop and as soon as it hits first character (other than 1 to 9) it returns the same string. After the first for loop we have following cases to consider:
case 1. 00000000000
case 2. 00000011111
case 3. 11111111111

if it's 1 or 3 (i.e. the i's value from the first for loop will be 0 or length of the string )case then just return the string. Else for the 2nd case copy from the char array to a new char array starting for the i's value (i's value we will get from the first for loop and it holds the first numeric value position.). Hope it clears.

    public String trimLeadingZeros(String str)
    {
    if (str == null)
    {
        return null; //if null return null
    }
    char[] c = str.toCharArray();
    int i = 0;

    for(; i<c.length; i++)
    {
        if(c[i]=='0')
        {
           continue;
        }
        else if(c[i]>='1' && c[i]<='9')
        {
            break;
        }
        else
        {
            return str;
        }
    }
    if(i==0 || i==c.length)
    {
        return str;
    }
    else
    {
        char[] temp = new char[c.length-i];
        int index = 0;
        for(int j=i; j<c.length; j++)
        {
            temp[index++] = c[j];
        }
        return new String(temp);
    }
    }

Answer: Simply I did the following
String string = string.trim();
while(string.charAt(0) == '0'){
    string = string.substring(1);
}

Comment: 1. You missed the part that "If you have a alpha numeric number the leading zeros must not be removed".
2. If your string have 20 leading zeros, you will create 20 strings that needs to be garbage collected.


How can I make an element replace itself individually without knowing its ID?

Question: I wrote this very poorly the first time. Sorry. Revised:
Each element will have an ID but I won't know what it will be beforehand. What I need is for hovering over each div to replace only its own list item, ie. hovering over #1 makes #1 .second replace #1 .first, but doesn't make #2 .second replace #2 .first.
Here's what I have that affects both divs:

First

Second

First

Second

$(document).ready(function() {
    $(".hover").mouseenter(function() {
        $(".second").show();
        $(".first").hide();
    }).mouseleave(function() {
        $(".second").hide();
        $(".first").show();
    });
});

.second {display:none;}

https://jsfiddle.net/L50bm2vp/
Comment: What exactly do you mean by " it only replaces itself"?
Comment: it replaces itself with what?
Comment: nvm, figured it out, I think. For anybody else who is confused, he wants it so that when you hover over one of the span 1s, only that span 1 is turned into a span 2
Answer: Try this:
target each span1 class and show/hide its next span2 class
$(document).ready(function() {
    $("div .span1").mouseenter(function() {
        $(this).hide().next('.span2').show();

    }).mouseleave(function() {
        $(this).show().next('.span2').hide();
    });
});

UPDATE
Based on your revised post you can do below:
DEMO
$(document).ready(function() {
    $(".hover").mouseenter(function() {
        $(this).find(".second,.first").toggle();
    }).mouseleave(function() {
        $(this).find(".second,.first").toggle();
    });
});

You were just missing to target the element on which you are doing
  hover which can be done by targeting with $(this)
Comment: Anytime! Happy coding! :)
Answer: Is this what you want?
$(document).ready(function() {
    $(".hover").mouseenter(function() {
        $(this).find(".second").show();
        $(this).find(".first").hide();
    }).mouseleave(function() {
        $(this).find(".second").hide();
        $(this).find(".first").show();
    });
});


SQL Server: how to insert a group by parameter using IF

Question: I need to insert a condition at the end of a group by with respect to a condition
in SQL Server.
For example:
GROUP BY if(x>Y) parameter1, parameter2 else parameter3

Thanks
Comment: What does your SELECT look like when you are dynamically trying to create your GROUP BY?
Comment: @MitchWheat, I think OP required here conditional group by, not dynamic group by. Using `case` expression also we can solve this, but this completely based on the requirement and query. dynamic SQL is not required in some situation.
Comment: Re-opened. Poster: please add more info to your question.
Comment: Yeah i didn't do it dynamically...i had a sub query inside a main select in which i had to group by depending on the value of one of the values in a temp table. The case worked though.
Answer: You can use CASE expression here.
GROUP BY (case when x>Y then parameter1 else parameter3 end),parameter2

but it completely depends on what else other column you are used in the select part of your query.
Example Query:-
SELECT  (case when rank1>rank2 then user1 else user2 end) AS Users
        ,location
        ,SUM(Amount) as Value
FROM    Table1
GROUP BY (case when rank1 > rank2 then user1 else user2 end),location

Comment: Thank you so much....That seems to work in SQL server...

I added it like this

Select * from Table GROUP BY p1, (CASE WHEN a>3 THEN p2 END)

so that i can append an additional parameter

Let me just check whether it gets everything and i'll confirm


How to implement a global setUp() for multiprocessing using nosetests

Question: So far I've used nosetests with just one process and everything works fine.
To ensure my setUp is only executed once, I'm using a boolean var.
def setUp(self):
  if not self.setupOk:
    selTest.setupOk = True
    # start selenium
    # do other stuff which will be needed for all other tests to be able to run

Now I would like to run nosetests with the option --processes=5
How can I ensure that setUp(self) is only execued by one process (while the other processes are waiting).
I've tried to work with
def setUp(self):
  lock = multiprocessing.Lock()
  lock.acquire()
      if not self.setupOk:
        selTest.setupOk = True
        # start selenium
        # do other stuff which will be needed for all other tests to be able to run
  lock.release()

but this doesn't seems to work.
Answer: setUp will be called before every test is run.  If you want a method to execute just once, you can use setUpClass:
@classmethod
def setUpClass(cls):
    print "do stuff which needs to be run once"


Data structure in JS | Create reference to an object

Question: In my app, I have quizzes with questions. I'm writing a class whose goal is to load and concat quizzes. I have two arrays in my class.
The first array contains the quizz meta data :
metadata = [
  {
    name:'countries',
    language:'French'
  },
  {
    name:'music',
    language:'English'
  }
]

I also have an array containing all the questions concatenated:
questions = [
  {
    question:'What is the capital of France?',
    metaIndex: 0
  },
  {
    question:'What is the capital of Poland?',
    metaIndex: 0
  },
  ...
  {
    question:'Who is the singer of the Rolling Stones?',
    metaIndex: 1
  }
]

As you can see, the questions contain a reference to the meta data index. It's like a foreign key in relational database. My problem is that if I remove the quiz 0, it will shift all the indexes, and I'll have to iterate through the questions to update the indexes.
In JS, is there a way to reference directly the object instead of the index?
Any general suggestion is welcome ;-)
Comment: *"It's like a foreign key in relational database."* - Not quite.  Because it's relying on index position rather than an identifying key.  What if you give the first array of objects unique keys, and the second array references those keys instead of their positional index?
Comment: *"for some obscure reason this is not a reference, but a copy of the object that is created"* - That definitely doesn't sound right, and probably worth investigating on its own (perhaps as a separate Stack Overflow question if necessary).  But if the first solution is working, I'll go ahead and add it as an answer below.
Comment: Depending on how these data structures are created/used, you might even just include a direct reference to the relevant object instead of an identifier.  But there could be scenarios in which that doesn't quite work for you, which is why I haven't posted either approach as an answer.  At the moment I don't have an objective view on which would be "better".
Comment: I don't even understand why I didn't think of it in the first place.
Comment: Yes I already try to create a reference to the meta object, but for some obscure reason this is not a reference, but a copy of the object that is created. I guess this is one of the *scenarios* you are talking ;-) But your first solution is perfect for my app, and it also solves some other problems like asynchronous operations
Comment: I perform some other operation like concatenation to append the next questions to the list. Maybe the problem comes from there. But it's OK, if you add the answer, I'll mark the question as best answer.
Comment: `for (const q of questions) q.meta = metadata[q.metaIndex]` will create the object references you are looking for; not copies.
Answer:
It's like a foreign key in relational database.

Almost.  Note that in a relational database, the order of returned records is not guaranteed unless explicitly defined.  It can change on any given SELECT.  (A subject which is often in question on Stack Overflow, but that's another conversation entirely.)  But in this case the second data structure is referencing the positional index of elements in the first.
If the index changes, either by changing the data or even simply sorting the data, that reference breaks.
The analogy of a relational database is a reasonable one though, all you have to do is update the implementation to match that analogy.  A foreign key references a primary key.  Simply add a primary key of some kind.  For example:
metadata = [
  {
    id: 1,
    name:'countries',
    language:'French'
  },
  {
    id: 2,
    name:'music',
    language:'English'
  }
]

Then the second data structure can reference that:
questions = [
  {
    question:'What is the capital of France?',
    metaID: 1
  },
  {
    question:'What is the capital of Poland?',
    metaID: 1
  },
  {
    question:'Who is the singer of the Rolling Stones?',
    metaID: 2
  }
]

That way the index/order/etc. of the former structure can change, but as long as the objects therein still have their id values then the latter is still referencing them.
In fact, if name is going to be unique in the former structure then that can be the identifier used.  (Though in the data shown I'm not assuming it would be, for example if there's a countries entry in French and another one in English then that value wouldn't be unique.)