Stokes Theorem - finding the normal

Question: Calculate the absolute value of the line integral
$$\int\limits_C (2yz){d} x\ +(zx){d} y +(xy){d}z$$
where the curve C is the intersection between the surfaces $x^2+y^2=1$ and $z=y^2$.
I think I am correct in applying Stokes Theorem to this problem and have calculated the $curl\ \vec{F}= (0,y,-x)$. However I am stumped on how to find the unit normal vector? Any help greatly appreciated.
Comment: Evaluating this line integral directly looks pretty straightforward. Try cylindrical coordinates.
Comment: If you want to find a normal vector, you'll need a surface and a parameterization of said surface...
Comment: Try to parameterize $C$ as $t \rightarrow (\cos(t),\sin(t),\sin(t)^2)$, $t \in [0,2\pi[$.
Answer: Method 1: Calculating the Line Integral.
Lookings at the plots of the surfaces
$$ \color{blue}{z = y^2} \qquad \color{orange}{x^2+y^2=1} $$

We see that the intersecting curve $C$ looks like:

We can parametrize this curve by seeing that, since the $x,y$ coordinates lie on the unit circle, we have:
$$C: \mathbf{x}(t) = \langle \cos t, \sin t, \sin^2 t \rangle \qquad (0 \leq t \leq 2\pi) $$
Taking the vector field:
$$ \mathbf{F}(x,y,z) = \langle 2yz, xz, xy \rangle $$
We evaluate the line integral:
\begin{align*}
\int_C \mathbf{F} \cdot d\mathbf{s} &= \int_0^{2\pi} \mathbf{F}(\mathbf{x}(t)) \cdot \mathbf{x}'(t) \, dt \\
&= \int_0^{2\pi} \langle 2\sin^3 t, \cos t \sin^2 t, \cos t \sin t \rangle \cdot \langle -\sin t, \cos t, 2\sin t \cos t \rangle \, dt \\
&= \int_0^{2\pi} \left(3 \cos^2 t \sin^2 t - 2\sin^4 t \right) \, dt \\
&= \int_0^{2\pi} \left[3\left(\frac{\sin 2t}{2} \right)^2 - 2\left(\frac{1 - \cos 2t}{2} \right)^2 \right] \, dt \\
&= \int_0^{2\pi} \left[\frac{3\sin^2 2t}{4} - \frac{2 - 4\cos 2t + 2\cos^2 2t}{4} \right] \, dt \\
&= \int_0^{2\pi} \left[\frac{3\sin^2 2t - 2\cos^2 t + 4\cos 2t - 2}{4} \right] \, dt \\
&= \int_0^{2\pi} \left[\frac{\sin^2 2t + 3\cos 2t - 2}{4} \right] \, dt \\
&= \int_0^{2\pi} \left[\frac{1 - \cos 4t + 6\cos 2t - 4}{8} \right] \, dt \\
&= \int_0^{2\pi} \left[\frac{1 - 4}{8} \right] \, dt \\
&= -\frac{3}{8}\int_0^{2\pi} \, dt \\
&= -\frac{3\pi}{4}
\end{align*}

Method 2: Applying Stokes' Theorem.
We must choose a surface $S$ that has $C$ as its boundary. We can simply choose the part of the surface $\color{blue}{z = y^2}$ thats enclosed within $\color{orange}{x^2+y^2=1}$, that is:

$$S = \{ (x,y,z) \mid x^2 + y^2 \leq 1 \,,\, z = y^2 \}$$
We can parametrize the surface by noting that the $(x,y)$ points form a solid disk in the $x$-$y$ space, and $z$ is simply $y^2$, so we parametrize the surface as
$$S: \quad \mathbf{X}(r,\theta) = \langle r \cos \theta, r \sin \theta, r^2 \sin^2 \theta \rangle \qquad (\underbrace{0 \leq r \leq 1, 0 \leq \theta \leq 2\pi}_{(r,\theta) \in \, R = [0,1] \times [0,2\pi]})$$
We find the normal vector that arises from this parametrization by calculating:
\begin{align*}
\frac{\partial \mathbf{X}}{\partial r} &= \langle \cos \theta, \sin \theta, 2r \sin^2 \theta \rangle \\
\frac{\partial \mathbf{X}}{\partial \theta} &= \langle -r \sin \theta, r\cos \theta, 2r^2 \sin \theta \cos \theta \rangle \\
\mathbf{N}(r,\theta) &= \frac{\partial \mathbf{X}}{\partial r} \times \frac{\partial \mathbf{X}}{\partial \theta} \\
&= \begin{vmatrix} \mathbf{i} & \mathbf{j} & \mathbf{k} \\
   \cos \theta & \sin \theta & 2r \sin^2 \theta \\
   -r \sin \theta & r\cos \theta & 2r^2 \sin \theta \cos \theta
   \end{vmatrix} \\
&= \langle 0, -2r^2 \sin \theta, r \rangle
\end{align*}
We note that the $z$ component of the normal vector is positive, so as to point upward, conforming with the counterclockwise orientation of the line integral taken before.
The curl of the vector field $\mathbf{F}$ is:
\begin{align*}
\nabla \times \mathbf{F}
&= \begin{vmatrix} \mathbf{i} & \mathbf{j} & \mathbf{k} \\
   \frac{\partial}{\partial x} & \frac{\partial}{\partial y} & \frac{\partial}{\partial z} \\
   2yz & xz & xy
   \end{vmatrix}
= \langle 0, y, -z \rangle
\end{align*}
And so, we evaluate the line integral over $C = \partial S$ by applying Stoke's Theorem:
\begin{align*}
\int_{\partial S} \mathbf{F} \cdot d\mathbf{s} &= \iint_S (\nabla \times \mathbf{F}) \cdot d\mathbf{S} \\
&= \iint_R (\nabla \times \mathbf{F})\mid_{\mathbf{X}(r,\theta)} \cdot \mathbf{N}(r,\theta) \, dA \\
&= \int_0^{2\pi} \int_0^1 \langle 0, r \sin \theta, -r^2 \sin^2 \theta \rangle \cdot \langle 0, -2r^2 \sin \theta, r \rangle \, dr \, d\theta \\
&= \int_0^{2\pi} \int_0^1 (-3r^3 \sin^2 \theta) \, dr \, d\theta \\
&= -\frac{3}{4}\int_0^{2\pi} \sin^2 \theta \, d\theta \\
&= -\frac{3}{8}\int_0^{2\pi} (1 - \cos 2\theta) \, d\theta \\
&= -\frac{3}{8}\int_0^{2\pi} 1 \, d\theta \\
&= -\frac{3\pi}{4}
\end{align*}
Comment: Out of curiosity what program did you use to produce the graphs?
Comment: WOW fantastic answer! Thank you for taking the time to explain it so thoroughly.
Answer: To find the normal vector you need to find the divergence of f then divide it by the modulus of the divergence of f.

Stokes Theorem - finding the normal


How to resolve suexec policy violation causing error 500 using git-http-backend?

Question: I'm trying to get git-http-backend working on my remote vps with no luck. I've adjusted httpd.conf in a way similar to the on this question, but as soon as I add the ScriptAlias directive, the error occurs.
Apache error log:
<code> suexec policy violation: see suexec log for more details
 Premature end of script headers: git-http-backend
</code>
Suexec log
<code> error: target uid/gid (503/500) mismatch with directory (0/0) or program (0/0) or trusted user (0/10)
</code>
Can anyone comment on how one normally solves suexec problems?
EDIT
The main problem seemed to be that the web server is not allowed to run cgi scripts.
The documentation on configuring suexec is beyond me at the moment. I've chosen to disable it for now, which allows the web server to run these scripts. I can now successfully push to the repo. I found this article helpful.
Answer: I had this error while setting up moinmoin.   I suspect it's both lines you need to pay attention to (which in my case, were):
<code>[2014-09-18 17:17:18]: uid: (1009/testsite) gid: (1006/testsite) cmd: moin.cgi
[2014-09-18 17:17:18]: target uid/gid (1009/1006) mismatch with directory (0/0) or program (0/0)
</code>
The first line is stating that a process - in this case owned by testsite:testsite -  is attempting to execute a command (moin.cgi).
It then checks the calling process's user id/group id to see if it matches the command to be executed, which triggers the second output when it fails (0/0 indicates root/root).
Simply calling chown should fix it:
<code>chown -R testsite:testsite </path/to/directory-or-binary>
</code>
Answer: Alright well obviously you found your way...
I spent 7 hours straight today trying to solve this issue, contacted my hosts (godaddy) 3 times. All without prevail...
I ent up turning SUEXEC "off" then re-installed Apache (fresh install) on my server. Finally, when my day was coming to an end, I finally got it to work...
Answer: I chown the /var/www/ directory to my user in suexec directive and it works..!


What is the best way to compare two NSArrays and detect changes

Question: My requirement is to determine changes in address book (which contact(s) and which fields(s) has been changed since the application was last opened.
Now I have two NSArrays as arrSavedContacts(contains previous address book contacts) and arrContacts(current address book contacts). This is how the two arrays looks like
arrSavedContacts
{
    firstName = Gayan;
    id = 224;
    lastName = Udaha;
    phones =         (
                    {
            label = Mobile;
            value = "123456789";
        }
    );
},
    {
    firstName = Chandrananda;
    id = 225;
    lastName = "";
    phones =         (
                    {
            label = Mobile;
            value = "234567891";
        }
    );
},
    {
    firstName = Joe;
    id = 228;
    lastName = B8;
    phones =         (
                    {
            label = Mobile;
            value = "345678912";
        }
    );
},

arrContacts
{
    firstName = FirstName Changed;
    id = 224;
    lastName = Udaha;
    phones =         (
                    {
            label = Mobile;
            value = "123456789";
        }
    );
},
    {
    firstName = Chandrananda;
    id = 225;
    lastName = "";
    phones =         (
                    {
            label = Mobile;
            value = "345678912";
        }
    );
},

As the above two arrays, we can notice two changes, 3rd item is deleted and the firstName get changed in the 1st item.
Since we can have thousands of items in the address book, my question is, what is the best and optimum way to compare those two arrays and detect the changed items (deleted, added, changes for the internal fields)?
A code example is highly appreciated
Comment: Your data structure makes it nearly impossible to do what you want. You really need a dictionary of dictionary instead of an array of dictionary. The outer dictionary should be keyed on some sort of unique id for each contact entry. Then you can correlate the two (saved and changed) dictionaries by the keys. Then you can compare each corresponding inner dictionary looking for changes.
Comment: @rmaddy thanks for the idea, highly appreciated if you can show some example
Comment: Start with `arrSavedContacts`. You have an array of dictionary. Instead, put all of the dictionaries in a dictionary instead of an array. Your existing dictionaries will be the values in the dictionary and some sort of unique id for each contact will be its key. Now do the same for `arrContacts`. Now the each contact will have the same unique id in the two sets of data.
Answer: Here is code to check the changes, add and delete. Please check it, If you don't understand please comment...
NSMutableArray *oldArr =[NSMutableArray arrayWithArray:@[@{
                                                             @"firstName" : @"Gayan",
                                                             @"id" : @224,
                                                             @"lastName" : @"Udaha",
                                                             @"phones": @[
                                                                     @{
                                                                         @"label" : @"Mobile",
                                                                         @"value" : @"123456789"
                                                                      }
                                                                     ]
                                                             },
                                                         @{
                                                             @"firstName" : @"Chandrananda",
                                                             @"id" : @225,
                                                             @"lastName" : @"",
                                                             @"phones": @[
                                                                     @{
                                                                         @"label" : @"Mobile",
                                                                         @"value" : @"234567891"
                                                                         }
                                                                     ]
                                                             },
                                                         @{
                                                             @"firstName" : @"Joe",
                                                             @"id" : @226,
                                                             @"lastName" : @"",
                                                             @"phones": @[
                                                                     @{
                                                                         @"label" : @"Mobile",
                                                                         @"value" : @"345678912"
                                                                         }
                                                                     ]
                                                             },
]];

NSMutableArray *newArr =[NSMutableArray arrayWithArray:@[@{
                                                             @"firstName" : @"Gayan",
                                                             @"id" : @224,
                                                             @"lastName" : @"Udaha",
                                                             @"phones": @[
                                                                     @{
                                                                         @"label" : @"Mobile",
                                                                         @"value" : @"123456789"
                                                                         }
                                                                     ]
                                                             },
                                                         @{
                                                             @"firstName" : @"Chandrananda",
                                                             @"id" : @225,
                                                             @"lastName" : @"",
                                                             @"phones": @[
                                                                     @{
                                                                         @"label" : @"Mobile",
                                                                         @"value" : @"11111111"
                                                                         }
                                                                     ]
                                                             },
                                                         @{
                                                             @"firstName" : @"Luan",
                                                             @"id" : @229,
                                                             @"lastName" : @"",
                                                             @"phones": @[
                                                                     @{
                                                                         @"label" : @"Mobile",
                                                                         @"value" : @"55555555"
                                                                         }
                                                                     ]
                                                             },
                                                         ]];

NSMutableSet *oldSet = [NSMutableSet setWithArray:oldArr];
NSMutableSet *newSet = [NSMutableSet setWithArray:newArr];

//1: Get filter all changed, add, delete items

[oldSet minusSet:newSet];
[newSet minusSet:oldSet];

NSArray *remainOldArr = [NSArray arrayWithArray:[oldSet allObjects]];
NSArray *remainNewArr = [NSArray arrayWithArray:[newSet allObjects]];

if (remainNewArr.count == 0 && remainOldArr.count == 0) {
    // there is no changes.
    return ;
}

//2: detect which items changed,add,delete

NSMutableArray *arrayChangedItems = nil;
NSMutableArray *arrayDeleteItems = nil;
NSMutableArray *arrayAddItems =nil;

NSPredicate *pre1 = [NSPredicate predicateWithFormat:@"self.id IN %@",[remainOldArr valueForKeyPath:@"id"]];
NSPredicate *pre2 = [NSPredicate predicateWithFormat:@"NOT self.id IN %@",[remainOldArr valueForKeyPath:@"id"]];
NSPredicate *pre3 = [NSPredicate predicateWithFormat:@"NOT self.id IN %@",[remainNewArr valueForKeyPath:@"id"]];

arrayChangedItems = [NSMutableArray arrayWithArray:[remainNewArr filteredArrayUsingPredicate:pre1]];
arrayAddItems = [NSMutableArray arrayWithArray:[remainNewArr filteredArrayUsingPredicate:pre2]];
arrayDeleteItems = [NSMutableArray arrayWithArray:[remainOldArr filteredArrayUsingPredicate:pre3]];

Comment: I tested the code, but every time it returns empty arrays for arrayAddItems and arrayDeleteItems. arrayChangedItems is always the full set of items
Comment: super cool answer. How ever in my case it needs to change the predicates slightly like this. pre2 and pre3 should use arrays before get the minus set operation. Also, the same arrays should use to filteredArrayUsingPredicate operation
Answer: In continuation to what rmaddy suggested, it makes sense to have data in dictionary of dictionary to easily find out deletions at first place based on unique IDs. For instance this is how your base dictionary should look like:
{ 224 = {
        firstName = Gayan;
        id = 224;
        lastName = Udaha;
        phones = (
               {
                 label = Mobile;
                 value = "123456789";
               }
                );
        }

    225 = {
        firstName = Chandrananda;
        id = 225;
        lastName = "";
        phones =  (
               {
                 label = Mobile;
                 value = "234567891";
                }
                 );
    }
}

Now, once your data is set correctly, you can add a category on NSDictionaryand implement following method:
- (NSArray*)changedKeysIn:(NSDictionary*)iAnotherDict {
    NSMutableArray *changedKeys = [NSMutableArray array];

    for (id key in self) {
        if(![[self objectForKey:key] isEqual:[iAnotherDict objectForKey:key]])
            [changedKeys addObject:key];
        }

        return changedKeys;
}

Then simply call it like:
[baseDict changedKeysIn:anotherDict];

Comment: This is a start. This only works for keys found in both dictionaries. Logic needs to be added keys added or removed from one or the other dictionary. And logic needs to be added to see what changed in a changed contact dictionary.
Comment: @rmaddy yes, I managed to get the data sets as dictionaries, with a uniq key for each inner dictionary. 224 =     {
        firstName = Gayan;
        lastName = Udaha;
        phones =         (
                        {
                label = Mobile;
                value = "1234567890";
            }
        );
    };   But still unable to figure out the logic for detecting inner field changes
Comment: @sajaz Once you know a two corresponding dictionaries are different, you will have to compare each field one at a time. There's no shortcut.
Answer: How about…
// put new contacts in a dictionary
NSMutableDictionary *aDictionary = [NSMutableDictionary dictionary];
[arrContacts enumerateObjectsUsingBlock:^(id theNewContact, NSUInteger idx, BOOL *stop)
{
    [aDictionary setObject:theNewContact forKey:[theNewContact valueForKey:@"id"]];
}];

// check each old contact
[arrSavedContacts enumerateObjectsUsingBlock:^(id theOldContact, NSUInteger idx, BOOL *stop)
{
    NSDictionary *aNewContact = [aDictionary objectForKey:[theOldContact valueForKey:@"id"]];
    if (aNewContact == nil)
    {
        // delete old contact
    }
    else
    {
        if (![aNewContact isEqual:theOldContact])
        {
            // update old contact
        }
        // remove existing contact from the dictionary
        [aDictionary removeObjectForKey:[theOldContact valueForKey:@"id"]];
    }
}];

// new contacts
[aDictionary allValues];

Each array is enumerated once.


What does this option at the end of NieR: Automata actually do?

Question: After beating

 the credits mini-game

in NieR: Automata's last main ending, you get two options. One of these is

  to simply display a message made out of per-selected phrases to
 display to other players going through the same mini-game,

simple enough.
But after that question, you're given a heftier question. Your pod asks if

 you would like to "save" another, random, player.

  In order to do this though, you must have all of your save data
 erased. As I'm not yet done getting achievements or side endings,

I said no, leaving me curious as to what he meant. What exactly would have happened

 to this randomly selected player

if I had I hit yes?

 Would I get any indication of anything that happened as well, or would
 the pod have just said 'affirmative', erased my data, and send me back
 to the title screen?
Comment: May want to put some spoiler tags around your stuff
Answer: Ah, the big choice.

 Since the ending sequence is nigh impossible without accepting help (this is clearly intentional, as the entire point is that you can't take on enormous tasks alone), you accepted it, right? Every person that assisted you was actually someone who chose to erase all of their save data for this purpose. Had you chose to delete your save, someone out there who needed help on the ending sequence would have gotten assistance from you.

I originally declined in order to 100% the game, but as soon as I had done so, I went back and redid this sequence so that I, too,

 could erase all save data in order to assist someone else.

If you choose yes, you will actually be prompted for confirmation about 7 or 8 times before it actually happens.

 During the sequence directly following, it will show all of your data being deleted, one item at a time (though many are skipped over so this doesn't take an eternity). The very last part shows all of your save slots being erased. This means you cannot simply copy your save data to a second save data slot. All three are erased entirely. The only record of you having played the game and made this choice is that you will get an alternate background for the title screen. It looks like this:
Comment: @Tylor it will only give help if you say yes. I believe the choice defaults to yes. I tried to do it solo for about 20 minutes. Every death, it would offer me help from another player. Eventually it gets to the point where your DPS is so low and the "enemies" shoot so many bullets that it's impossible to survive. If it gave you help, it's because you selected the option. Another horrifying part is that every time you got hit after that point, someone's save was permanently deleted from the game's server.
Comment: It's worth noting that on PC at least, you can backup your save file and replace it after. In My document/my games/Nier Automata, Slot_0, Slot_1 and Slot_2 (exact name escapes me at the moment) are your 3 save slots. The 2 other files can be left as they contain the system and graphic settings (such as which title screen background you have). Doing so has no effect on game progress, endings or achievements.
Comment: Actually, I had not accepted the request for help when offered. I have some (though not a whole lot) of experience with bullet hell games, so while I probably would have not completed it without help, I certainly wasn't ready at the point when asked to do it the easy way. Or at least, I meant to hit no (I could have easily hit yes accidentally, can't say for sure). If I hit no, it gave me the help anyway.
Comment: @fhlamarche I believe it's possible to copy your save data to a USB for PS4, but doesn't that defeat the purpose of it all? ;)
Comment: @Vemonus "Another horrifying part is that every time you got hit after that point, someone's save was permanently deleted from the game's server. "  Huh?  What server, the game saves locally (and I doubt anyone's cloud saves get deleted)?
Comment: @Andy you have to delete all your saves to have your name appear there. By that point, the server should be the only place with your old save. If they say it's deleted, it very well could be
Comment: You say that the only record of having played is the modified title screen. Have you started a new game after deleting your save? My friend has told me that there are some differences in the game. In particular, the boss names are all written in the game's made up language instead of English.
Comment: @murgatroid99 Yep. I got ending E a second time so that I could do the DLC. The bosses' names are written in English before ending E (before routes C and D, even). 9S is able to read the machine's language, so all throughout route B, you're able to read the bosses' names in English. I distinctly remember, however, that when I was playing the game after deleting my save, I knew what all of the bosses' names were *despite* seeing alien characters when fighting them as 2B
Comment: I don't have enough reputation to downvote, but this doesn't answer the question of what it actually does. The fact that your saves are deleted is implied already. I would've expected the answer to explain if you actually helped a random person.
Comment: @Zimano I'm not sure what you want me to say to please you lol. I'm not a developer for Platinum, so I can't tell you the *exact* nuances of this choice. It removes your save, for sure, and your name can show up for other players (it's hard to prove this however, since it's random and you would need a second account to be playing the same part and happen to get your name to show). You also get a nifty new startup screen. That's what happens. *Ta-daaaa*
Answer: The usual claim is (quoting the earlier answer) that

Every person that assisted you was actually someone who chose to erase all of their save data for this purpose.

The idea seems to be that there is, in effect, a counter stored on a Square Enix/Platinum server that increments every time someone

sacrifices their save files to help someone

and decrements every time someone

accepts the help

and when it reaches zero the second action becomes impossible.
That can't be true because of the huge difficulty gap between the incrementing and decrementing actions. (Keep in mind that the counter would be increased by a player only if they performed the incrementing action without previously performing the decrementing action.) In practice the counter would almost always be zero, but public evidence shows that it's never or almost never zero. (I'm not aware of anyone ever being unable to perform the decrementing action, but if that does happen, it's at least uncommon.)
The decrementing action displays the username of someone who allegedly performed the incrementing action. I see no reason to believe that those usernames are made up. Most likely, there's a pool of names on a server, the decrementing action randomly selects a name from the pool without removing it, and the incrementing action adds your name to the pool and removes someone else's (probably whoever's been there the longest) to prevent the size from growing without bound. That would mean that the incrementing action has no effect on the ability of others to perform the decrementing action. The only effect is that they'll see your name instead of someone else's. I think the most selfless action is to give that other person a little more time to shine.
The incrementing action also has a local effect on your machine – see the last spoiler box of the earlier answer if you want to know that effect.
Comment: @pinckerman I wanted to avoid adding two more spoiler boxes, since they break up the flow of the text, but since it's confusing I added them.
Comment: What do you mean with [redacted]?


Am I missing some obvious way to change this lightbulb?

Question: I thought I'd be able to lift the plastic shade and angle it out of the trim, but it doesn't lift at all.  It slides side-to-side a bit, but the flanges are large enough to keep it firmly behind the trim.  The trim is attached on the two rounded ends and doesn't seem to slide down or unclip in any way.  The long sides of the trim will bend down a bit if I pull on them.
I just want to see if anyone has any obvious suggestions I'm missing before I try prying the trim off the ceiling.  A lot of things in this house seem to have been done in the cheapest way possible that wouldn't be immediately noticed by a potential buyer, and I'm guessing this bulb that can't be changed without reinstalling the trim around the fixture might be one of them.
Comment: Have you examined the shortest ends for some kind of clip or clasp? Something that sort of slides, just above the trim?
Answer: After an hour of searching google
Home Depot

Looks like your light
Taking the description from the Home Depot page, I found this PDF for installation instructions
PDF
Looking at the PDF and the photos, it looks like there is a white trim ring around the glass. Instead of prying from the trim that touches the ceiling, see if theres another lip closer to the glass where it flattens out. It is probably held in via compression.
Comment: +1 for some good googling, though those are some of the worst instructions I've seen.
Comment: Another possibility is that the plastic dome is very flexible and you just pry it out.  I have a smallish circular light where the dome is removed this way.
Answer: this might be a cover similar to ones I've seen used for bathroom exhaust fans/lights, where you pull the entire cover down to remove. This type of cover uses some long spring wires to retain the cover to the enclosure. They can be a bit unnerving at first as you have to pull pretty hard to get them started coming off. Generally they'll then hang from the spring clips, as they're kinda hook shaped.
Comment: The question stated "doesn't seem to slide down or unclip in any way"...
Comment: Yup. I could easily see that as the description of how the fan cover I'm describing feels. In fact, I once scratched my head in quite the same way as the OP when trying to replace a bulb in one of these. I've got a strong suspicion this is what the OP is up against.
Comment: Well, tonight I tried taking a pry bar to one end of the trim where it seems to be attached, and I used so much force it felt like I was going to break the trim into pieces rather than remove it if I pushed any harder.  It will come down perhaps less than a centimeter from the ceiling with a _lot_ of force, and then retract as soon as I stop prying.  So it isn't just a matter of pulling it down.  I'm not sure what to try next, other than prying harder and probably breaking it.
Comment: @NickG well there goes my idea. glad you didn't break anything (yet)


Nullpointer Exception reading in file line by line

Question: txt file that I am reading into my program line by line. My goal is to display this text with no punctuations and in all lowercase. So far I am able to display this text in this way with the code below however I keep receiving a run-time error of a nullpointer exception at the last line of my "while" expression and I am not sure where my error is. I believe the problem may have been in my boolean while expression and I tried changing input != null to reader.readLine() != null with no success. Thank you!
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;

public class BinaryTree {

    public static void main(String[] args) {

        String inputFile = "pg345.txt";
        FileReader fileReader = null;

        try {
            fileReader = new FileReader(inputFile);
        }   catch (FileNotFoundException e) {
                e.printStackTrace();
        }

        BufferedReader reader = new BufferedReader(fileReader);
        String input;

        try {
            input = reader.readLine().toLowerCase().replaceAll("[^a-zA-Z ]", "").toLowerCase();
            System.out.println(input);
            while (input != null) {

                input = reader.readLine().toLowerCase().replaceAll("[^a-zA-Z ]", "").toLowerCase();
                System.out.println(input);
            }

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try {
            fileReader.close();
        }   catch (IOException e) {
            e.printStackTrace();
        }

    }

}

Comment: possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it)
Answer: Your culprit is
reader.readLine().toLowerCase().replaceAll("[^a-zA-Z ]", "").toLowerCase()
reader.readLine().toLowerCase().replaceAll("[^a-zA-Z ]", "").toLowerCase();

Here the invocation
reader.readLine()

might return null if there are no more lines in the file.


PYTHON: projecteuler 60

Question: I have some trouble about project euler problem 60.
The primes 3, 7, 109, and 673, are quite remarkable. By taking any two primes and concatenating them in any order the result will always be prime. For example, taking 7 and 109, both 7109 and 1097 are prime. The sum of these four primes, 792, represents the lowest sum for a set of four primes with this property.

Find the lowest sum for a set of five primes for which any two primes concatenate to produce another prime.

The code that I created is too slow to see the correct answer. And I don't even see that is it work correctly or not. The code is:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 27 21:18:10 2022

@author: burak
"""

def is_prime(n, check_list_for_primes): #checks if value is prime
    if check_list_for_primes.count(n) > 0: #checks if valu calculated before. if it were, it avoid loop.
        return True
    else:
        if n == 1:
            return False
        if n == 2 or n == 3:
            return True
        i = 2
        while i * i <= n:
            if n % i == 0:
                return False
                exit(0)
            i += 1
        check_list_for_primes.append(n) # if it never calculated, stores the value to avoid loop at the beginning of function.
    return True

def check_1(i, j): # checks the concanated calues if they are primes.
    if is_prime(int(str(i)+str(j)), check_list_for_primes) == True and is_prime(int(str(j)+str(i)), check_list_for_primes) == True:
        return True
    else:
        return False

def check_2(temp_list, n): # checks the final list that obtain the minimum summation.
    if temp_list.count(n) == 0:
        temp_list.append(n)
    for i in temp_list:
        for j in temp_list:
            if len(temp_list) == 1:
                return check_1(i, j)
            elif i == j:
                continue
            elif len(temp_list) == 1:
                return True
                break
            elif check_1(i, j) == False:
                return False
    return True

def func_(prime_list): # creates a dictionary summation of the five prime numbers in order to problem.
    temp_list = []
    result_dic = {}
    k = 0
    t = 0
    for i in prime_list:
        if i == 5:
            continue
        while k == 0:
            t = k
            for j in prime_list:
                if i == j or j == 5:
                    continue
                elif j  0 and len(temp_list) > 1:
                    t -= 1
                    temp_list.remove(max(temp_list))
                    continue
        if len(temp_list) == 5:
            result_dic[sum(temp_list)] = temp_list
        elif len(temp_list) < 5:
            k +=1
        temp_list = []
    return result_dic

if __name__ == "__main__":
    dic_ = {}
    prime_list = []
    check_list_for_primes = []
    for i in range(3, 9000, 1): #creates prime list between given range
        if is_prime(i, check_list_for_primes) == True:
            prime_list.append(i)
    check_list_for_primes = prime_list.copy() #pseudo prime list to avoid calculating if the number is prime.
    dic_ = func_(prime_list) #final dictionary to obtain minimum summation of five prime numbers.
    x = min(list(dic_.keys()))
    print(str(x) + " : " + str(dic_[x]))

I tried to type the examination of calculating order.
The main problem is at "func_" function. The for loop of "j" must be manipulated if the code not to get required list lenght. The "j" loop must be restart again after remove second element of "temp_list" and it must be start after shift to removed element of "prime_list".
Could you help me to see where I made mistakes and how can I improve calculation speed. Thanks so much.
Comment: please be specific with the prblem that you have, which part are you stuck on exactly ?  https://stackoverflow.com/help/minimal-reproducible-example
Answer: I solved it. while loop changed and the "j" for loop determined by a list. The final code is;
def is_prime(n, check_list_for_primes): #checks if value is prime
    if check_list_for_primes.count(n) > 0: #checks if valu calculated before. if it were, it avoid loop.
        return True
    else:
        if n == 1:
            return False
        if n == 2 or n == 3:
            return True
        i = 2
        while i * i <= n:
            if n % i == 0:
                return False
                exit(0)
            i += 1
        check_list_for_primes.append(n) # if it never calculated, stores the value to avoid loop at the beginning of function.
    return True

def check_1(i, j): # checks the concanated values if they are primes.
    if is_prime(int(str(i)+str(j)), check_list_for_primes) == True and is_prime(int(str(j)+str(i)), check_list_for_primes) == True:
        return True
    else:
        return False

def check_2(temp_list): # checks the final list that obtain the minimum summation.
    for i in temp_list:
        for j in temp_list:
            if len(temp_list) == 1:
                return check_1(i, j)
            elif i == j:
                continue
            elif len(temp_list) == 1:
                return True
                break
            elif check_1(i, j) == False:
                return False
    return True

def func_(prime_list): # creates a dictionary summation of the five prime numbers in order to problem.
    prime_list.remove(5)
    temp_list = []
    result_dic = {}
    # k = 0
    copy_primes = prime_list.copy()
    for i in prime_list:
        for z in prime_list:
            if z <= i:
                copy_primes.remove(z)
            else:
                break
        if i == max(prime_list):
            break
        elif i == 5:
            continue
        # for z in range(len(prime_list) - 1, 0, -1):
        #     if check_1(i,prime_list[z]) == True:
        #         max_prime_of_i = prime_list[z]
        #     break
        while len(temp_list) < 5:
            # if temp_list[1] == max_prime_of_i:
            #     break
            if len(temp_list) == 1:
                break
            if len(copy_primes) == 0 and len(temp_list) > 1:
                copy_primes = prime_list.copy()
                for z in prime_list:
                    if z <= temp_list[1]:
                        copy_primes.remove(z)
                    else:
                        break
                temp_list = []

            for j in prime_list:
                if len(copy_primes) > 0:
                    j = copy_primes[0]
                    copy_primes.remove(j)
                else:
                    break
                if temp_list.count(i) == 0:
                    temp_list.append(i)
                    continue
                temp_list.append(j)
                temp_list.sort()
                if check_2(temp_list) == True and len(temp_list) > 1:
                    continue
                elif check_2(temp_list) == False  and len(temp_list) > 1:
                    temp_list.remove(j)

            print(i)
            print(temp_list)
            if len(temp_list) < 5 and len(copy_primes) == 0:
                continue
            elif len(temp_list) == 5:
                break
        copy_primes = prime_list.copy()
        if len(temp_list) == 5:
            result_dic[sum(temp_list)] = temp_list
            print(str(min(list(result_dic.keys()))) + " : " + str(result_dic[min(list(result_dic.keys()))]))
            weight_ = 0
            check_weight = 0
            for p in temp_list:
                    weight_ = weight_ + len(str(p))
            if weight_ < check_weight or check_weight == 0:
                check_weight = weight_
            elif check_weight < weight_ and len(temp_list) == 5:
                return result_dic
        temp_list = []
    return result_dic

if __name__ == "__main__":
    dic_ = {}
    prime_list = []
    check_list_for_primes = []
    for i in range(3, 9000, 1): #creates prime list between given range
        if is_prime(i, check_list_for_primes) == True:
            prime_list.append(i)
    check_list_for_primes = prime_list.copy() #pseudo prime list to avoid calculating if the number is prime.
    dic_ = func_(prime_list) #final dictionary to obtain minimum summation of five prime numbers.
    x = min(list(dic_.keys()))
    print(str(x) + " : " + str(dic_[x]))

PYTHON: projecteuler 60


UTC to Eastern Converter - Looping through list in a function

Question: I have a csv of tweets with the column "created_at" that shows times in UTC as such:
Thu Mar 19 12:37:15 +0000 2015
I created this function so that is can convert a UTC time to Eastern time (EST or EDT):
import pandas as pd
df = pd.read_csv('tweets.csv')

from datetime import datetime
from email.utils import parsedate_tz, mktime_tz
import pytz

def to_local_time(tweet_time_string):
    timestamp = mktime_tz(parsedate_tz(tweet_time_string))
    dt = datetime.fromtimestamp(timestamp, pytz.timezone('US/Eastern'))
    return dt.strftime('%Y-%m-%d %H:%M:%S')

time_string = to_local_time('Thu Mar 19 12:37:15 +0000 2015')

But I want to loop it through the entire column of df['created_at'] as opposed to inputting a single value one by one like above. I tried:
import numpy as np
time = df['created_at']

for row in time:
    new_time = to_local_time(time)
    print(np.array(new_time))

But get the error ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
How can I iterate through the entire "created_at" column to convert all values from UTC to Eastern and save the new Eastern time as a new column in the dataframe?
Answer: Try .tz_convert('US/Eastern')
# sample data
df = pd.DataFrame({'Date': ['Thu Mar 19 12:37:15 +0000 2015']})
# convert to datetime and convert utc to Eastern
df['Date_Eastern'] = pd.to_datetime(df['Date']).dt.tz_convert('US/Eastern')

                                 Date              Date_Eastern
    0  Thu Mar 19 12:37:15 +0000 2015 2015-03-19 08:37:15-04:00

larger sample data
df = pd.DataFrame({'Date': pd.date_range('2023-01-01', '2023-01-02', freq='h')})
df['Eastern'] = pd.to_datetime(df['Date'], utc=True).dt.tz_convert('US/Eastern')

                  Date                   Eastern
0  2023-01-01 00:00:00 2022-12-31 19:00:00-05:00
1  2023-01-01 01:00:00 2022-12-31 20:00:00-05:00
2  2023-01-01 02:00:00 2022-12-31 21:00:00-05:00
3  2023-01-01 03:00:00 2022-12-31 22:00:00-05:00
4  2023-01-01 04:00:00 2022-12-31 23:00:00-05:00
5  2023-01-01 05:00:00 2023-01-01 00:00:00-05:00
6  2023-01-01 06:00:00 2023-01-01 01:00:00-05:00
7  2023-01-01 07:00:00 2023-01-01 02:00:00-05:00
8  2023-01-01 08:00:00 2023-01-01 03:00:00-05:00
9  2023-01-01 09:00:00 2023-01-01 04:00:00-05:00
10 2023-01-01 10:00:00 2023-01-01 05:00:00-05:00
11 2023-01-01 11:00:00 2023-01-01 06:00:00-05:00
12 2023-01-01 12:00:00 2023-01-01 07:00:00-05:00
13 2023-01-01 13:00:00 2023-01-01 08:00:00-05:00
14 2023-01-01 14:00:00 2023-01-01 09:00:00-05:00
15 2023-01-01 15:00:00 2023-01-01 10:00:00-05:00
16 2023-01-01 16:00:00 2023-01-01 11:00:00-05:00
17 2023-01-01 17:00:00 2023-01-01 12:00:00-05:00
18 2023-01-01 18:00:00 2023-01-01 13:00:00-05:00
19 2023-01-01 19:00:00 2023-01-01 14:00:00-05:00
20 2023-01-01 20:00:00 2023-01-01 15:00:00-05:00
21 2023-01-01 21:00:00 2023-01-01 16:00:00-05:00
22 2023-01-01 22:00:00 2023-01-01 17:00:00-05:00
23 2023-01-01 23:00:00 2023-01-01 18:00:00-05:00
24 2023-01-02 00:00:00 2023-01-01 19:00:00-05:00

Comment: This is also for one date. How can I get this for every row in my date column?
Comment: It will work for all rows. You do not need a loop.
Comment: How does it work for all rows?
Comment: That is how this pandas function works. Did you click on the link I provided or try it on your actual data?
Comment: Thank you, from your reference I was able to do it!
Answer: Update:
Final code for how to do what I asked -
import pandas as pd
import numpy as np

df = pd.read_csv('tweets.csv')

time = df['created_at']
time = np.asarray(time)

# sample data
df2 = pd.DataFrame({'Date': time})

# convert to datetime and convert utc to Eastern
df['Date_Eastern'] = pd.to_datetime(df2['Date']).dt.tz_convert('US/Eastern')

Comment: This is a minor issue. the pandas Series is a one-dimensional array. You don't have to convert it to a numpy array, and then create a new pandas DataFrame.


In Minecraft, I put the Nether portal exactly how it should be but it won't light why?

Question: I've been trying to light my nether portal but it doesn't work. I have the portal set up correctly but it still won't work. The portal doesn't show up. Can anyone tell me why?
Comment: Because there **is** no Nether in the Pocket Edition. You need to use a Nether Reactor.
Comment: How do I use that?
Answer: In Minecraft Pocket Edition you can't go to the nether. Instead you have the Nether Reactor, follow the instructions below to make it.
C = Cobblestone
G = Gold Block
N = Nether Reactor Core
A = Air
. = Spacing to make my diagram look right
Bottom Layer
G  C  G
C  C  C
G  C  G
Middle Layer
C  A  C
A  N  A
C  A  C
Top Layer (3 blocks off the ground)
A  C  A
C  C  C
A  C  A
Done!
Now you just tap it to activate it and it will spawn a giant room out of netherack. Inside will spawn Zombie Pigmen to attack you while random items spawn inside the room. After 45 seconds the nether reactor will burn out and you will lose the gold blocks, meanwhile holes will appear in the walls to let you out and the Pigmen and items will stop spawning. When you leave you'll find it changed the time to night. To make a Nether Reactor Core follow the instructions below.
I = Iron
D = Diamond
Crafting Recipe
I  D  I
I  D  I
I  D  I
Comment: Last time I did that Zombie Pigman didn't show up
Comment: Probably on peaceful. That happened to me when I did it.


How to parse complex string with C++?

Question: I'm trying to figure out how could I parse this string using "sstream" and C++
The format of it is: "string,int,int".
I need to be able to assign the first part of the string which contains an IP address to a std::string.
Here is an example of this string:
std::string("127.0.0.1,12,324");

I would then need to obtain
string someString = "127.0.0.1";
int aNumber = 12;
int bNumber = 324;

I will mention again that I can't use boost library, just sstream :-)
Thanks
Comment: Smells like homework :) Or is there some other reason to why you can't use boost?
Comment: Why is it unusual he can't use boost? In a corporate environment you are not usually allowed to randomly add new library dependencies, it can take months to get permission or it may simply be rejected.
Comment: Or you can use Boost... but be stuck with an early version. I still have to use "1-33-x" thanks to oldish dependency that has not evolved :/
Comment: @larsm: I have to port some stuff for embedded devices, not homework at all. :-), trying to avoid external stuff like boost for example.
Answer: The C++ String Toolkit Library (Strtk) has the following solution to your problem:

int main()
{
   std::string data("127.0.0.1,12,324");
   string someString;
   int aNumber;
   int bNumber;
   strtk::parse(data,",",someString,aNumber,bNumber);
   return 0;
}

More examples can be found Here
Answer: It isn't fancy but you can use std::getline to split the string:
std::string example("127.0.0.1,12,324");
std::string temp;
std::vector<std::string> tokens;
std::istringstream buffer(example);

while (std::getline(buffer, temp, ','))
{
    tokens.push_back(temp);
}

Then you can extract the necessary information from each of the separated strings.
Comment: It's much easier not to mess up than Eli's example, though limited to only one delimiter (which covers this case) it really does the trick pretty neatly.
Answer: Here's a useful tokenization function. It doesn't use streams, but can easily perform the task you require by splitting the string on commas. Then you can do whatever you want with the resulting vector of tokens.
/// String tokenizer.
///
/// A simple tokenizer - extracts a vector of tokens from a
/// string, delimited by any character in delims.
///
vector<string> tokenize(const string& str, const string& delims)
{
    string::size_type start_index, end_index;
    vector<string> ret;

    // Skip leading delimiters, to get to the first token
    start_index = str.find_first_not_of(delims);

    // While found a beginning of a new token
    //
    while (start_index != string::npos)
    {
        // Find the end of this token
        end_index = str.find_first_of(delims, start_index);

        // If this is the end of the string
        if (end_index == string::npos)
            end_index = str.length();

        ret.push_back(str.substr(start_index, end_index - start_index));

        // Find beginning of the next token
        start_index = str.find_first_not_of(delims, end_index);
    }

    return ret;
}

Comment: `if (end_index == string::npos)` is not really necessary, `std::string::substr` copies chars up until the end of string if the number spans past it's end. http://www.cplusplus.com/reference/string/string/substr/
Comment: Made this the correct answer since it's a more general approach, thank you for this Eli.
Answer: You could do something like this as well I believe (Totally off the top of my head so apologies if i made some mistakes in there) ...
stringstream myStringStream( "127.0.0.1,12,324" );
int ipa, ipb, ipc, ipd;
char ch;
int aNumber;
int bNumber;
myStringStream >> ipa >> ch >> ipb >> ch >> ipc >> ch >> ipd >> ch >> aNumber >> ch >> bNumber;

stringstream someStringStream;
someStringStream << ipa << "." << ipb << "." << ipc << "." << ipd;
string someString( someStringStream.str() );

Comment: This is very fragile, and will fail on any input that does not precisely match the input structure (without allowing any sane form of error detection or recovery). This problem would be better solved with a tokeniser such as the post by @Eli Bendersky.
Comment: If you replace istrstream and ontrstream with stringstream and init it the correct way this works perfectly.
Comment: The first part is a string followed by a comman. You should not split that into its constituant parts unless sombody tells you its the IP4 address (or somthing specific).
Comment: indeed .. but the OP never stated that the format WOULDN'T always be like that ...

How to parse complex string with C++?


Cassandra big partitions and deduplication

Question: I have a table
CREATE TABLE user_songs (user_id int, song text, listen_date date, PRIMARY KEY (user_id, song))

and need to get unique listened songs by user. But some users can generate big partitions (more 100.000 or 100 MB).
If add listen_date to partition key (split big partitions) I cannot get unique songs and need use additional deduplication on app side. Also it complicates pagination.
Maybe there is a more effective solution?
Answer: You can split big partitions to several partitions by using consistensy hashing for part of partition key:
CREATE TABLE songs_listenings (
    user_id int,
    song_hash int,
    song text,
    listen_date date,
    PRIMARY KEY (( user_id, song_hash ), song)
);

song_hash - is a hash which is generated based on song text. To generate this hash you need to implent a Consistent hashing function in your app which will provides ability to generate some number in a specified range (max number of partition which you want to have for single user) for a specified input parameter (song text). (E.g. Guava java library provides consistent hashing function)
For the case with multiple listenings for the same song the consistent hash will return the same number, so it will be the same partition key and you will have only one record for the same song per user.
But due to you will have multiple partitions per user you will have to perform multiple requests to get all data for an user (iterate over all possible hash values).
Answer: I would model your data like this;
listened_songs_by_user
user_id(partition key) | song_id (clustering key) | listen_date
songs_by_user
user_id (partition_key) | song_id (clustering_key)
Whenever you insert a record to listened_songs_by_user table, do these after the insert

lookup songs_by_user;
if there is a record

Yes, then do nothing
No, add a record to songs_by_user

If you want to retrieve unique songs, then read songs_by_user table by user_id

Denormalization and duplication of data is a fact of life with Cassandra. Don't be afraid of it.
  https://www.datastax.com/dev/blog/basic-rules-of-cassandra-data-modeling


Ran install from ISO to disk(Trial)Ubuntu 14.04, the disk installed beside windows10 but now have 2 screens to load...

Question: Turn on power, screen asks which to load(From windows) So, I select windows, and poof, good !   Then if I choose Ubuntu, a screen says stuff, and ESCape is my option.  Then I choose to boot (f9) Ubuntu, and another Ubuntu screen appears.
I got a pastebin,
http://paste.ubuntu.com/14673246/
I'm worried wubi will destroy the computer... and, I would like to just click on ONE or the other to load whichever OS I need to use...instead of having the two loaders... as I do now.  Whatever did this was from the live-install icon for 14.04, thanks.
Comment: Possible duplicate of [Fixing grub menu after migrating wubi to partition](http://askubuntu.com/questions/264344/fixing-grub-menu-after-migrating-wubi-to-partition)
Comment: Read that question and it's answer.  That may help you.
Comment: Reading, but i am afraid to .. mess with this.  A broken Wubi has been detected. Please fix it this way:
https://wiki.ubuntu.com/WubiGuide#Cannot_boot_into_Ubuntu
Comment: It looks like you have an EFI install of Windows.  You can't use wubi with EFI to my knowledge.
Comment: Uninstalled Wubi / Ubuntu.  Re-installed via liveCD option says "Install Ubuntu" (Not try it.)  Ubuntu is definitely working from the firmware... But, Windows boot mgr has no entry to load it, so I have to exit windows via troubleshooting/firmware advanced settings, or hold shift/on restart to load Ubuntu.
Comment: Read "http://askubuntu.com/questions/264344/fixing-grub-menu-after-migrating-wubi-to-partition?lq=1"  and Got very interested !  Still not sure what to do about getting Ubuntu into that boot file.
Comment: Hold on a minute
Comment: Check out my answer below.
Answer: OK, so now your problem seems to be that there is no boot menu entry.
Use EasyBCD to set this up.  This answer has a more detailed description.
This will let you select wether to boot into Windows or Ubuntu from the windows boot menu.
If you don't like booting to GRUB after you select Ubuntu, you can configure GRUB to have a 0 second delay, so that you don't see it.  It will remain hidden.
Comment: And I have confirmed myself that this **DOES** work in Windows 10 (at least it does in the Enterprise version).
Comment: Have Home version. HP i5 4core.  I also read this...  "" Alternatively you can use "Dual-boot Repair Tool" which has a graphical interface to bcdboot.exe, bootsect.exe and other useful functions like boot sector view and one click dual-boot repair function for Windows 10/8/7/Vista  (also can fix Windows XP boot files).
Comment: EasyBCD will do that for you, and it's very simple and easy to do.  I strongly suspect that this will work with Home, since they use the exact same bootloader.


Calling replaceWith gives "not a function" error (replacing text node with mix of text and html)

Question: I have multiple text nodes which I want to replace some text in it with html:

{
       "data": [
          {
             "source": "e.com",
             "created_time": "2015-11-13T06:16:09+0000",
             "id": "913680432051814"
          },
          {
             "source": "e.com",
             "created_time": "2015-11-13T06:16:02+0000",
             "id": "913680355385155"
          },
          {
             "source": "e.com",
             "created_time": "2015-11-13T06:16:00+0000",
             "id": "913680332051824"
          }

I want to add  tag to the id number.
I am trying:
x=$("pre")
  .contents()
  .filter(function() {
    return this.nodeType === 3
  });

trying to replace on any element. i am trying with x[0]
rep =  x[0].data.replace(//\"id\": \"(.*)\",/, "/\"id\": \"$1\"")

then try
x[0].replaceWith(rep)

it says: x[0].replaceWith not a function
So how to replace the text with html elements?
Answer: I tried the below it worked. Using $(this) worked.
x=$("pre")
  .contents()
  .filter(function() {
    return this.nodeType === 3
  })
.each(function(){
 rep =  this.data.replace(//\"id\": \"(.*)\",/, "/\"id\": \"$1\"")

  $(this).replaceWith(rep);  //when i used $(this) it worked.
})


Removing Carpet Glue

Question: I installed outdoor carpet on my porch.  The glue bled through in spots.  What can I use to remove the spots from the carpet?
Comment: What type of glue did you use? A solvent based or water based glue? The brand name would be helpful in directing you to the correct chemical or process.
Comment: I used Roberts Indoor/Outdoor Carpet Adhesive
Comment: I'm curious if the carpet was inexpensive enough, is it worthwhile to remove, replace, and try again with a different method? Can you share a picture of the bleed through? I'm trying to picture how much work it might be to cleanup, and even if you get the glue to release/dissolve, getting that out of carpet could be a challenge in-itself.
Answer: Roberts 8000 concentrated stripper is suggested by mfg for glue removal. The roberts adhesive you used is a solvent free adhesive so best to use what they recommend. This a concentrated latex adhesive remover so you will want to probably apply it to a cloth and work the spots to remove the stains. Non VOC and enviromentaly according to the documentation.
Comment: I understand you used their adhesive. roberts 8000 is a concentrated stripper made for thier adhesives. There are many latex strippers out there but for best results I use one made by the same company or recommended by the company that makes the adhesives if I spill some or have bleed through at a seam.
Comment: Will this damage the carpet?
Comment: It is used to glue it down so I would not expect it to cause damage but test a small area to be sure.
Comment: The problem is that I used Roberts to glue it down, but the glue bled thru the carpet in spots.  That's what I need to remove.
Answer: I'm a carpet installer; I use mineral spirits to clean glue.
When installing glue-down carpet, you should use a 1/16th notched trowel and spread it evenly with no glops, and right up to all edges. You also need to wait till it dries and is tacky (1/2 hour more or less) before you lay the carpet down. This avoids the issue. https://www.youtube.com/watch?v=F12k2J3ouYg
Answer: Try acetone nail polish remover.
Comment: Almost all carpet is made from plastic (i.e., recycled soda/popbottles)... Acetone will eat this plastic material and make a much bigger mess.
Comment: I'm near positive it will harm the carpet. No acetone does not eat all plastics, but if you are going to try to use it on the carpet, test it on a scrap.
Comment: It comes in a plastic bottle. I use nail polish remover as a glue remover all the time, works great.
Comment: Will nail polish remover harm the carpet?
Comment: I'm not making this up, I do this for a living.
Comment: Added a pic of acetone in a cheap dollar store plastic bag, and a cheap made in Pakistan table towel dowsed in acetone. Short of going in the shed and dumping it on a cheap piece of rental carpet, not sure what other proof you want. You can believe the innerwebs, or real life. Your choice.
Comment: @NPM, I'm not attempting to personally attack you. Nor am I calling you an inanimate object with a derogatory or superiority pretense. I am simply stating a definite fact - Acetone absolutely can and will dissolve MANY plastics (Not all), but many. More than ONE!  Check the chemical formula's and some chemistry references & you will learn this is true. As someone who has used Acetone on MANY things (including plastic) I can say as a human being with experience that Acetone can and will absolutely damage plastic, potentially hers. I stand by my recommendation against your answer knowing this.
Comment: Here ya go, a plastic item, that acetone ate like the blob :)  seriously though, acetone does damage some plastics, thus the recommendation against it's use on "unknown" plastic.  http://www.evilmadscientist.com/2006/how-to-extract-magnets-from-plastic-toys/

Removing Carpet Glue


How can I manipulate 2D arrays in Java?

Question: I've been studying for my upcoming Java exam, and i'm having a hard time wrapping my head around 2D arrays. I have the basics down, such as creating and initializing a 2D array, but when it comes to inserting, deleting, or even sorting through one, I get pretty confused. My professor spent all of 10 minutes going over the basics but on our exam, we are expected to know how to create a 2D array of objects and manipulate the data by inserting, deleting, and sorting the objects in the array. He makes us hand-write all of our code on our exams, so no computers are allowed to assist in the process. I've spent hours pouring over examples both here and on other sites, but I still don't feel like I understand the material well enough to hand write all my code and get it right.
My confusion mostly stems from the nested for loops usually used to move thru a 2D array. I can see how other people do it and copy that, but I still don't understand why the loops work as they do. I'm sure i'm in the minority here, but for whatever reason the logic behind it has me completely lost.
Take this(albeit poor) example i've been working on to help myself understand 2D arrays(as well as the rest of the exam material). Say you run a car dealership and you want to order cars to fill your stock. The program starts with a top abstract class that describes the cars you are selling in general(in my case Audi). The dealership offers 4 models of Audi's, an A4, A6, A8, and R8. All these cars(classes) inherit methods from the super, named Audi. I then want to create a 2D array to store the cars in stock. This will be used in another class defined by me, including methods to search(), delete(), and sort(). Let's call it AudiDealership. The dealer can only hold 3 of each model, so the array would be something like Audi[4][3]. The A4's would fill the first row, subscript 0, A6 fills subscript 1, ect. How would I set up the for loops to insert/delete from the proper row? I obviously don't want an A4 inserted into a row that should hold an A6, and so on.
Again, I can stare at code all day and copy it, but I want to understand why/how the loops work as they do. I apologize if this topic seems trivial or has been beaten to death, but all the reading i've done before posting this has left me just as confused as before. Many of you on this site are fantastic teachers in your own right, so I thought someone may be able to explain this in a way that I can understand. My professor hasn't been any help in this regard, so i'm using external means to try and figure things out. I greatly appreciate any advice or explanation in advance :)
Comment: Maybe you read this? http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html It's a great resource for understanding how to deal with arrays. If you understand how to work with a single array, a 2D array is simply an array of arrays, so once you grap the concept that would be more easy to understand it.
Comment: [Concise Explanation of Two-dimensional arrays](http://math.hws.edu/javanotes/c7/s5.html)
Answer: It helps to think of 2D arrays as arrays that hold other arrays. Such as Cars[0][5] is accessing a car array at 0 and the actual car is found in position 5 of that array. Cars[1][5] would access the second car array at position 1 and the car is found at 5 of the array that's in position 1. This code might help you understand it a bit more:
public class TwoDArray {

  public static void main(String[] args)
  {
    Cars[][] cars; // declaring my 2D array.

    cars = new Cars[4][]; // making the x axis 4 cars wide.

    // now we will step along the x axis and create a Cars array in each slot.
    for ( int a = 0; a < cars.length; a++) // cars.length = how wide.
    {
        cars[a] = new Cars[3]; // creating a new Cars[] in each slot of our 2D Car array @ position a.
                               //cars[a] = new 1D Cars array in slot a, length of 3.
    }

    // Note that we could have also created our array like this.
    // Cars[][] cars = new Cars[4][3];

    for ( int x = 0; x < cars.length; x++) //stepping along the x axis. cars.length = how wide.
    {   //every time we step thru x we will execute this next loop.
        for ( int y = 0; y < cars[x].length; y++) // stepping along the y axis. cars[x].length = how long.
        { // this loop will cycle through the y axis each time we increment x
            cars[x][y] = new Cars( 2014, "someAudi", x + " " + y ); // creating a new car(s) @ x,y position.
        }
    }

    // now to just print them.

    for ( int x = 0; x < cars.length; x++) //stepping along the x axis again.
    {
        for ( int y = 0; y < cars[x].length; y++) // stepping along the y axis.
        {
            System.out.println(cars[x][y].getYear() +
                    " " + cars[x][y].getModel() +
                    " " + cars[x][y].getName() +
                    " " + cars[x][y].getManufacturer()); // the super method.
        }
    }

    //INSERTION.

    // To insert into your array, you simply need to provide the coordinates to insert the new Car(s) object.
    // This next line will insert a new Car into the array at position 1 and the number 2 element of that array.
    cars[1][2] = new Cars( 2014, "someAudi", "My Favorite Car!");

    System.out.println(); // Just adding a space between outputs.

    for ( Cars[] c: cars) //extracting each Cars array and name it c from the 2D Cars array named cars.
    {                     //basically stepping along the x axis and getting each array stored in x.

        for ( Cars car: c) // Now we are stepping along the y axis.
        {                  // We are getting each individual Cars object and naming it car
                           // from each Cars[] named c from our first loop.

            System.out.println(car.getYear() +
                    " " + car.getModel() +
                    " " + car.getName() +
                    " " + car.getManufacturer()); // the super method.
        }
    }

    // NOTE* if you wish to insert a new element and do not have extra capacity then you will need to
    // create a larger array @ cars[x]. cars[x] = new Cars[newSize];.

    // DELETION.

    // To delete an element you can just simply overwrite it.
    // such as:
    cars[1][1] = new Cars( 2014, "someAudi", "new Audi"); // Essentially we deleted and inserted a new object
                                                          // at position [1][1].

    // If you just want to completely remove the element then you will need to update the size of the array.

    // You can define a new array to hold the values of the old array minus the element that should be deleted.
    Cars[] newArray = new Cars[cars[2].length - 1]; // We will use the array stored in cars[2] for this example.
                                                    // we set the length to one less to completely get rid of the
                                                    // old element.

    int deleteThisPosition = 1; // We will use this variable to store the position that will be deleted from
                                // the array stored in cars[2].

    int newArrayPosition = 0; // We will use this to increment our position in the new array along with `a`
                              // in the next for loop.

    for ( int a = 0; a < cars[2].length; a++)
    {
        if ( a == deleteThisPosition) // if it reaches this position we will advance `a` and exclude it from
             a++;                     // our new array.

        newArray[newArrayPosition] = cars[2][a]; // we will store the value @ position `a` from the array in cars[2]
                                                 // into our newArray @ position `newArrayPosition`.

        newArrayPosition++; // incrementing our variable to stay parallel with the array in cars[2].
    }

    //Now we can just assign the newArray to cars[2]. You will notice that Car `2 1` is no longer present.
    cars[2] = newArray;

    System.out.println(); // Just adding a space between outputs.

    for ( Cars[] c: cars)
    {
        for ( Cars car: c)
        {
            System.out.println(car.getYear() +
                    " " + car.getModel() +
                    " " + car.getName() +
                    " " + car.getManufacturer()); // the super method.
        }
    }

  }
}

Here are the other classes from your example.
Audi class:
public abstract class Audi {

  public String getManufacturer() { return "Audi"; } // method from this super class.

}

Cars class:
public class Cars extends Audi{ //extending Audi.

  private String model;
  private String name;
  private int year;

  Cars(int year, String model, String name)
  {
    this.year = year;
    this.model = model;
    this.name = name;
  }

  public String getName() { return name; }

  public String getModel() { return model; }

  public int getYear() { return year; }

}

If you run the code you will notice the pattern in the names of the cars.
Output:

Notice the pattern in each car's name, the unique column. It corresponds to how we stepped through our loops. We started with x and for each x we looped through y. x + " " + y was how we named each car in the code above.
Comment: Amazing example! This helps me understand how the loops actually move thru the array. Your comments made the code easily readable, and I know how it's functioning during each iteration. Thanks a ton :) Why my prof couldn't construct something like that is beyond me.
Comment: I'm glad that I was able to help.
Comment: I updated my answer to include insertion and deletion, just incase you still needed some help with those as well. Also added enhanced for loops incase you would like to understand those as well. You can ignore the enhanced loops if you like as I only use them to print out the arrays.
Comment: Thanks a ton! I've been playing around with some code since you posted this(before the insertion and deletion) and I think i'm starting to get the hang of it! With the rest you added, i'll feel a lot more comfortable come test time on monday. I really appreciate your helpful input. People like you are what make the programming community so awesome sometimes :)
Comment: As far as the enhanced for loops, i've used em a few times w regular arrays and my prof briefly went over them in class last week, but I never really got the gist of it, so thanks for adding that. I'm always down to learn something new, so the convenience of less code when referring to enhanced loops is something I should probably get more familiar with.
Answer: Let me give you an example:
StringBuilder output = new StringBuilder();

    for (int i = 0; i < table.length; i++) {
        for (int j = 0; j < table[i].length; j++) {
            output.append(table[i][j]);
        }
        output.append("\n");
    }

This would be the code to loop through a 2 dimensional array.

The code goes directly into the first row. This is the i-value.
As you want to loop through every column of the row,
you need to know the length of the row to loop through it.
So you start in the first row, and go right to the end which is table[i].length.
In the first row the first length would be table[0].length.
And this length is 3 as you have 3 columns in each row.

As we're now done with looping through the first row, we get to second row.
By going into the second row i increases by one.
So our pointer shows now in row 2 (The i  in table[i].length is now 1 because it always starts at 0) and so on.
Our pointer goes through every row and thats just how it works.
with every new row the pointer of i increases by 1 (that's the i++ in the for loop).

With every new column in one row the j increases and the i stays the same.
The i only changes when you're entering a new row.
And the j changes by entering a new column.
Hope this helps ;)
EDIT.:
Another example :
if you would like to get the value of the 3rd column in the 4th row:

The value you want is inside here: table[3][2];
Remember arrays always start counting at 0. :)
Comment: Wow, the visual helped a ton! For whatever reason that was the hardest part for me, the visualization. Along with your explanation of each section, I feel like I understand it much better than before. I'm still not 100% but I can play with some code and hopefully figure it out. Thanks a ton! :)
Comment: no problem :), I had the same problems when starting. Feel free to ask :)
Answer: Audi[4][3] cars = ... // your 2D array of all cars

As you correctly specified,

The A4's would fill the first row, subscript 0, A6 fills subscript 1, ect.

which translates to cars[0] holds Audi[] with A4 instances, cars[1] holds Audi[] with A6 instances etc.
OK, so
 Audi[] A4s = cars[0];
 Audi[] A6s = cars[1];
 ...

Then you could say that
 Audi A4_1 = A4s[0];
 Audi A4_2 = A4s[1];
 Audi A4_3 = A4s[2];
 ...

And repeat it for each car you have. But this is a wrong approach. First we generalize access to each car.
If you want to traverse specific cars in each model array, you need to have a for-loop with index called, say, specificCarIndex. Loop to traverse an array of A4s will be simple:
 for (int specificCarIndex = 0; specificCarIndex < 3; specificCarIndex++) {
      // Here A4s[specificCarIndex] contains an object of concrete Audi car of model A4
  }

To traverse array of another model (like A6) you do the same, replacing A4s with A6s and so on.
Now we need to generalize everything.
  for (int carModelIndex = 0; carModelIndex < 4; carModelIndex++) {
      // Here cars[carModelIndex] holds an array of specific Audi model as you mentioned before
  }

cars[carModelIndex] essentially is Audi[] A4s if carModelIndex == 0, then Audi[] A6s if carModelIndex == 1 and so on.
Now that we know how to access array of each Audi model, and we know how to access individual cars in each model array, we combine the two:
 for (int carModelIndex = 0; carModelIndex < 4; carModelIndex++) {
     for (int specificCarIndex = 0; specificCarIndex < 3; specificCarIndex++) {
         // Here cars[carModelIndex][specificCarIndex] holds an object of type Audi which refers to a specific car
         // If double index seems difficult, consider this:
         // Audi[] audis = cars[carModelIndex] (array like A4s, A6s...)
         // Audi audi = audis[specificCarIndex] (specific car)
         // Just as in the examples before for-loops.
     }
 }

Comment: Thank you for relating to one of my specific questions, which was how to search for a specific car in the array itself. Also, your variable names helped me understand what each block of the loop is doing in relation to my example. It will be hard to choose an answer as you all have brought something helpful to the table :)

How can I manipulate 2D arrays in Java?


Can't add local SQL database to VS2010 project?

Question: I've been reading up and doing exercises in Visual Studio 2010 Professional C#. Everything has worked til' I came across an exercise that asked to create a local SQL database(.sdf). When I add it, it gives me the error message; "The data provider required to connect to the local data file could not be found. The file will be added to the project but the typed DataSet associated with the file will not be generated." It will add the database but whenever I try to access it it gives me another error Message;
"The operation could not be completed. Unspecified error."
At first, I thought it was a matter of reinstalling SQL Server Compact 3.5 SP2. Tried it and no luck. Not sure what to do from here. :\
If relevant:
    Windows XP x32
    Visual Studio Professional 2010
    SQL server compact 3.5 SP2
Comment: Please see this http://stackoverflow.com/questions/8372969/data-provider-required-to-connect-to-local-data-file-could-not-be-found
Answer: Try this link. I just started a ASP.NET web application and I have used this article for setting up some entity framework stuff. I really like this so far. I hope this helps.
http://weblogs.asp.net/dotnetstories/archive/2011/03/01/using-stored-procedures-with-entity-framework-in-an-asp-net-application.aspx
Answer: Are you using Entity Framework?  If so are you doing Code First or Database First coding?
This is an example using MVC3 but is easily transferable to other project models and easy to follow: http://www.asp.net/mvc/tutorials/getting-started-with-aspnet-mvc3/cs/adding-a-model
If you are new to Entity Framework here are some more tutorials to scan through to get what you need: http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc


file descriptor in unix

Question: i have the below shell script:
pankaj@pankaj-Lenovo-G500:~$ cat demoscr
if [ $# -ne 2 ]
then
   echo "Error : Number are not supplied" 1>&2
   echo "Usage : $0 number1 number2" 1>&2
   exit 1
fi
ans=`expr $1 + $2`
echo "Sum is $ans"

when i run the shell script, error message is being printed but nothing is present in the er1 file. why?
pankaj@pankaj-Lenovo-G500:~$ ./demoscr > er1
Error : Number are not supplied
Usage : ./demoscr number1 number2
pankaj@pankaj-Lenovo-G500:~$ cat er1
pankaj@pankaj-Lenovo-G500:~$ cat er1

Answer: The simple > operator redirects STDOUT to a file. However, your script is printing to STDERR (see the 1>&2 at the end of your echo commands). That's why you see the text in the terminal and not in the log file.
You need to redirect the output of the script using 2> (redirect STDERR only) or &> (redirect both STDOUT and STDERR) instead.
See How do I save terminal output to a file? for more details about output redirection to files in Bash.

file descriptor in unix


dell inspirion 7559 -- ubuntu 16.04 booted up using `nomodese` to login screen successfully but desktop is now showing after logging in

Question: I'm a very novice user of ubuntu, tried installing ubuntu on my dell 7559 15" laptop. Installed it successfully after some search, I had to press e and add the following line to grub bootloader nomodeset added that... installed it successfully after when I went to start the ubuntu
I repeated the added nomodest in bootloader again to run ubuntu 16.04 ran it to login screen image below.

once I logged in no desktop loaded, the following image

Any Idea?
Kindly help me, what should I do to get it working...
Comment: thank you @AndroidDev I'll try that today come back if i need any help regards
Comment: @AndroidDev I can't manage to do anything on that desktop... everything is blinking very very fast even terminal.... I'm using UEFI bios... as I said I'm not that technical when it comes to using ubuntu... please help
Comment: Blinking? What do you mean by that exactly?
Comment: blinking `display/display of` of the terminal at very rapid speed... like you blink your eye open close
Answer: Please try replacing nomodeset with nouveau.modeset=0.
Comment: This is very much a possible solution.  I can't test it cuz I don't have this particular hardware but I can assure you this problem is because of the i7 skylake processor & nvidia 960m GPU which this Laptop has.  I too had resolved the same issue on the same combination of processor & GPU using this command line argument
Comment: This does not provide an answer to the question. Once you have sufficient [reputation](http://askubuntu.com/help/whats-reputation) you will be able to [comment on any post](http://askubuntu.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](http://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/low-quality-posts/586393)
Comment: one more thing buddy, do I have to add this everytime when i boot my laptop to ubuntu OS ? is there a permanent fix?
Comment: You can make it permanent by editing the /etc/grub/default.cfg file.  Then run `sudo update-grub` .  Not sure about the exact commands, a quick Google search to update kernel parameters will tell you both


Separating js from angular controllers (do I create a directive for this?)

Question: I'm using a lot of built in angular directives such as ng-repeat with the html. I already separated the UI component to a different HTML file using ng-include. How do I separate out the js from the controller?
html (ui/hotkeys.ui.html)

<button class="btn hotkey" ng-change="vm.changed($index)" ng-class="{'btn-danger': $index === 1, 'btn-info': $index === 2, 'btn-primary': $index === 3, 'btn-success': $index === 4, 'btn-warning': $index === 5, 'btn-inverse': $index === 6 }" ng-if="hotkeys !== null" ng-model="vm.credentials.groups[$index]" ng-repeat="hotkeys in vm.showGroups track by $index" tabindex="-1" type="button" style="margin-right: 4px" uib-btn-checkbox>
  <svg width="42" height="42" version="1.1" xmlns="http://www.w3.org/2000/svg">
    <circle cx="20" cy="20" r="4" stroke="black" fill="white" ng-if="$index === 1 || $index === 3 || $index === 5" stroke-width="1"/>
    <circle cx="10" cy="10" r="4" stroke="black" fill="white" ng-if="$index ===4 || $index === 5 || $index === 6" stroke-width="1"/>
    <circle cx="10" cy="20" r="4" stroke="black" fill="white" ng-if="$index === 6" stroke-width="1"/>
    <circle cx="10" cy="30" r="4" stroke="black" fill="white" ng-if="$index === 2 || $index === 3 || $index === 4 || $index === 5 || $index === 6" stroke-width="1"/>
    <circle cx="30" cy="10" r="4" stroke="black" fill="white" ng-if="$index === 2 || $index === 3 || $index === 4 || $index === 5 || $index === 6" stroke-width="1"/>
    <circle cx="30" cy="20" r="4" stroke="black" fill="white" ng-if="$index === 6" stroke-width="1"/>
    <circle cx="30" cy="30" r="4" stroke="black" fill="white" ng-if="$index === 4 || $index === 5 || $index === 6" stroke-width="1"/>
  </svg>
</button>

This is the code I want to load from another js file instead of keeping all this in the controller.
/* ============ HOTBAR ============ */
var enableHotbar = true;
$document.bind('keypress', function (e) {
    //console.log(e.key);
    var key = String.fromCharCode(e.which);
    if (key == 1 || key == 2 || key == 3 || key == 4 || key == 5 || key == 6) {
        //alert(key);
        $scope.$broadcast('keypress', e, e.which);
    }
});
$scope.keyList = []; //["1","2", "3"];
$scope.$on('keypress', function (event, key) {
  var easyToReadKeyFromKeycode = String.fromCharCode(key.charCode);
  if (enableHotbar && (document.activeElement.id !== 'manager-phone') && (document.activeElement.id !== 'manager-name')) {
    vm.credentials.groups.forEach(function(group, index){
      if (easyToReadKeyFromKeycode === (index).toString()) {
        vm.credentials.groups[index] = !vm.credentials.groups[index];
      }
    })
  }
  $scope.keyList.push(String.fromCharCode(key.charCode));
  //console.log($scope.keyList);
  $scope.$apply();
});

  // add ng-focused and ng-blurred to any input element requiring numbers
    $scope.focused = function (e) {
      enableHotbar = false;
    }
    $scope.blurred = function (e) {
      enableHotbar = true;
    }

    // Manager Name disables keys 1 through 6
    $scope.keyPressed = function(e) {
      console.log(e);
      if ((e.keyCode >= 49 && e.keyCode <= 54)) {
        event.preventDefault();
      }
    }

/* ================================= */

Answer: You have more options to separate JS from controller (to another controller honestly). If you want some singleton usage, you should create service for it. If you want some special functionality without separate view create a filter or directive. And if your special functionality has some view (HTML) create component. This is angularJS basic


Instruction which results in 0 but isn't dependency-breaking

Question: I've developed a little benchmark. The result of the loop inside this benchmark should be transformed to zero and the next round of my calculation should depend on the zero-"result" of the loop before to measure the latency of the code and not its througput. MOVing the result to another register and XORing itself doesn't work because today's CPUs recognize that an XOR with itself isn't dependent on the instructions before. So I tried to subtract the register from itself hoping that the CPU (Ryzen Threadripper 3990X) hasn't such a shortcut like with XOR. I evaluated this with a separate program:
#include <iostream>
#include <chrono>

using namespace std;
using namespace chrono;

int main()
{
    auto start = high_resolution_clock::now();
    for( size_t i = 1'000'000'000; i--; )
        __asm
        {
            sub     eax, eax
            sub     eax, eax
            sub     eax, eax
            sub     eax, eax
            sub     eax, eax
            sub     eax, eax
            sub     eax, eax
            sub     eax, eax
            sub     eax, eax
            sub     eax, eax
        }
    double ns = (int64_t)duration_cast<nanoseconds>( high_resolution_clock::now() - start ).count() / 10'000'000'000.0;
    cout << ns << endl;
}

"Unfortunately" the CPU also does a shortcut here and each instruction takes abut 0.06ns, ie. the CPU does about six sub eax, eax in each clock cycle (4,3GHz).
So is there a way to have an instruction that results in zero and that this instruction is dependent on the instruction before on a moderen CPU ?
Comment: Those aren't "serializing".  In x86 terminology, that means blocking exec of later instructions, and draining the store buffer.  (i.e. serializing / flushing the whole pipeline).  The term you're looking for is carrying a dependency, or not dep-breaking.  I'd recommend looking at sequences https://uops.info/ uses to benchmark latency, e.g.  https://uops.info/html-lat/ZEN+/DIV_R64-Measurements.html#lat2-%3E2 uses AND with a register they zeroed earlier.  (For their throughput tests they unroll a lot more, but a small chain like this is similar to how they use nanobench for latency.)
Comment: Related: [Make a register depend on another one without changing its value](https://stackoverflow.com/q/51646598).  (And my answer happens to start with an answer to your question.)  Possible duplicate of [What is the best way to set a register to zero in x86 assembly: xor, mov or and?](https://stackoverflow.com/q/33666617) which covers the fact that AND isn't dep-breaking.
Answer: Use an and with an immediate of zero.
and eax, 0

The instructions xor eax, eax and sub eax, eax are both recognised as zeroing idioms and won't do the trick.


How to change datatype of the column in derby database?

Question: Iam trying to change the datatype of the column from integer(9) to Numeric(14,3).
but not able to change
i tried below query
<code>alter table TableName alter ColumnName NUMERIC (14,3);
</code>
Comment: possible duplicate of [How to alter a column datatype for derby database?](http://stackoverflow.com/questions/2385020/how-to-alter-a-column-datatype-for-derby-database)
Comment: Rohit, that question describes the way to alter the datatype - looks like you'll only be able to do it by creating a new column, copying the data over, dropping the old column and then renaming the new column.
Comment: What error are you getting?
Comment: @Andrej : that is for decimal to decimal, which is not useful to me.
Comment: @Boneist iam getting syntax error:
Encountered "Numeric" at line 1,Column 50
Answer: hope below one will help.
ALTER TABLE Table_Name ALTER COLUMN Column_Name SET DATA TYPE NUMERIC(14,3);
Comment: Helped me to change the size of the column. but when trying to change the type, again getting syntax error like numeric is not possible type to change.
can you help me on this


Find the limit $\lim_{x\to 0}\frac{\sqrt[5]{1+\sin x}-1}{\ln(1+\tan x)}$

Question: Find the limit $\lim_{x\to 0}\frac{\sqrt[5]{1+\sin x}-1}{\ln(1+\tan x)}$.
I tried subtracting $1$ for using $\lim$ of $e$ but I realized that this is not a problem that can be solved in that way.
Using only algebra, famous limits without L'Hôpital.
Answer: Hint:
$$\lim_{x\to0}\dfrac{\sqrt[n]{1+\sin x}-1}{\ln(1+\tan x)}=\lim_{x\to0}\dfrac{\sqrt[n]{1+\sin x}-1}{\sin x}\cdot\lim_{x\to0}\dfrac{\sin x}{\tan x}\cdot\dfrac1{\lim_{x\to0}\dfrac{\ln(1+\tan x)}{\tan x}}$$
For the first limit, set $$\sqrt[n]{1+\sin x}-1=y\implies\sin x=(1+y)^n-1$$
$$\lim_{x\to0}\dfrac{\sqrt[n]{1+\sin x}-1}{\sin x}=\lim_{y\to0}\dfrac y{(1+y)^n-1}=\lim_{y\to0}\dfrac y{ny+O(y^2)}=\cdots=\dfrac1n$$


C# .NET System.Io.File.Move() does it guarantee file integrity on transfer?

Question: For example, if I'm moving a file over FTP, I believe that does not guarantee file integrity, leaving me to do some sort of checking on file sender/receiver ( checksum for example ).
Can somebody tell me if the .net implementation of System.File.Move has any sort of file integrity checking if I'm moving a file across a network ( local network mind you, but a network still.. ). Checksum or anything?
Comment: [Does the CopyFile function verify that the data reached its final destination successfully?](https://blogs.msdn.microsoft.com/oldnewthing/20120919-00/?p=6563/)
Comment: It's just a wrapper around [`MoveFile`](https://msdn.microsoft.com/library/windows/desktop/aa365239), which is entirely at the mercy of file system filters and drivers. So the short answer would be "no, it has no way of doing that in general".
Comment: To my knowledge it is just the Move command that was part of DOS since 1.0. With all it's limitations. Soemthing like ROBOCOPY might be a better tool for this kind of work, but you may have to use consolerediction to get any usefull data from it.
Comment: FTP uses TCP/IP and TCP/IP does have checksums, so I'm pretty sure FTP also guarantees file integrity (as far as you can guarantee it). Of course no protocol can protect you from disk failure.
Comment: @Wazner: for what it's worth, the TCP/IP checksums are not very large, so errors can still happen. Granted, they are rare. In decades of using computer networks, I've only had one file transfer corrupt. But, there's a reason for crucial files people publish MD5 or SHA hashes.
Answer: Depends on the protocol used to move the file.
Microsoft SMB protocol (most common protocol) does guarantee file integrity. It also supports file locking, meaning that someone else can not modify or partially read the file while the file is being moved/uploaded over the network.
Source: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365233(v=vs.85).aspx


SQL Loop - Add 1 to each batch

Question: Hello I have a file that has batch headers and detail records.  I would like to add a new column that will assign a number to the batch header and then take that number and add it to the detail records.
The data in the first column looks like this.
AAA
BBB
BBB
BBB
BBB
BBB
BBB
AAA
BBB
BBB
BBB
AAA
what i want it to do is this:
The data looks like this
AAA   -   1
BBB   -   1
BBB   -   1
BBB   -   1
BBB   -   1
BBB   -   1
BBB   -   1
AAA   -   2
BBB   -   2
BBB   -   2
BBB   -   2
AAA   -   3
Comment: You mention a file.  Is this (the data) a text file that you want to import?  Or database table that you already have?
Comment: It is a text file that I have imported to a table
Answer: Assuming your file is a text or CSV file that you want to import to SQL Server 2008:

If you need to do this once, I'd fiddle with the file in Excel before
importing it.
If you need to do this on a regular basis, I'd write a
quick console app in .NET to do this for me.  You could then have the app do the push to SQL Server as well to make it a one step process.

If the data is already in SQL Server 2008, I'd still consider doing this in .NET on a record-by-record basis.  .NET is simply a better tool for doing sequential processing than T-SQL is.
If T-SQL is the only tool you have ... it might be possible (using ROW_NUMBER()) to write a couple of batch updates that could do this for you.  But they'd be tricky to get right.  You might have to just use a cursor and attempt sequential processing.
ETA:  If you have SSIS available, you could write a Script Transform to do this for you.  That might actually be the best solution.
Comment: I currently do it in excel, but it is slow and tedious I will look at this .net tool. Thanks

SQL Loop - Add 1 to each batch


Why log in with facebook , url not ok?

Question: When i log in with facebook , it's will get url
for example
http://www.vasplus.info/demos/login_with_fb/index.php#_=_

OR
http://stackoverflow.com/#_=_

what does it mean #_=_ in url ?
Comment: you got any issue when u have #_=_  in url ?
Answer: I think this problem has been resolved in this stackoverflow. The problem you've mentioned has been ask in the past.
Try and see this: https://developers.facebook.com/blog/post/552/

Change in Session Redirect Behavior
This week, we started adding a fragment #= to the redirect_uri when this field is left blank.
          Please ensure that your app can handle this behavior.
Answer: it is because mostly you haven't set the application namespace and refrenece url in the facebook.
when you create app on facebook go to settings of app and set the namespace of the application which will include your domain so that facebook can determine the correct call of app, and reference url on which user will be redirected after successful login
Comment: Namespace cannot fill ulr because can not fill (.) full stop
Comment: namespace is something like the directory where your file is present dont give the name of file in url! like if you file is in www.domain.com/facebook/fblogin.php then your name space will be www.domain.com/facebook

Why log in with facebook , url not ok?


How can I run Ubuntu off USB

Question:
Possible Duplicate:
How do I install Ubuntu to a USB key?

I want to know if it is possible to install and run Ubuntu completely off a flash drive without using my computers hard drive. I want to be able to plug in a USB and boot Ubuntu off it. I can't get passed the install screen, and I'm using version 11.10. If this can be done, please help me.
Answer: Yes, you can do this. Here's how:
http://www.ubuntu.com/download/help/try-ubuntu-before-you-install
Comment: that is NOT the same thing as running ubuntu completely off a usb device.  more elaboration is needed.

How can I run Ubuntu off USB


Github action - node.js CI npm test hanging [Angular9]

Question: new to github actions. I've got everything set up for the most part following the tutorial on ghub's documentation for setting up a nodeJs.yml in the workers dir.
Having this issue where when it gets to the run command of npm test it produces a log saying that it can't open the chrome browser? it tries twice and then it just hangs there. The test suite is in jasmine/karma. At current there are no unit tests apart from the auto generated ones when you create an angular component. Please see attached photos of the .yml set up and the output from the CI action.
I'd appreciate any help you can send my way, I'm new to managing github repo's and can't seem to find any solutions on my own.
If I've missed any important details let me know :)
Thanks for your time guys!
Answer: It seems like ng test is not starting an headless chrome.
Try to replace the test script in the packages.json with ng test --watch=false --browsers=ChromeHeadless (or add a new script dedicated for the CI runs like citest).


Is there a way to disable css rules like unchecking them in devtools of firefox does?

Question: Is there a way to reproduce that but using additional css rules ?

My specific problem is how to disable a framework rule (that i cannot modify or edit) using additional css the same way firefox and chrome dev tools do.
Comment: Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Comment: @Paulie_D I think it should be clearer now
Answer: Disabling code in css while leaving it in place for possible later use is done by commenting it out. All code between /* and */ will not be used.
/* .foo {
  display:block;
} */

Answer: What you might mean is the CSS unset or inherit keyword. By that, you can rule out   CSS-properties assigned from other CSS sources (that probably aren't your own, e.g. coming from some theme files). unset makes it as if it wasn't set in the first place while  inherit makes it inherit the parent's property.
Then just define the selector you're targeting and switch off a certain CSS property, e.g.:
.foo .bar {
    font-family: unset;
}

You might have to enforce that with !important in case your selector is less powerful than some other.
Comment: But remeber unset isn't supported by internet explorer.