android text file import where do i save text file what folder?

Question: So this is a pretty embarrassing question, but i have a text file and java will read all of the words in it and add it to a array, i don't know where to put the text file, like what folder so the comp can go get it? could someone tell me. my code works in a regular java application, so it should work on android.
Answer: you can use
<your-context>.getAssets();

to return an AssetsManager object.
AssetsManager assets = context.getAssets();

You can then open an input stream with the open() method.
InputStream inputStream = assets.open("filename");

The InputStream object is a standard Java object from the IO package.  You can decorate this stream with an object decorator you wish (Reader, BufferedReader, etc).
If you wish to move this file out of the APK (that is not inflated) to the phone you can just copy the bytes of the file from the input stream using an output stream.  Note you will have to have permissions in your write directory (you can do this if your phone is rooted and you have created a shell interface to run native shell commands through JNI).
UPDATE
try {
    InputStream inputStream = this.getAssets().open("test.txt");
    BufferedReader buffer = new BufferedReader(new Reader(inputStream));

    String line;
    while((line = buffer.readLine()) != null) {
        tots.add(line);
    }
}
catch(IOException e) {
    e.printStackTrace();
}

Haven't tested it, but I think this is what you want.
Comment: Could u explain the first thing like what goes in the < > the file name is test.txt
Comment: You need a context object to pull the assets from, IE the getAssets() method is a context method.  So if your in an Activity or anything that inherits from ContextWrapper you can just say "this.getAssets()".  Otherwise you will need to pass a context reference to the function/method that is attempting to get the Assets Manager.
Comment: try {
   FileInputStream textfl = (FileInputStream) getAssets().open("test.txt");
   DataInputStream is = new DataInputStream(textfl);
   BufferedReader r = new BufferedReader(new InputStreamReader(is));
    String strLine;

        while ((strLine = r.readLine()) != null) {
            tots.add(strLine);  //tots is the array list
           }
     } catch (IOException e) {
   // TODO Auto-generated catch block
     e.printStackTrace();
    }
i have that right now and it doesn't work.... do u know a quick fix from that?
Comment: Try using InputStream instead of FileInputStream.  Drop the DataInputStream as you are not using any methods in its decoration, instead use Reader.
Answer: You can put the file to assets folder and use
InputStream stream = getAssets().open(filename);

to get the input stream
Comment: i did this, but now i am getting a error when the code works. that is a link to my new question maybe check it out?http://stackoverflow.com/questions/9676773/read-a-text-file-android
Answer: I created new raw folder in res folder and put chapter0.txt in here.
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.induction);

    wordss = new Vector<String>();

    TextViewEx helloTxt = (TextViewEx) findViewById(R.id.test);
    helloTxt.setText(readTxt());
}

private String readTxt() {

    InputStream inputStream = getResources().openRawResource(R.raw.chapter0);
    // getResources().openRawResource(R.raw.internals);
    System.out.println(inputStream);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

    int i;
    try {
        i = inputStream.read();
        while (i != -1) {
            byteArrayOutputStream.write(i);
            i = inputStream.read();
        }
        inputStream.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return byteArrayOutputStream.toString();
}


Best way to show number of results in a filter using Ajax

Question: First, a quick explanation of my current situation:
My webpage contains a list of (about 40, categorized) filters and a list of 400+ products.
I get the list of products using Ajax. By default 20 products are shown, but when you scroll to the bottom more products are added. Users can filter the results by clicking the desired option. It's like a simplified ebay. Only difference is i don't reload the page when i click on a filter, but instead i use Ajax to get my products.
Now, ebay has these numbers next to every filter option, which shows the amount of results you'd get if you click that option. My question is, What is the best way to show these numbers?
My approach would be to run a sql query (SELECT COUNT(id) FROM sometable WHERE filter='something') for every filter option. However that means i have to run about 40 queries on load, and every time the user clicks an option (using Ajax). This seems like heavy server load, or am i wrong?
Comment: If you already are using Ajax I assume you use Json, why not make the filtering and counting in native javascript? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter and then count the results using .length?
Comment: At the moment i call a PHP script using Ajax, which returns my products. On load 20 products are loaded (sql query: `LIMIT 0,20`). You suggest i load all products on load, put them in an array, and filter using javascript? ps. Yes i'm using json
Comment: Ah well if you want to count the available products in SQL you'll need to do as you suggested, bvery efficient way. Only way to be more efficient are by stored procedures.
Comment: Why not make one extra ajax call at page load just to get the total amount for each filter and keep that in a variable/object? then you can just make your other javascript calls to get your 20 products.
Answer: I'm going with my first approach, but now i'm using UNION queries to get all counts. This way i only have to run 1 query instead of 1 query for every filter.


Custom UITableViewCell, autorelease and other method

Question: (sorry for my english :-)
I'm loading a custom UITableViewCell:
static NSString *CellIdentifier = @"ReminderCell";
ReminderCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {
    NSLog(@"Alloco nuova cella");
    NSArray *objectsInNib = [[NSBundle mainBundle] loadNibNamed:@"ReminderCell" owner:nil options:nil];
    for(id currentObject in objectsInNib)
    {
        if([currentObject isKindOfClass:[ReminderCell class]])
        {
            cell = (ReminderCell *)currentObject;
            break;
        }
    }
} //fine caricamento cella dal Nib

return cell;

I'm setting the owner to nil because I have .m and .h for this cell, and want to have the outlet inside it's own files and not in the UITableViewController. It's working ok.
My question is about correct memory management in this situation.
I understand that loadNibNamed returns an autoreleased array.
Moreover, I understand that the autorelease pool is drained at the end of the current loop.
For this reason, there should be no need to retain my custom cell before returning it.
But, I've heard many times that you shuold assume that an autoreleased object is guaranteed to live only until the end of the method where the autorelease was sent.
Assuming this, I should retain the cell immediately and then autorelease it:
cell = [[(ReminderCell *)currentObject] retain];
//code...
[cell autorelease];
return cell;

Is this correct or should I not worry about this?
Thanks
Comment: Sorry, obviously the autorelease should be inside the if, immediately after cell = [[(ReminderCell *)currentObject]retain]; otherwise I could wrongly over-release other cells (eg. the dequeued cells)
Answer: This is not necessary. Object is not guaranteed to live only until the end of the method where the autorelease was sent - methods are irrelevant here. Object will be released after autorelease pool to which it was added by autorelease method is drained. Since there is no autorelease pool management in your method currentObject will not receive release during its execution.
For example (without ARC of course):
id obj;
NSAutoreleasePool *pool = [NSAutoreleasePool new];
...
obj = [other object];
...
[pool drain];

[obj doSomething]; // DANGEROUS

In your case it is something like:
id obj;
...
obj = [other object];
...
[obj doSomething]; // SAFE


R - Running multiple scripts in parallel

Question: I have 3 R scripts which take a lot of time to run. These scripts run each different data. I would like to run them in parallel. One solution is to run them in 3 different R sessions or 3 different projects as mentionned here or in 3 different batch. The problem is that I need to gather the data returned by these 3 scripts once they have run and complete the rest of computation in a fourth script that takes a lot of time as well. It would need to be done under Windows.

Is it possible to run these 3 scripts in parallel and return the ouput in one workspace to complete the computation with the fourth automatically? If yes, how?

Let's suppose that the answer to question 1 is yes. The fourth script output 3 variables. Is it possible to use them as input to the 3 scripts and loop until a condition in the 4th script is verified?

As an example you can assume the following scripts:
Script1.R
Sys.sleep(10)
a <- 3

Script2.R
Sys.sleep(10)
b <- 5

Script3.R
Sys.sleep(10)
c <- 56

In reality my scripts take 1 hour each to run. I would need to run the 3 above scripts in parallel, retrieve the 3 outputs a,b and c in the same workspace to continue the computation. So instead of having to wait 10 seconds for each scripts to compute I would wait only 10 seconds for the 3 scripts to compute. Alternatively you can take any 3 scripts of your choice that takes a lot of time to compute.
Comment: Use `system()` with `wait = FALSE` to trigger each script in its own R process and write the results to something like an RDS or RData file. Then have your main script run a while loop that periodically checks for the output files and, when all three are present, load them using `load()` or `readRDS()`.
Comment: Please provide a minimal, reproducible example.
Comment: Put it in your question please.
Comment: @Thomas. Thank you for your answer. I think it answers the first question. How would you solve the second one?
Comment: depending on your OS you can use parallel packages like `foreach` to do this
Comment: https://beckmw.wordpress.com/2014/01/21/a-brief-foray-into-parallel-processing-with-r/
Answer: Rstudio has a very reliable, easy and intuitive way of running parallel scripts called Background jobs. This link explains how to use it, but in summary, every time you run a script, it runs in parallel, using multiple cores and it usually goes much faster (if the CPU and RAM are not super busy). There are two ways to use Background Jobs, the manual and the scripted:

The manual way: you just open the background job and select the script and the working directory. Then, in your case, your script should save the objects at local, using saveRSD() or save multiple objects with save(). You can run the script three times (in your case), changing just the line with the object you want to use in each case, save the script and run background job, and then change again the script with the second value, save the script and run the background job again, etc. This way you can run it in parallel but please, check that CPU or RAM do not run at values too close to 100%. And please, do not name a variable/object with a 'c'...

The scripted way: you can use JobRunScript to create background jobs with code. Therefore you can automate the changes you want from the scripts.


Is it safe to append std::string to itself?

Question: Considering a code like this:
std::string str = "abcdef";
const size_t num = 50;

const size_t baselen = str.length();
while (str.length() < num)
    str.append(str, 0, baselen);

Is it safe to call std::basic_string<T>::append() on itself like this? Cannot the source memory get invalidated by enlarging before the copy operation?
I could not find anything in the standard specific to that method. It says the above is equivalent to str.append(str.data(), baselen), which I think might not be entirely safe unless there is another detection of such cases inside append(const char*, size_t).
I checked a few implementations and they seemed safe one way or another, but my question is if this behavior is guaranteed. E.g. "Appending std::vector to itself, undefined behavior?" says it's not for std::vector.
Comment: It should be but like yourself I can't find anything one way or the other.  `str += str;` is legal and it boils down to the same thing so I guess it is fine.
Comment: @NathanOliver: Actually, there's a good reason for not making it illegal. With strings, attaching the same string to itself, or a subset of the string, is reasonable. With `vector`, it's a lot less likely.
Comment: @NicolBolas I get that.  I just wasn't finding the standardies to support my argument.  Looks like Rakete1111 did.
Answer: According to §184.108.40.206/§220.127.116.11:

The function  [basic_string& append(const charT* s, size_type n);] replaces the string controlled by *this with a string of length size() + n whose first size() elements are a copy of the original string controlled by *this and whose remaining elements are a copy of the initial n elements of s.

Note: This applies to every append call, as every append can be implemented in terms of append(const charT*, size_type), as defined by the standard (§126.96.36.199/§18.104.22.168).
So basically, append makes a copy of str (let's call the copy strtemp), appends n characters of str2 to strtemp, and then replaces str with strtemp.
For the case that str2 is str, nothing changes, as the string is enlarged when the temporary copy is assigned, not before.
Even though it is not explicitly stated in the standard, it is guaranteed (if the implementation is exactly as stated in the standard) by the definition of std::basic_string<T>::append.
Thus, this is not undefined behavior.
Comment: I see, thanks - I should have read that definition of `append(const charT*, size_type)` more literally.
Answer: This is complicated.
One thing that can be said for certain. If you use iterators:
std::string str = "abcdef";
str.append(str.begin(), str.end());

then you are guaranteed to be safe. Yes, really. Why? Because the specification states that the behavior of the iterator functions is equivalent to calling append(basic_string(first, last)). That obviously creates a temporary copy of the string. So if you need to insert a string into itself, you're guaranteed to be able to do it with the iterator form.
Granted, implementations don't have to actually copy it. But they do need to respect the standard specified behavior. An implementation could choose to make a copy only if the iterator range is inside of itself, but the implementation would still have to check.
All of the other forms of append are defined to be equivalent to calling append(const charT *s, size_t len). That is, your call to append above is equivalent to you doing append(str.data(), str.size()). So what does the standard say about what happens if s is inside of *this?
Nothing at all.
The only requirement of s is:

s points to an array of at least n elements of charT.

Since it does not expressly forbid s pointing into *this, then it must be allowed. It would also be exceedingly strange if the iterator version allows self-assignment, but the pointer&size version did not.


Finding limit of a sequence in product form

Question: \begin{equation} \prod_{n=2}^{\infty} \left (1-\frac{2}{n(n+1)}  \right )^2 \end{equation}
I need to find limit for the following product..answer is $\frac{1}{9}$.
I have tried cancelling out but can't figure out.
Its a monotonically decreasing sequence so will converge to its infimum..
how to find the infimum?
Comment: Find the infimum is almost always the harder method.
Comment: If you find computing the limit of a sum easier, you might want to find the natural logarithm of your product...
Answer: $$1-\frac2{n(n+1)}=\frac{(n+2)(n-1)}{n(n+1)}=\frac{n-1}n\cdot\frac{n+2}{n+1}$$ waiting for a lot of cancellations
$$\prod_{n=2}^r\left(1-\frac2{n(n+1)}\right)=\left(\prod_{n=2}^r\frac{n-1}n\right)\left(\prod_{n=2}^r\frac{n+2}{n+1}\right)=\frac1r\cdot\frac{r+2}3$$
Now set $r\to\infty$
Comment: Also worth noting that the product of squares is the square of products
Comment: @Henry, please find the edited version
Answer: Hint:
You can write it as $$e^{2\sum_{n=2}^{\infty}f\left(n\right)}$$
Note that $$\log\left(1-\dfrac{2}{n\left(n+1\right)}\right)=\log\left(\dfrac{\left(n-1\right)\left(n+2\right)}{n\left(n+1\right)}\right)=\log\left(n-1\right)+\log\left(n+2\right)-\log n-\log\left(n+1\right)$$
Comment: @Jens. Had a look at your profile. Sing me a song!
Comment: Can you count me in? Thanks. http://www.youtube.com/watch?v=TakqPZu4dEw
Answer: The product is equal to $\left(\frac{2-1}{2+1}\frac{n+2}{n}\right)^2$
and the limit is 1/9.


How can I prevent Gaming Sickness?

Question: Some gamers call me a wimp, but games like Spyro send me reeling and running for the bathroom in a matter of minutes. I get a massive headache, nausea, and sick to my stomach. I can play Portal, Ape Escape, Ico, Shadow of the Collosseus for longer. I think the problem has to do with the free-floating (or controllable) camera.
Is there a way to still play these games and not get sick?
Comment: @ChrisF Spyro isn't a first-person-shooter, and that's the example used by the OP. This question seems to be about the general cases (and the accepted answer gives a wide gamut of reasoning that can apply to FPS as well), so I believe it would be wiser to not tag it with a specific genre.
Comment: Well I can't play most FPS games - I'd feel nauseous in matter of minutes. I'm pretty sure lot more people are there who face the smae problem. For this reason I stick to RTS/ RPG (not those FPS/RPG hybrids) games :)
Comment: Yes, it did improve - but each person is different. A combination of all the suggestions is what worked for me, specifically: Playing in a well-lit environment, a much brighter screen, brightening my game options, and playing in maximized mode. I noticed that with minimized windows, I was always leaning closer to see. To force myself to retain a good distance from the screen, I switched to a non-wheeled chair. I've also upgraded to a newer computer since then (8fps games are now 40fps) and that has been extremely helpful.
Comment: I get game headaches sometimes, after playing games for a few hours on end. You just have to go and do something for a while that doesn't involve a screen
Comment: I get this too. It means I miss out on some great games :-(
Comment: @Grace - OK - no problem. Was going to roll back but @Tobias beat me to it.
Comment: Wait, Portal poses no problems, but Spyro does?  That's unusual :-p  Portal makes me dizzy.
Comment: Spyro makes me sick within a minute, Portal within a half hour.
Comment: Wow. Suddenly grateful that I'm able to game nausea-free.
Comment: During certain free fall animations in certain games give me a slight sensation of falling, if not being near the precipice myself.
Comment: @rlb.usa since you accepted [an answer](http://gaming.stackexchange.com/a/913/88) and more than one year has passed, which of the suggestions worked? Did this improve?
Comment: I've had this happen to me before, but only with one game, GTA4. Every other game I'm fine and can play for hours and hours, but 30 minutes with GTA and my head is pounding, and after an hour I begin to feel nauseous...
Answer: Among other things, you may be sensitive to:

frame rate
strobing or shifting colors
sensation of movement
disparity between visual and other sensory input

Depending on your platform and environment you probably don't have much control over these.  You can try the following, but as David said you should probably consult with your doctor also.

Don't play in a dark room - leave a lamp or other soft light on
Position your chair and screen so that you're sitting comfortably and looking directly ahead at the screen
Play with whatever visual settings are available to maximize frame rate and minimize visual strobing
Back up a bit so that the screen doesn't dominate your vision.  This has two effects - it minimizes the sensory conflict, and also minimizes your awareness of screen refresh/frame rate
Comment: [A game specific question](http://gaming.stackexchange.com/q/29338/88) suggests changing the FOV setting might help as well
Answer: I would talk to your doctor.
Anybody that tells you to try anything could risk your health and I would NOT advise.
Comment: I think this response is a little over the top.  Advice pertaining to your gaming environment hardly needs the intervention of a doctor!
Comment: i don't think anything anyone has said here would risk your health, except maybe the answer that suggested using dramamine. turning on the lights, getting further from the tv, looking out a window every now and then--there's no way any of those things would be a risk to your health
Comment: I think the idea is that one shouldn't assume that difficulty playing games comes from something that only affects game-playing. It's always good to consult with your doctor about things like this; while it's not a bad idea to try some of the remedies listed, make sure to get professional feedback as well to rule out anything serious.
Comment: @Daz Lewis despite the fact that the EXACT SAME MESSAGE is listed by LAW in every video game manual published in the US?
Comment: There is room for such a strong comment in some cases. I have a friend who had a seizure playing Xenosaga some years ago. Nausea, though? Not so much. It's almost certainly some kind of game-induced motion sickness.
Answer: Mythbusters looked at the various anecdotal and pharmaceutical cures for seasickness (which as I understand has the same triggers as stationary motion sickness), and they got positive results from Ginger extract.
Results here: http://mythbustersresults.com/episode43
Your Mileage May vary, but I tried them, to play Halo reach. Normally just looking at the Halo reach Demo makes me feel dizzy and nauseous after a few seconds. I took two ginger pills, waited an hour and then happily played Halo reach for the next four hours with no discernible side effects.
Like I said YMMV, but Ginger pills definitely worked for me.
Answer: The first thing I'd say is ask yourself the following:
What is my gaming environment like?

How much light is in the room?
How far are you from the Monitor/TV/etc.
What are you sitting on?
What is your posture?
Are there windows in the room you can look out of?

Massive headaches and nausea may not just be caused by the game you're playing (though that can be a factor), but also by the exposure to flashing lights.  The human brain actually has a hard time with flashing lights, especially at certain frequencies.  Since a game often doesn't control this, it's not uncommon to experience these types of symptoms.
My advice is the following:

Make sure you're in a well lit room with good ventilation.
Don't play continuously for hours at a time, take 5 minute breaks
Don't get too close to the screen
Remember to Eat properly (you'd be surprised how big a difference a little Vitamin C can make).
Comment: Along with all this, I'd recommend trying to play on a different TV. This could (possibly) cause a different "actual" framerate.
Comment: Eating is very important. Some people don't even realize that they spent five hours without eating anything or even going to the bath room!
Answer: My wife got simulation sickness really easily. As an example, she could play Sims 1 and 2, but not 3. I've been with her for 15 years so I would like to add one more piece of advice to the ones already there:

As soon as you start experience some bad feelings, stop right away and get some fresh air. It will only get worse from that point.
Answer: It is something that affects different people to different degrees. It's similar to motion sickness where the motion cues you get from your eyes don't match the cues you are getting from your ears.
You can only try various things to see what minimises the effect for you:

Take frequent breaks and/or make your breaks longer.
Sit further away from the screen so it doesn't fill your field of view.
Make sure the room is well lit - don't play in a darkened room.
Don't play when tired.
Change the resolution of the screen (if possible). As I mention in the comments, you might find that decreasing the resolution helps as it seems to be more prevalent with newer games. It could be that a lower resolution (and hence less realistic scene) works for most people, but equally it could make it worse for you.

You will need to try these things individually or in combination to see what works best for you. Unfortunately, it might be that none of them actually help.
Comment: How would you suggest changing the resolution?  Should it be bigger or smaller?  Is it to avoid pixelation?  Other than that this is a great answer.
Comment: Does that mean wearing earplugs would help? :)
Comment: @badp - no ;) it's the balance/orientation information not the sound :)
Comment: @StrixVaria - I hesitated to suggest either direction as I fear it may depend on the individual. As it seems to be more prevalent with newer games it could be that a lower resolution works for most people, but I wouldn't like to bet on it.
Answer: Some people suffer from motion sickness if the field-of-view of the games is different from what the brain expects. This is specially noticeable in first-person-shooters. For these people, tweaking the FOV might solve the motion sickness.
See also:

My answer at What field of view should I choose in a first person shooter?
These very informative videos from FZDSCHOOL: EPISODE 29 FOV in Games part 1 and part 2
Comment: All recent [Valve games](http://store.steampowered.com/publisher/Valve) have FOV option ([Team Fortress 2](http://store.steampowered.com/app/440/) is free-to-play; I'm not sure if the demo versions of other games were updated with a FOV setting - but the full version of them has it)
Comment: [TotalBiscuit](http://www.youtube.com/watch?v=DPDq_qvsKUA#t=212): "*Many of you may have noticed and I am one of the people afflicted by this, this is a very, very common thing indeed that if you are playing a game on a monitor, particularly a large monitor ... you are sitting there playing your game and you will get headaches, you will feel perhaps nauseous, you will feel lightheaded, it will be an unpleasant playing experience ... it's like having tunnel vision all the time, and your brain doesn't like it*"
Comment: The accepted answer mentions *"disparity between visual and other sensory input"*, but this one nails it. Watch the FZDSCHOOL links, people.
Comment: Good to see someone's explaining this scientifically. This information needs to be given to more first-person game developers! Can you give an example of a game with changeable FOV so I can try it out?
Answer: I used to have this problem when I started playing FPS games on my PC, and I know how much of a drag it is. I found that on my PC monitor if I dropped the game resolution to less than full screen it would minimize the motion sickness feeling. And after playing in less-than-fullscreen for a while the sickness went away.
As a bonus to overcoming that form of sickness I can now read in a car without getting sick, which is pretty cool. I used to get very queasy very soon if I put my head down to read while in a car.
If you're console gaming on a TV I would suggest moving away from the TV enough that it isn't taking up the biggest portion of items in your view. If you make the screen dominate your field of vision it will enhance the feeling that you're really moving.
Answer: I find myself suffering from headaches quite quickly when gaming (not when browsing weirdly) and have found the following things useful:

Only play in a room which is well lit
Try to put your monitor against a light background, so there is less contrast between the screen and the surrounding environment
What type of monitor are you using? TFT? CRT? If it's a CRT switch to a TFT, if it's a TFT you could look at monitors with a higher refresh rate (120Hz~).

I don't know if anyone else has had any experience with this, but I've also looked into glasses with a special anti-glare coating on them in the past the most "recommended" of which being from these guys: http://www.gunnars.com/technology/
They might help with the headache side of things?
Answer: I get this, and, for me at least, it's plain old motion sickness. Generally, I just try not to sling my mouse around as much until I get used to it. Like with seasickness, you can habituate yourself to the motion, and it'll stop bothering you. In my case, 6-8 hours cures me, and as long as I play regularly, the symptoms never return.
Of course, it can also be epilepsy, so might want to get yourself checked, or check yourself by looking at a seizure pattern (goes without saying, make sure someone is around).
Answer: I had this problem all my life and pretty much never played FPS or similar games. Anyway, when Skyrim came out someone suggested to me that I try travel sickness pills. I bought a pack, took one an hour before I started playing, and for the first time in my life felt completely fine playing in FPS! I found that, after the pills ran out, I was so used to playing that the sickness never came back.
Comment: I had this same experience in Skyrim and corrected it by always playing in a lit room with the brightness up to 100%, and on the 3rd person POV.
Answer: It's possible that Dramamine or other motion sickness remedies (like those bracelet things) could help for this kind of thing.
Comment: I do hope you're not talking about those "Power Band" things. Those are completely placebos. (though it may be help just by thinking that they'll help, oddly enough)
Comment: @Earlz The ones with the hologram inside? Yeah, totally placebo. https://en.wikipedia.org/wiki/Motion_sickness#Treatment has a bunch of things, some of which (like the bracelet) are potentially pseudo-science.
Answer: I heard that you can use some bracelets called "Sea Bands."  They supposedly put pressure on a nerve in your wrist that is supposed to send the signal for nausea to your brain.  By putting pressure on it, it prevents the signal for nausea to go to your brain and prevents motion sickness.
Answer: Sony's game manual suggests when playing video games to avoid some of the ill induced symptoms by doing the following:

Play in a well lit environment or with a light basically behind the screen
Play on a small TV screen probably anything under a 27" TV
Sit back as far as you can from the TV
Take breaks, if you beat the game or lose on the first 2 or 3 attempts.. 15 minutes or more..
Avoid playing when you are tired or need sleep.

If you read most game's manuals, the warnings are on the first page. I've  failed to do that at one point and now I'm wiser than before ha!
From my personal experience, your brain and normal breathing is off track which can put your body into fight or flight mode or panic mode over long or short periods of game play. Remember , your brain controls your breathing patterns. Why you think you feel exulted after playing some of those fast paced high action games? Thats where the Nausea and feeling like you want to vomit comes into play.
Answer: No other answer addresses Spyro directly, so this might help as well:
Most Spyro games have two camera modes: "Active" and "Passive".

Active mode will always try and re-center the camera behind Spyro, so whenever you start walking/sprinting/gliding it will snap back behind him again. This can be jarring, especially if you start sprinting in a direction other than forward.
Passive mode will instead reduce the camera's movement by keeping the camera facing the same direction, even when Spyro is walking side to side, or directly towards the camera, leaving it up to the player to reorient the camera manually in most situations.

You might find Passive mode a bit easier to deal with, as it will not throw the camera around too much, instead relying on you moving the camera yourself to reorient when needed.
Answer: The only thing I can suggest is fresh air and a break. Having a fan pointing directly on your face helps a lot and gives you a bit of extra time.
Answer: My advise is to read the first page of your manual that tells you how to avoid some of these issues...Now here'a a really big problem that people overlook when playing video games, its your off pattern breathing.. You playing games and your mind concentrating on the game and your breathing pattern gets off track ..That signals the brain that something is wrong and that's where you get your NAUSEA in the stomach as well as the HEADACHES comes in ..I stopped playing because i can't balance my brain and breathing correctly... The games are in excitement mode   and your brain is not use to that kind of constant action ..Again most of the games are in hyper pattern speed in which the brain cant keep up with as well as your breathing ..It's more to it than just flashing light, sitting far away from the tv and etc ...If they just kill the hyper speed patterns from games in a more slower moment , then it would'nt be such as bad...
P.S. Mind and breathing if they are not regulating normally, then you are going to have some health issues......
Answer: Video games re-wires the brain because it was not made for this kind of activity and in many instances can cause you great distress.
 From my personal experiences from playing high action intense games will put your body in fight or flight response or great distress for some people. Blurred vision, tense muscles, continued headaches and etc. are signs too from flight response too.
If you play games like mind games, Family Feud, puzzles, board and card games or casino games, they require any excitable reactions. You can play them for hours with little or any side effects. For as high action games, the brain regulates your breathing and when the two are out of balance, the body goes into total chaos. Why you think you have nausea after you played certain games?
And that doesn't end there. Why you feel fatigued after you play certain games? The brain can't keep up with the hyper speed patterns of some games while it's trying to regulate your breathing as well. It can't keep up with 2 jobs (brain). The best thing to do is try to balance your breathing and brain in practice mode because high action games overstimulates your brain like your in a flight or fight response.
It's not always about frame rate and lighting. Your out of regulating breathing is cause you nausea along with your brain. Play smart and safe.
As for me, I've retired from high action intense games.

How can I prevent Gaming Sickness?


Is it possible to publish component revisions within workflow?

Question: Our current setup is that we have two targets, Staging and Live. Collaborators may update the affected component while it is still within the workflow. A final activity is set to publish the related pages to Live. Is it possible to publish component updates (revisions e.g. 2.2, 2.5) to Staging from within the workflow?
The TOM API documentation for Page.Publish() method does not seem to have an input parameter to fullfil such purpose.
EDIT: Additional details to our current setup: The page we're trying to publish has a "custom renderer", so to speak. The page template is setup to pull components from a certain folder recursively and build the HTML accordingly. The method used is Folder.GetItems(OrganizationalItemItemsFilter). It retrieves the list of components together with their data. The page doesn't have component presentations.
Answer: For standard Tridion solutions i.e. using Page+ComponentPresentations+Workflow, this will suffice:
Setting activateWorkflow parameter to True in the Publish() method will publish the workflow revision. It's the 3rd parameter:
Public Function Publish( ByVal targets As Variant,
            ByVal activateBlueprinting As Boolean,
            ByVal activateWorkflow As Boolean,
            ByVal rollbackOnFailure As Boolean,
            Optional ByVal publishTime As Date = 0,
            Optional ByVal unpublishTime As Date = 0,
            Optional ByVal deployTime As Date = 0,
            Optional ByVal resolveComponentLinks As Boolean = True,
            Optional ByVal priority As TDSDefines.EnumPublishPriority = Normal,
            Optional ByVal ignoreRenderFailures As Boolean = False,
            Optional ByVal maximumRenderFailures As Long = 0 ) As String

Reference: TOM API Documentation: "activateWorkflow | Indicates whether the item is being (un-/re-)published from the user's work list."

However, if customized renderers are used to build page output, like when using Folder.GetItems() to retrieve components in templates, additional calls would be required to actually retrieve the latest revision of components such as the version-zero -v0 trick by Nuno.
Please note that if you decide to do this, the latest revision will always be published to your targets and it may not exactly be "approved" content.
Comment: You have to execute the publish as a user who has permission to view the revision in WF. That means doing either as an Admin, or as the user that currently owns the WF item (explicitly as that user, or by impersonation). There's a good chance that your custom renderer doesn't do this. Do you have access to the Tridion Forum? There's an interesting discussion on how best to get the revision at https://forum.sdltridion.com/topic.asp?TOPIC_ID=7504.
Comment: I tried to use `activateWorkflow` parameter and it worked for one of our workflows. Thank you.

However, it still didn't publish the revision for another workflow that publishes a page using a "custom renderer". Please refer to my recent update to the question.
Comment: Yeah, I do have access to the forums. I have to try the `-v0` trick and impersonation from the template. You may be right, the `Folder.GetItems` method may only be retrieving the latest version (not revision).
Comment: Jeremy, the `-v0` trick worked as well and we're able to get the latest revision from the template. Thanks for helpin out man! I've edited your answer above to provide the distinction between the `Publish()` and solution for our custom renderer. Feel free to edit if something is not clear. Thanks again!


How to get old 16-bit Windows games to work on 64-bit Windows?

Question: Trying to play some old Windows 95 games on Windows 7 64-bit, I'm getting the following error:

The version of this file is not compatible with the version of Windows you're running. Check your computer's system information to see whether you need an x86 (32-bit) or x64 (64-bit) version of the program, and then contact the software publisher.

Trying to run the application in compatibility mode has no effect. I'm guessing these games somehow rely on 32-bit dlls which are missing from my system, and I would like to know if anyone else has encountered a similar problem and is able to give insight as to possible solutions or work-arounds.
Notes:

I've checked this question but it discusses system requirements and not actual application invocation.
The games in questions are Metal Marines and Fire Fight, but I'm sure many more might be affected.
The error message above is not game-specific, it comes directly from Windows itself.
Comment: Related: http://superuser.com/questions/333103/is-it-possible-to-run-an-old-16-bit-dos-application-under-windows-7-64-bit
Comment: Related: [Win3mu](https://www.toptensoftware.com/win3mu/) - an open source Windows 3.0 emulator. It includes an 8086 CPU emulation that loads 16-bit Windows executables and maps API calls onto the modern 32 or 64-bit Windows API.
Comment: Why was this voted to be closed as off-topic? I realize the problem is not specific to game executables, but it is a common obstacle faced by people wanting to play (old) games, and that's one of the pillars of this community, right?
Comment: @Joachim "the problem is not specific to game executables" by itself is enough to make a question off-topic in my opinion.
Answer: It's actually quite likely that these games are relying on old 16-bit DLLs. A lot of early 32-bit software relied on old 16-bit DLLs for some functions, as they did the job, they weren't used in a performance critical part of the software and there was no need to look for 32-bit versions. (for example until fairly recently the install software was often 16-bit, so much so that Win7 actually detects that and silently replaces with it's own 64-bit version of the old DLL).
Have you looked at Windows 7's XP Mode? This runs an entire copy of 32-bit Windows XP within your Windows 7, letting old programs run within XP without the program knowing it's on a 64-bit Win7 machine at all, and as it's all integrated you will hardly notice that it's running in XP.
Windows 7's XP Mode: what it is, how it works, who it's for
Comment: Keep in Mind the version of Windows 7 that includes XP mode is Windows 7 Professional. The Home edition does not include that, from the start. However most computer stores even retail stores fail to mention that most computers sold with Windows 7 home premium actually are Windows 7 professional in locked down mode until you purchase a key code at Staples or any other retailer or even online that will fully unlock Windows 7 from the home Edition to Windows 7 Professional that includes the XP Mode. And true In XP mode all your older games should in theory run without a problem. Another trick is
Comment: +1 I didn't even know that this mode existed, now I need to get Windows 7 so I can play all of my XP games that got busted during the vista transition.
Comment: Actually I was referring to Win95-era games which run fast even without 3D acceleration; in general, however, you are correct that it's a pretty poor emulator for gaming.
Comment: Although it's unlikely you're using the Starter edition, XP Mode is not available for that edition of Windows 7.  Also, it requires certain hardware support that may or may not be enabled in the BIOS even if it is available on your hardware...  Other than, that, I love XP Mode.  :)
Comment: Still some issues with it, but in general it was a success so answer accepted :)
Comment: @Noctrine While XP Mode is fantastic, it does not have hardware acceleration support, so don't plan on playing any DirectX games.
Comment: XP Mode is useless for games, as there's no 3D acceleration. It's only meant for business applications that have trouble running natively in Windows 7.
Comment: 16-bit programs don't work on 64-bit Windows at all, DLLs or not. Apparently video modes are a big reason they don't always work on 32-bit, in addition to your suggestion about DLLs.  http://support.microsoft.com/kb/926657
Comment: @Oak: XP mode is not meant to be able to support games.  It was included specifically for business apps that have compatibility issues.  It's all based on [Virtual PC](http://www.microsoft.com/windows/virtual-pc/) but integrated into Windows 7.  So don't expect to get anything to work using this.
Comment: @user17930 - Actually what you say really isn't true.  Windows 7 Home Premium there is no such thing as a "locked down" version of Windows 7 Professional.
Answer: 16-bit games will not work on Windows 7 64-bit as it lacks WOW (Windows on Windows), a program included with 32-bit Windows NT versions (including XP) that provided support for legacy 16-bit applications.
The 64-bit versions of Windows have their own emulator: WOW64, which allows now-legacy 32-bit applications to run on the 64-bit operating system.
Answer: Updated answer, just in case anyone stumble with that question in 2021 or later:
You can play Windows 16-bit games in a 64-bit Windows computer by using DOSBox-X. Install Windows 95 (or Windows 98, depending of the game requirements) inside a DOSBox-X virtual disk, and use it to install and play the game.

https://dosbox-x.com/wiki/Guide%3AInstalling-Windows-95

https://dosbox-x.com/wiki/Guide%3AInstalling-Windows-98

You may need to do some tweaks in order to get the best performance of that game, but that will make you capable of playing the game without using a dual boot. You may also be able to add the game launch to Windows 96/98 startup, which will give a more immersive experience.
DOSBox is basically a virtual machine, so the game won't have access to the same amount of resources as if it was being played in a 32-bit dual boot, but seriously, if it's a Windows 16-bit game, it won't demand that much anyway.
Answer: Actually you can run 16-bit Windows Apps under Win7 32-bit system. Only Win7 64-bit does not support Win16 Apps. So you may also consider to install Win7 32-bit OS into a separate partition just to play most old games (From Win3.x era up to WinXP...)
Answer: There are many games that run fine on 64-bit, only that the installer is limited to 16/32 bit.
I found a great article that explained the problem:
http://www.reactos.org/forum/viewtopic.php?t=10988
Basically, I could copy the contents of the CD to a local folder, copy in the correct 32 bit installer (the article explains how to find which installer is needed, and links to the correct installer).  Once the installer was in the correct location I could run it, install the game and then change some registry details to point to my real CD drive (as it would often use the temp directory).
I recently used this method to install Indiana Jones and the Infernal Machine on Windows 8 / 64-bit.  I played the game from start to finish.
Comment: Some other games of that generation (like the first Command & Conquer) require an InstallShield unpacker tool like WinPack to actually get to the game files though.


Multiplying using reciprocal, addition and subtraction

Question: Let $a,b\in\mathbb{R}$. How can we compute $a\times b$ using only the following operations only (with any reals) :

$\frac{1}{*}$ (inverse)
$*+*$ (addition)
$*-*$ (subtraction)

?
Comment: Are you allowed to use numbers other than $a$ and $b$ ?
Comment: I don't understand why you edited the title. The old title seemed better to me.
Comment: @BenMillwood Ok i changed it back
Comment: Are you sure it isn't $*/*$ (division of any pair) instead of inverse $1/*$?
Comment: @kwak Yep i'm sure
Comment: Are you allowed to take a limit?
Comment: @phs no i'm not
Answer: I claim it is impossible. Let $a = b = \sqrt{2}$. Then any number you can make with your operations is a rational multiple of $\sqrt{2}$, and in particular you cannot make $ab = 2$.
edit: this answer was given when it was unclear whether the use of arbitrary real constants was allowed. I assumed they were not, but the question has since been edited to indicate they are. I'm keeping this answer anyway because people seem to like it.
Comment: @Bananarama: I believe it's correct also. To be slightly more general, the set of rational multiples of $\sqrt{2}$ (which includes $0)$ is closed under these operations, but this set is not closed under multiplication. I managed to get $\frac{a^2}{b}$ (and hence also $\frac{b^2}{a},$ $\frac{a}{b^2},$ $\frac{b}{a^2})$ by combining $\frac{1}{a-b} - \frac{1}{a+b},$ then taking the reciprocal, then adding the last result to itself, then adding $b,$ but I wasn't able to do anything with this.
Comment: I'm pretty sure this answer is adequate.
Comment: Are you sure that $\frac{1}{\sqrt{2}-1}= 1 + \sqrt{2}$ is a rational multiple of $\sqrt{2}$?
Comment: In fact, $0-\left( \frac{1}{1-\sqrt{2}} + \frac{1}{1+\sqrt{2}} \right) = 2$.
Comment: @seaturtles:  I see no restriction on the constants used.  This is the reason I upvoted lhf's still unanswered inquiry.  (In my own experimentation, I have only permitted myself constants from $\mathbb{N}$.)
Comment: (Several comments have been deleted above)
Comment: @EricTowers How did you get $1$ by adding, subtracting and reciprocating with $\sqrt{2}$?
Comment: @Eric Towers: I just saw your comments and I don't understand their relevance to what I wrote. Specifically, let $\cal{S} = \{r\sqrt{2}:\; r \in {\mathbb Q}\}.$ Then my claim is that none of the three specified operations applied to elements in $\cal S$ produce, when defined, an element not in $\cal{S}.$ (Note I was incorrect in saying this set is closed under these operations, since the reciprocal of zero is undefined.) None of $1 + \sqrt{2},$ $1 - \sqrt{2},$ or $\sqrt{2} - 1$ belong to the set $\cal{S},$ so I don't see their relevance.
Comment: The question has now been edited so that this answer is wrong. But I still like it, so I'm leaving it there.
Answer: Build first the square function, as follows.
If $x\neq -1,0$, then $\displaystyle x^2= \frac{1}{\frac{1}{x}-\frac{1}{x+1}}-x$
Squaring $0$ and $-1$ is trivial.
Now, $\displaystyle xy=\frac{(x+y)^2-(x-y)^2}{4}$
Comment: How do you get $x+1$ from $x$ and $y$ and the use of the three operations?
Comment: @DaveL.Renfro Ask OP what's allowed and what's not.
Comment: It seems pretty clear that "adding $1$" is not allowed. As to what is intended, this also seems clear, with the possible exception of a universal quantifier at the beginning and restriction to finitely many uses of the operations: For each choice of two real numbers, $a$ and $b,$ is it possible to obtain their product by finitely many applications of the three operations (in any order) to these numbers? For some choices this is possible (i.e. $a=1$ and $b=42,$ or $a=\sqrt{2}$ and $b=42$) and for other choices this is not possible (Ben Millwood's answer), so the universal statement is false.
Comment: @Dave I think he modified the statement 15 mins ago "using only the following operations only (with any reals) ". But I got your point.
Comment: I didn't notice the modification having been made until you mentioned it. I'm deleting my last comment because I don't think it's entirely appropriate for this site. (But I'm still thinking it . . .)
Comment: How do you divide by $4$?
Comment: I suppose you can make $4xy$, then make $1/4xy$, then add it to itself four times to get $1/xy$, then reinvert it.
Comment: @Ben I think OP authorized the use of arbitrary numbers. It's as if he had a calculator where the $\times$ button is broken.
Comment: @G.T.R: yes, but they didn't authorise the use of division :)
Comment: @Ben $\frac{a}{4}=\frac{1}{\frac{1}{a}+\frac{1}{a}+\frac{1}{a}+\frac{1}{a}}$


How can I use a query of id's for another query with eloquent - Laravel

Question: I am new to back-end development and I am trying to use an intermediary table inside my controller to select the campaigns from user 5. So far I get the following error with the following code. I don't really understand what the error means and the google results are not really helping.

"stripos() expects parameter 1 to be string, object given"

public function index()
{
    $userCampaignIDs = CampaignUser::where('user_id', '5');
    $campaigns = Campaign::findMany('id', $userCampaignIDs);
    return $campaigns;
}

Answer: Because $userCampaignIDs is not an array, but a QueryBuilder.
You have to get an array to use findMany, like this :
$userCampaignIDs = CampaignUser::where('user_id', '5')->get()->pluck('id');

But, you have to use Eloquent relations to get your relations more easily, like :
$userId = 5;
$campaigns = Campaign::whereHas('campaignUser', function($query) use ($userId) {
    $query->where('user_id', $userId);
})->get();

I suppose there is a relation between Campaign and CampaignUser


Install dlib error not found cublas_v2

Question: Trying to install dlib with GPU support.
Use tf image
FROM tensorflow/tensorflow:latest-gpu-py3

Install cudnn
COPY cudnn-9.0-linux-x64-v7.1.tgz ./
RUN tar -zxvf cudnn-9.0-linux-x64-v7.1.tgz
RUN cp -P cuda/include/cudnn.h /usr/local/cuda/include
RUN cp -P cuda/lib64/libcudnn* /usr/local/cuda/lib64
RUN chmod a+r /usr/local/cuda/include/cudnn.h /usr/local/cuda/lib64/libcudnn*

And than install dlib
RUN git clone https://github.com/davisking/dlib
RUN cd dlib && python3 setup.py install

I get this error

[  1%] Building NVCC (Device) object
  dlib_build/CMakeFiles/dlib.dir/cuda/dlib_generated_cuda_dlib.cu.o [
  1%] Building NVCC (Device) object
  dlib_build/CMakeFiles/dlib.dir/cuda/dlib_generated_cusolver_dlibapi.cu.o
  /notebooks/dlib/dlib/cuda/cusolver_dlibapi.cu:9:23: fatal error:
  cublas_v2.h: No such file or directory compilation terminated. CMake
  Error at dlib_generated_cusolver_dlibapi.cu.o.cmake:207 (message):
  Error generating
  /notebooks/dlib/build/temp.linux-x86_64-3.5/dlib_build/CMakeFiles/dlib.dir/cuda/./dlib_generated_cusolver_dlibapi.cu.o

if I don't install cudnn dlib builds successfully but with notification that it doesn't use CUDA.
Tried to google but people write to set USE_CPU_ONLY=1 (they have the error for caffe) which is not what I need.
Answer: Got the same problem. Install cublas-dev (sudo apt install cuda-cublas-dev-9-0) solved it for me.
Comment: for now name changed to libcublas-dev-...

    `cuda-cublas-10-0  - CUBLAS native runtime libraries;  cuda-cublas-dev-10-0  - CUBLAS native dev links, headers`

but

    `libcublas-11-0 - CUBLAS native runtime libraries;    libcublas-dev-11-0 - CUBLAS native dev links, headers`

Install dlib error not found cublas_v2


How to enable php5-mysql in ubuntu 16.04 trough cli?

Question: I want to enable the module php5-mysql in my Ubuntu 16.04 trough the cli.
When I do apt search php, I see php5-mysql is there.
Then run apt-get install php5-mysql and that is what I get :
root@25814ad2fc62:/var/www/html# apt-get install php5-mysql
Reading package lists... Done
Building dependency tree
Reading state information... Done
php5-mysql is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 8 not upgraded.

So the conclusion is that this module is installed but not enabled.
Following that post, I see run the command php5enmod mysql and have no messages or errors.
After run php -m I see that mysql is not there:
root@25814ad2fc62:/etc/php5/mods-available# php -m
[PHP Modules]
Core
ctype
curl
date
dom
ereg
fileinfo
filter
ftp
hash
iconv
json
libxml
mbstring
mysqlnd
openssl
pcre
PDO
pdo_sqlite
Phar
posix
readline
redis
Reflection
session
SimpleXML
SPL
sqlite3
standard
tokenizer
xml
xmlreader
xmlwriter
zlib

[Zend Modules]

And these are available modules in my machine:
root@25814ad2fc62:/etc/php5/mods-available# ls
mysql.ini  mysqli.ini  opcache.ini  pdo.ini  pdo_mysql.ini  redis.ini

So, how can I enable this mysql module in this instance of my php?
I am running inside a docker container.
Answer: Edit the file:
sudo nano /etc/php5/mods-available/mysql.ini

And make sure it contains an uncommented line like this:
; configuration for php mysql module
; priority=20
extension=mysql.so

Lines starting with ; are comments and are ignored.
Restart apache or nginx or php-fpm after this change.


GTA 5 cannot save game

Question: Every time it tells me to sign in, and I sign in but then it says sign in again so I do, and the cycle continues. So I pressed (B) and went into the game, but it won't let me save, as it says I'm not signed in.
Answer: Sometimes Socialclub will go down (usually after a patch). You can check the rockstar games website to see their server status if the issue still persists.

GTA 5 cannot save game


What's the difference between "Highest Kill Streak" and "Kill Streak Bonus"

Question: When I look at the bottom of my stats in Battlefield 3 in the battlelog, under "All time statistics" there are "Highest Kill Streak" and "Kill Streak Bonus" listed with the same number, 20 in my case. I've checked countless other profiles and I didn't find a single one where the numbers were different.
So, do they actually mean the same thing and they screwed it up somehow?
Or is the difference so subtle that people having different numbers are rare?
Answer: In the stats API, there is only one of these stats: killstreakbonus. Which would very strongly suggest, that both "Highest Kill Streak" and "Kill Streak Bonus" are just different display names for same stat.
Comment: I think you're right, but bf3stats.com has no affiliation with EA or DICE.


Aluminum wire size needed for new 60 amp garage panel 130' from main 200 amp service in house?

Question: What size aluminum wire for a new 60 amp garage panel to be fed from a 200 amp main service in my house 130' distance?  How many wires?
Comment: If you are running 60A wire and a 60A breaker in the main panel, feel free to upsize to a larger sub-panel, which will give you more breaker spaces.  The 60a breaker will continue to protect the wires, and a 100A sub-panel can obviously handle 60A.  The "main" breaker in the sub-panel can be ignored.
Comment: Attached or detached garage? And are you running a *cable* or wires in conduit?
Comment: Assuming US/Canada, 4 wires for standard 120/240VAC service. Hot, Hot, Neutral and Ground. Neutral and ground isolated under current code.
Comment: The garage is unattached. The wire run is 30' through he house rafters, then 22' outside the house in conduit, 10' drop into the ground, 50' underground in conduit, and then 8' up from the ground  in conduit and into the new garage panel box.
Answer: Number 4 aluminum is good for 65 amps at 130' the voltage drop at 60 amps would be 2.55% . Up to 3% is allowed by code.


If $|z|^2+\bar{A}z^2+A(\bar{z})^2+B\bar{z}+\bar{B}z+c=0$ represents a pair of intersecting lines.... find the value of $|A|$.

Question:
If $|z|^2+\bar{A}z^2+A(\bar{z})^2+B\bar{z}+\bar{B}z+c=0$ represents a pair of intersecting lines with angle of intersection $'\theta'$ then find the value of |A|.

I tried using general equation of straight line in complex form as $a\bar{z}+\bar{a}z+b=0$ where b is real,where slope of line is $\frac{-a}{\bar{a}}$ and multiplying two such lines and then compairing coefficient.I found that c is real and used $$\tan(\theta)=\big|\left(\frac{\text{slope}_1-\text{slope}_2}{1+\text{slope}_1*\text{slope}_2}\right)\big|$$
one thought was also that the use of $|z_1+z_2|^2=(z_1+z_2)(\bar{z_1}+\bar{z_2})=|z_1|^2+|z_2|^2+\bf{z_1\bar{z_2}+z_2\bar{z_1}}$
But this is becoming very long and I think this is also not much effective and there should be some good way, is there a better way out ?
Answer: If the given equation defines two intersecting lines then we can translate them such that they  intersect at the origin. (Replace $z$ in the equation  by $z+p+iq$, and determine $p$ and $q$ such that there are no linear terms in $z$, $\bar z$ appearing. The constant term will then automatically be zero, or we would not have two lines.)
The new equation is
$$z\bar z+\bar A z^2+A\bar z^2=0,\qquad A=a\, e^{i\alpha}\ne0\ .\tag{1}$$
The map $$T:\quad{\mathbb C}\to{\mathbb C}, \qquad z\mapsto w=e^{-i\alpha/2}\, z$$ is a rotation. It  moves the two lines into the $w$-plane without changing the angle of the intersection. The equation there is obtained from $(1)$ by letting $z:=e^{i\alpha/2}\,w$, hence is
$$w\bar w+a(w^2+\bar w^2)=0\ .$$ With $w=u+iv$ this means $(u^2+v^2)+2a(u^2-v^2)=0$, or
$$v=\pm\sqrt{{2a+1\over2a-1}}\>u\ .$$
These are two lines symmetric to the $u$-axis. It follows that
$$\tau:=\tan{\theta\over2}=\sqrt{{2a+1\over2a-1}}\ ,$$
so that
$$\cos\theta={1-\tau^2\over1+\tau^2}=-{1\over2a}\ .$$
This implies
$$|A|=a=-{1\over2\cos\theta}={1\over2\cos\theta'}\ ,$$
where $\theta'$ is the angle $<{\pi\over2}$ between the two lines.
Comment: @user69608: When the angle between the descending and the ascending line is $\theta$ then the angle between the positive $u$-axis and the ascending line is ${\theta\over2}$.
Answer: Let $L$ be a straight line on the Argand plane. Since we can rotate $L$ to obtain a vertical straight line and the equation of a vertical straight line on the closed right half plane is given by $\Re(z)=x$ for some constant $x\ge0$, the equation of a general straight line is given by $\Re(\omega z)=x$ for some complex number $\omega$ on the unit circle. It follows that if the angle between two lines $\Re(\omega_1 z)=x_1$ and $\Re(\omega_2 z)=x_2$ is $\theta'$, then $|\cos\theta'|=|\Re(\omega_1\overline{\omega_2})|$.
Now suppose $z$ lies on the union of the two lines $\Re(\omega_1 z)=x_1$ or $\Re(\omega_2 z)=x_2$. Then
$$(\omega_1 z+\overline{\omega_1 z}-2x_1)
(\omega_2 z+\overline{\omega_2 z}-2x_2)=0.$$
Expand the LHS, we obtain
$$2\Re(\omega_1\overline{\omega_2})|z|^2
+\omega_1\omega_2 z^2
+\overline{\omega_1\omega_2}\,\overline{z}^2
+pz+\overline{pz}
+r=0,$$
where $p$ and $r$ are some constants. If this equation is equivalent to
$$|z|^2
+\overline{A}z^2
+A\overline{z}^2
+\overline{B}z
+B\overline{z}
+c=0,$$
by comparing the coefficients of $|z|^2$ and $\overline{z}^2$ in both equations, we have $2\Re(\omega_1\overline{\omega_2})A=\overline{\omega_1\omega_2}$. Hence
$$2|\cos\theta'||A|=2|\Re(\omega_1\overline{\omega_2})||A|=1.$$
Comment: nice solution! what motivated you to think like this?
Comment: @user69608 I don't know. I just wanted to find an equation of the straight line that is "angle-friendly" and based the proof on that.
Answer: The equation of a line when it's slope is known can be written in the form of complex numbers as
$$z (m+i) + \bar z(m -i) + 2c = 0$$
(you can derive it from $y=mx +c$ form, and for clarity I didn't assume $m-i =A$ and didn't write $2c=B$)
So, it is given to us that
$$
|z|^2+\bar{A}z^2+A(\bar{z})^2+B\bar{z}+\bar{B}z+C=0
$$
represents two straight lines, therefore that equation can be broken down in the form
$$
\left[z(m_1 +i) + \bar z (m_1 - i) + 2c_1\right] \times \left[z(m_2 +i) + \bar z (m_2 -i) + 2c_2\right]=0~~~~~~~~~~~~~~~~~(i)$$
Where $m_1$ and $c_1$ are the slope and y-intercept of first line, $m_2$ and $c_2$ are the slope and y-intercept of the second line. Multiplying that out, we get
$$
z^2(m_1 +i) (m_2 + i)  + \bar{z}^2 (m_1 - i )(m_2 -i) + |z|^2 \left[(m_1+i)(m_2-i) + (m_1 -i)(m_2 +i)\right] \cdots = 0$$
By comparing the coefficients, we have
$$
\bar{A} = (m_1+i) (m_2+i) \\
A = (m_1 - i)(m_2 -i) \\
\\
(m_1 +i) (m_2 -i) + (m_1 -i)(m_2 +i) =1 \\
\\
\tan \theta = \frac{m_1 -m_2}{1+m_1 m_2}$$
Now, we can obtain something by doing some algebra:
$$
(m_1 +i) (m_2 -i) + (m_1 -i)(m_2 +i)=1 \\
m_1m_2 = -\frac{1}{2} ~~~~~~~~~~~~~~~~~~~~~~(1)$$
$$\tan \theta = \frac{m_1 -m_2}{1+m_1 m_2}\\
\tan \theta + \tan \theta (m_1 m_2) = m_1 - m_2 \\
\left(\frac{1}{2} \tan \theta\right)^2 = m_1^2 + m_2^2 - 2m_1 m_2 \\
\frac{\tan^2 \theta}{4} -1 = m_1^2 + m_2^2~~~~~~~~~~~~~~~~~~~(2)$$
$$
|A|^2 = A \bar{A} = m_1 ^2 + m_2^2 + (m_1m_2)^2 + 1 \\
\text{from eqaution (1) and (2)} \\
|A|^2 = \frac{tan^2 \theta }{4} + -1 +1 \\
|A|=\frac{\sec \theta}{2}
$$
Hope it helps!
To some it may seem unjust to assume equation (i) to be exactly the same as the given in question, but there is nothing that prohibits that assumption. If you have any query, they are all welcome.
Answer: Hint:
Compare the quadratic coefficients of the equation with those of $$(y-m_1x)(y-m_2x)$$ and use $$\tan^2\theta=\left(\frac{m_1-m_2}{1+ m_1m_2}\right)^2=\frac{(m_1+m_2)^2-4m_1m_2}{(1+m_1m_2)^2}.$$


Best way to select a city from a list of cities unevenly distributed among countries

Question: I'm working for a company that owns restaurants in 28 cities distributed in 10 countries. The restaurants are distributed unevenly in the countries: in some countries they are present in many cities but in most countries they have restaurants only one.
For each city, we have a page that lists all the restaurants in that city (ex: Restaurants in Madrid).
I've been told to design the way the user would get to the city page. I've considered some options but all of them seem to have problems:

Search with autosuggest (it works for finding your city but most cities would have no results)
Tabs by country (but most tabs have only 1 item/city)
List with all cities (28 cities are a lot for a list)

Do you have any suggestion? Thanks in advance
Comment: @Kishan Yes, I have. Thanks
Comment: Who is the user here? And is there a top level page you're thinking of here? This forum works best when you have some visuals showing the larger context, so the community can help with your specific situation?
Comment: how many countries ?
Comment: Did you consider exploring maps? ex: a map when zoomed out has 10 pins that show the count of cities in each pin (a.k.a country). When clicking on one pin, it will zoom in to one country with the pin distributed to various cities (now each pin will show the number of restaurants in each city).
Comment: Have you considered an accordion list. First it will have 10 closed accordions - with country name on the left, cities count in a badge and chevron to the right. Open the accordion and the same structure repeats, but this time with list of cities on the left, restaurant count in a badge and CTA on the right.
Answer: There are many other ways to display the information, but without knowing more details it is hard to determine what would be the optimal way to show the details.
But in terms of providing alternatives to what you have listed there, here are some that you can consider:

Map view with countries highlighted and cities displayed with pins (zoom level for pins need to be considered if there are multiple restaurants in the same city)
List of countries with cities as sub lists
Grid layout of countries, which takes you to a subpage of cities or the main page if there is only one restaurant in that country


AWS CLI copy recursive command not copying files from S3 to local

Question: I'm trying to recursively copy S3 objects to my local directory, but when I do, nothing happens. No error message either.
Locally I use the aws cli via a temporary Docker container by adding the following to my ~/.bash_aliases file:
alias aws="docker run --rm -v ~/.aws:/root/.aws -v $(pwd):/aws amazon/aws-cli

I cd into my local directory where I want the S3 objects to go to and I run:
aws s3 cp s3://myBucket/myFolder/ . --recursive

Ref: https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3/cp.html#:~:text=Recursively%20copying%20S3%20objects%20to%20a%20local%20directory
Output:
download: s3://myBucket/myFolder/file1.xlsx to ./file1.xlsx
download: s3://myBucket/myFolder/file2.xlsx to ./file2.xlsx
download: s3://myBucket/myFolder/file3.xlsx to ./file3.xlsx
# ... etc etc

But when I go to my local current directory there's nothing there.
The docker run mounts a volume so it should in theory work?
Answer: Read up answer in docs. The aws alias in ~/.bash_aliases was missing the interactive option -it:
alias aws="docker run --rm -it -v ~/.aws:/root/.aws -v $(pwd):/aws amazon/aws-cli

Working successfully now.


How many square foot of coverage per bag of mortar when repointing brick?

Question: I haven't been able to find the answer anywhere. In a standard 80lb bag of mortar mix, how many square feet of coverage can I get when repointing a running bond brick wall with standard 8x4x2.25 assuming a depth of about 1"?
Anybody have a rough rule of thumb?
Answer: Had a few minutes... created a model in SketchUp and found that with a 3/8" wide joint the mortar takes up .55 sq ft per square foot of wall. 1" depth after removing part of the old mortar and it comes out to 0.015 cubic feet per square foot of wall.
About 0.7 cubic feet of wet mortar per 80lb bag and that comes out to close to 46 square feet per 80lb bag for a 3/8" wide mortar joint.
With a 1/2" joint width yield is roughly 36 square feet per bag.


Running a nightly process with Meteor

Question: I'm writing an application using meteor and I need to run a process each night at a certain time. This process will need access to Meteor's Mongo database and would benefit from other Meteor features too.
Is it possible to run a meteor process or task of some sort on a scheduled basis? Or will I need to use a different stack to achieve what I want?
Answer: There's a smartpackage called meteor-cron that can help you: https://atmosphere.meteor.com/package/cron.
Additionally if you want to go more manual you can use Meteor.setInterval (docs) to run every hour and if its midnight to run your task.
Keep in mind if you use meteor deploy for meteor's free hosting, if no one visits your site it will go into a 'sleep mode' then wake up when the next user visits it. The user won't notice it but your meteor app won't be running to run these tasks.
Comment: @JonathanMoffatt yes it would use setInterval behind the scenes. It wont fire if the hosting site is sent to sleep. This is only meteor's free `deploy` hosting. If you host it yourself you won't run into this.
Comment: Thanks Tarang! Does meteor-cron use a similar setInterval method behind the scenes i.e. will it also not fire if the hosting has sent the site to sleep?

Running a nightly process with Meteor


want to store data in the reactJs for faster access

Question: What i want to achieve is when the user log in,the data gets loaded on the first instance the data is of around 30mb.So the next time the same user access the website the data should get loaded from the front end rather fetching the same data from backend which is quite large and will take 1 minute in fetching the data.Is there any way by which we can store data in the react js.
Comment: It takes 2 seconds to download 1 MB?
Comment: it depends on the network,in my previous application it takes 50 secs to download the data
Answer: A warning before providing some solutions to your problem: A payload of 30mb is quite large for a web application. I recommend being mindful of user connectivity. A resource providing some useful stats on connectivity: https://ourworldindata.org/internet.
With regard to caching a large amount of data in your React app, there are a couple of options. Mozilla's Client-side_storage is a good place to start looking. That being said, I don't think there are any options that allow you to store over 50mb client side.


Find the number of pairwise non-isomorphic $(n − 2)$-regular graphs with $n$ vertices

Question: Find the number of pairwise non-isomorphic $(n − 2)$-regular graphs with $n$ vertices (i.e.
graphs in which all vertices have degree $n − 2$).
Answer: Look at the complement, the missing edges! You get a graph where every vertex has degree 1. Now it is easy.
Answer: One vertex is connected to $n-2$ vertices. The remaining vertex must be connected to the same $n-2$ vertices. Then the other $n-2$ vertices must form an $(n-4)$-regular graph with $n-2$ vertices. Since there is $1$ kind of $0$-regular graphs on $2$ vertices and $0$ kinds of $1$-regular graphs on $3$ vertices, it follows by induction that there is one kind of $(n-2)$ regular graph with $n$ vertices for even $n$ and none for odd $n$.
Note that the proof is constructive in that it shows how to construct an $(n-2)$-regular graph with $n$ vertices for even $n$.


UX for entering two times per day for time period

Question: I'm building an iOS app to be used by children / youth for a period of four weeks. The app issues a notification twice per day, once in the AM and once in the PM. Prior to using the app, the user (the children or their parents) must select the AM and PM times for the notifications to be issued. I'm trying to figure out the best way to allow the user to enter these AM and PM times.
Currently I have a screen with a two-button segment control. The first button shows a table with two rows. One row presents an AM time, with the second showing a PM time. When the user taps a row, a time picker is revealed, allowing the user to configure the AM or PM time for the entire four week period.

The second button of the segment control reveals a view with a table with 56 rows--AM and PM rows for each day of the four week period. By selecting the appropriate row, the user can configure a specific time for a particular day.

Is there a more intuitive UX for entering two times per day for limited time period? The view with two rows feels bare and empty and the one with 56 rows feels clunky. Maybe it is better to merge the two views and have a single view with 58 rows? In this scenario, the top two rows would allow the user to set all AM and PM times, and then they can scroll down to one of the remaining 56 rows to configure a time for a specific date.
Comment: Can you upload a mockup of what you currently have? It's easier to visualise what you're working with if we have something to look at.
Comment: added the screenshots. it's very rough right now - far from a polished state, but hopefully it gives an idea of what I have so far.
Comment: What are they getting reminders for (ie. what does the app do)? It may make sense to group by weekday/weekend.
Comment: Look here for inspiration: http://blog.iangclifton.com/2014/01/22/mobile-time-pickers/ I prefer the "Analog" interface, though children, if they are young, may prefer a digital readout.
Comment: You could make it be more of a wizard and have you: 1. Punch in the first date then hit next, which 2. Slides over to a second view for the second date.
Answer: I think you should give a display of all of the days and the times of the notifications for each day.
Group this list into 2 groups (one group for each week), then the times (AM/PM) beside each day should be clickable so they can be changed individually. This way they act as a status of the time set and as an actual control that is clickable. When tapped throw up a modal time spinner control so they  can focus on setting the time.
Also above the main view have a button that says "Change All Times" or something similar. When this is tapped, you can have a 2 step wizard, the first spinner will be titled with something like "Change All AM Times", then they click next, and they get "Change All PM Times". Then when they save all of the times are updated. They can then change a specific time after that if they wish by following the method I mentioned above about the individual buttons beside each day of the week.
Also, I think you should populate the list with default times unless you want to force the user to set them themselves.
e.g. wireframe of above idea
Answer: I think it is possible to consider using sliders or similar controls for entering time using a small footprint. You can use colours or fixed starting points to limit the time period that users can enter, and create specific size steps if you don't need or want users to have to be very precise with the time. Using sliders also allow for comparison between the two time periods quickly to see overlaps or compare length of time. It also opens up to and more complex manipulation if you add in additonal input controls. It is not really a standard at the moment, but I am hoping it inspires more people to think up of innovative ideas for this problem.
Answer: First, why do you have to click a field before selecting the time? There shouldn't be too much more of an impact on screen real estate to show the time selector widget initially (depending on which time widget you use).
Second, depending on what kind of time-based application you are building, you should be able to extrapolate the most commonly entered values and pre-fill the form data (html placeholder text, styled differently of course) for easier manipulation.
Third, use a graphical representation of time. I would use two circular analog clocks and allow the user to click and drag the hands into the desired location (on desktop). The center of the clocks could have a sun and moon icon (respectively) and / or yellow and blue borders to visually represent the different functionality, for example.
Depending on what is going on here, of course, but this would be how I would structure it if the user is coming in each day to set times (I imagine this to be like parental controls for tv time based on the way you have described it).
Answer: Can it be like this?

download bmml source – Wireframes created with Balsamiq Mockups


Show description only when video is loaded (HTML  Tag)

Question: On the site (written ReactJS), the user has the opportunity to stream video from his screen. For this I use HTML  Tag. I put a small description on top of the video (blurring the background a little so that users can see both the description and the video).
The problem is that when the page loads, the video takes some time to load (from three to five seconds), but the text with the description appears immediately. It doesn't look very nice.
export function ShowVideo() {
   const videoRef = useRef<HTMLVideoElement>(null);
   return (

      {videoSourceId && (

              <DiscriptionForVideo />
              <video ref={videoRef} muted />

      )}

  );
}

Please tell me how to make sure that the text with the description appears at the moment when the video appears.
Comment: Could you please update the JSON of the video also to get more clarification?
Answer: To synchronize the appearance of the description text with the video, you can use the onLoadedData event of the video element. This event is triggered when the video's metadata has been loaded, and it's a good indicator that the video is about to start playing. Here's an updated version of your ShowVideo component:
import React, { useRef, useState } from 'react';
export function ShowVideo() {
const videoRef = useRef<HTMLVideoElement>(null);
const [isVideoLoaded, setIsVideoLoaded] = useState(false);
const handleVideoLoaded = () => {
setIsVideoLoaded(true);
 };
return (

{videoSourceId && (

<DiscriptionForVideo />
<video
          ref={videoRef}
          muted
          onLoadedData={handleVideoLoaded}
          style={{ visibility: isVideoLoaded ? 'visible' : 'hidden' }}
        />

)}

);
}

In this code, the onLoadedData event triggers the handleVideoLoaded function, which sets the isVideoLoaded state to true. The visibility of the video element is then controlled based on this state, ensuring that the description text and video appear together. Adjust the styling as needed for your specific layout.


The Logic of forEach() when works with variables in javascript?

Question: the result of code is :
test0: apple
1: orange
2: cherry

I want to know why my text variable is equal to "" in second and third loop, I expected the previous values to be added to the initial value of the text variable, Can anyone explain what happens to the text variable and what is the logic of forEach in this example ?

let text = "test";
const fruits = ["apple", "orange", "cherry"];
fruits.forEach(myFunction);

document.getElementById("demo").innerHTML = text;

function myFunction(item, index) {
  text += index + ": " + item + "
";
}

Comment: Your code is working exactly as it should. If you want  "test0" at the beginning of every line, you'll have to append it *inside* the loop.
Comment: [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173)
Answer: Your loop runs such that the text test is only added once. In the beginning and then later the variable text is updated.
If you want to add in every iteration just keep it in a seperate variable and keep adding.

let text = "";
let test = "test";

const fruits = ["apple", "orange", "cherry"];
fruits.forEach(myFunction);

document.getElementById("demo").innerHTML = text;

function myFunction(item, index) {
  text = text + test + index + ": " + item + "
";
}

Answer: Your codes works as expected. using innerText rather than innerHTML might illuminate the situaion

let text = "test";
const fruits = ["apple", "orange", "cherry"];
//fruits.forEach(myFunction);

document.getElementById("demo").innerText = text;

function myFunction(item, index) {
  text += index + ": " + item + "
";
  document.getElementById("demo").innerText = text;
  console.log(item,index);
}

window.setTimeout( myFunction.bind(null,fruits.shift(),0), 1000);
window.setTimeout( myFunction.bind(null,fruits.shift(),1), 2000);
window.setTimeout( myFunction.bind(null,fruits.shift(),2), 3000);


PG:InsufficientPrivilege: ERROR when trying to make an INSERT on stage database

Question: Im using heroku and postgres. Local is working fine but whenever the user (any user) performs an INSERT on stage it crashes. This is the message i get:
PG:InsufficientPrivilege: ERROR: permission denied for relation .. INSERT INTO..

I granted privileges to public on the required tables but it doesn´t make a difference. Any insight would be useful. Thanks.
Comment: Did you solve it? I just experience the exact same problem. No idea where to start digging.
Answer: I know it's waaaaay late, but I just ran into this issue and I believe the problem is that you have exceeded the number of rows allowed for your DB. In my case, I was using a Hobby-dev plan and the limit is 10k rows. If you run heroku pg:info you will see something like:
=== HEROKU_POSTGRESQL_BRONZE_URL (DATABASE_URL)
Plan:        Hobby-dev
Status:      Available
Connections: 4/20
PG Version:  9.3.3
Created:     2014-05-27 15:07 UTC
Data Size:   175.5 MB
Tables:      47
Rows:        409300/10000 (Write access revoked)
Fork/Follow: Unsupported
Rollback:    Unsupported

With the Write access revoked being the key piece of information. Upgrading your DB (or deleting some data) should solve this.
Comment: Wow thank you. I've been banging my head on this one for hours.
Comment: CLUTCH ANSWER!!
Comment: i upgraded my DB but i'm still getting the error. please help
Answer: I had this problem caused by over 10000 rows, I was using Hobby Dev (free until November 2022), I upgraded to Basic (paid), I understand this might not be solution for everyone
Hobby Dev 10,000 row limit
Mini 10,000 row limit
Basic 10,000,000 row limit
https://elements.heroku.com/addons/heroku-postgresql
Once I upgraded


NSOperation performSelectorOnMainThread crashes

Question: I'm calling a NSOperation from a Subview of a NavigationController.
MyOperation *op = [[MyOperation alloc] target:self action:@selector(didFinishOperation)];

The Operation loads some data from a server, parses it and then sends a
[target performSelectorOnMainThread:action withObject:nil waitUntilDone:YES];

when the job is done. This is generally working...
The problem is when I push the back button from the navigation controller while the NSOperation is doing its job, the app crashes because the action references a deallocated instance.
I've tried retaining the operation - but it still crashes...
Thanks in advance
Answer: Chris is on the right track, but it doesn't cover the case where the operation completes as you try to cancel it, and it will still crash. If the operation is executing in main, the cancel won't take effect.
Still, try and cancel it before your target is destroyed, but test that the target still exists before attempting to send it a message. Also, check if you're cancelled before trying to send the message:
if ( self.isCancelled ) return;

Comment: I've already cancel the operations in viewWillDisappear:
[operationQueue cancelAllOperations];
I run more than 1 operation when loading the view.

As you mentioned above - this will cancel the operations but not if its executing in main.

I've tried:
if (target)
[target performSelectorOnMainThread:action withObject:nil waitUntilDone:YES];

but the error still occurs...
Comment: I just reviewed my code, and my operations check if they're cancelled before attempting to notify their target.
Comment: Thanks ohhorob,
that did the job :)
Answer: In your UIView dealloc method, you could cancel the operation and remove it from its NSOperationQueue.


Diagnosing an erratic fan issue

Question: I am running Ubuntu 17 on a Dell XPS 9560, purchased brand-new last September. Last week I suddenly began having issues with the laptop fan:

it randomly spins up at least every 15 minutes or so to 5000 or 6000 RPM, even when the CPU is idling and cool (see sensors report below)
during those 5/6k periods, it will occasionally spin down to <2000 RPM for less than a second, then return to 5/6k

I currently have i8kutils installed to control the laptop fan, running with the default configuration file (which specifies that the fan should be at minimum speed when the CPU is below 50 C). Something else seems to be causing the fan to run like this..
I'm inclined to think this is actually a software / driver issue, but I'm not sure how to diagnose further. Here's why:

The fan issues began on the same day that I upgraded my nvidia-390 drivers.
I promptly downgraded to the previous driver version, which made the fan problem go away for a few days.
For some reason, though, the issues have now returned. (The drivers are still at their downgraded versions.)

Assuming this is a software problem — how can I further diagnose which processes might be making my fan go crazy? Is there any way to monitor which processes are setting fan speed?
(I'm also open to the suggestion that this must be a hardware problem, and that I should open up my laptop case instead!)
I'd really appreciate any help. Thanks!

Here is the output from sensors while the fan is running near top speed:
$ sensors
pch_skylake-virtual-0
Adapter: Virtual device
temp1:        +32.5°C

acpitz-virtual-0
Adapter: Virtual device
temp1:        +25.0°C  (crit = +107.0°C)

dell_smm-virtual-0
Adapter: Virtual device
Processor Fan: 6058 RPM
Video Fan:        0 RPM
CPU:            +34.0°C
Ambient:        +26.0°C
Ambient:        +27.0°C
Other:          +25.0°C

coretemp-isa-0000
Adapter: ISA adapter
Package id 0:  +46.0°C  (high = +100.0°C, crit = +100.0°C)
Core 0:        +46.0°C  (high = +100.0°C, crit = +100.0°C)
Core 1:        +44.0°C  (high = +100.0°C, crit = +100.0°C)
Core 2:        +43.0°C  (high = +100.0°C, crit = +100.0°C)
Core 3:        +41.0°C  (high = +100.0°C, crit = +100.0°C)

Here's the sensors output a few moments later, when the fan is completely off with a higher CPU temperature:
$ sensors
pch_skylake-virtual-0
Adapter: Virtual device
temp1:        +36.5°C

acpitz-virtual-0
Adapter: Virtual device
temp1:        +25.0°C  (crit = +107.0°C)

dell_smm-virtual-0
Adapter: Virtual device
Processor Fan:    0 RPM
Video Fan:        0 RPM
CPU:            +35.0°C
Ambient:        +29.0°C
Ambient:        +29.0°C
Other:          +29.0°C

coretemp-isa-0000
Adapter: ISA adapter
Package id 0:  +46.0°C  (high = +100.0°C, crit = +100.0°C)
Core 0:        +46.0°C  (high = +100.0°C, crit = +100.0°C)
Core 1:        +45.0°C  (high = +100.0°C, crit = +100.0°C)
Core 2:        +43.0°C  (high = +100.0°C, crit = +100.0°C)
Core 3:        +42.0°C  (high = +100.0°C, crit = +100.0°C)

Comment: If it helps, I can hear what sounds like a lot of rapid SSD reads (quiet ticking noises) when the fan first spins up, or is oscillating between high and low RPMs.
Comment: A similar issue (fan constantly on) appeared this morning when I updated ubuntu (18.04). Changing drivers to x.org makes the computer freeze. I also tried `nvidia-driver-396` with similar results.
Comment: FWIW: Looks like this was actually a hardware issue. I sent the laptop to Dell for repairs and with a new fan I have no issues.
Answer: I've got the inverse problem on an laptop, the fan was not running enough and got CPU crashes.
I've wrote a little script in order to help managing the fan rotation speed with more parameters in order to make it work following your own strategy.
To install it :
sudo npm install -g ubuntu-smart-fan
sudo apt-get install lm-sensors
sudo sensors-detect

After installing it, you can run it with default parameters :
sudo ubuntu-smart-fan --min=50

You can define your own strategy, take a look at the documentation here : https://github.com/ichiriac/ubuntu-smart-fan

Diagnosing an erratic fan issue


14.04 /etc/hosts ignored

Question: I have added a line like the following to my /etc/hosts file:
159.253.x.xxx www.***.nl

When I ping to www.***.nl it gives me the correct ip address back but when I use my browser I do not get to 159.253.x.xxx (which is my development server containing a copy of the actual site).
My question is, how do I solve this?
I'm running Ubuntu 14.04.
Comment: when you say development server, do you mean it is a server that you have hosted on your own or have you rented it from a hosting company?
Comment: When you say "doesn't work" please explain what you mean exactly. What doesn't work? What are you getting instead of what you expect? To me, it sounds like you have a problem with the configuration of the web server.
Comment: The development server and the live server are both two VPS servers I rent from a hosting company. I do not have a maintanance contract with them so I have to do all the work myself. On the development server the vhost configuration is correct. On the live server the website is running as expected.

What happens is that I end up on the website running on the live server  instead of the development server.
Comment: @bodhi.zazen As you can see in the answers and comments of that topic, the options listed there only work till Ubuntu 13.10. I run 14.04
Comment: Should work for 14.04, did you try it ? If so, post your config files so we can check them for syntax.
Answer: Until and unless a website is hosted on a dedicated IP, you will never be able to reach the website/domain by typing in the IP in the address bar even though you will be able to ping the ip address. This is the reason, Hosting companies are able to host thousands/millions of domains on a single IP via shared hosting plans and as a result the hosting charges are less.
Comment: I know this. I have been building websites for 10 years now. It is clear to me how DNS works ;-) I don't type the ip address in the address bar but the domain name I have set up in the hostsfile. The development server and the live server are both two VPS servers I rent from a hosting company. I do not have a maintanance contract with them so I have to do all the work myself. On the development server the vhost configuration is correct.
Comment: This answer is in left field. See the link I gave above.

14.04 /etc/hosts ignored


Is my wooden deck salvageable? Repair tips and Stain vs Paint questions

Question: Here is my deck condition.

Couple questions:

What do I need to do to prep a deck in this condition?
Was planning on washing with oxi clean and dish soap and orbital sanding. I'm guessing some wood filler would help here too?  Any other repair or prep tips?  Order of operation would he helpful.

Is condition salvageable enough to stain or am I stuck with paint?
Will use Cabot stain. Was hoping to do a semi transparent oil based stain. Am I stuck with their deck Repair line or the solid paint?

Any tips would appreciated!
Comment: If you are going to sand it, keep the sawdust to use as the base for your filler, as it will then match the rest of the boards ...
Comment: It's a bit unclear what the question is. That deck looks fine. Why do you think it might not be salvageable?
Comment: Don't use wood filler. I'm not sure it's even necessary to spell out a reason.
Comment: If you have boards with a lot of lifting bits, like the middle of your 2nd pic, maybe try flipping them to see if the other side is in better shape.
Comment: Just needs some [Schaffer's New Zealand Style Deck Sealant](https://www.youtube.com/watch?v=tbazGVrbN-g)!
Comment: I replaced all the board on my deck this summer, after having replaced bad boards as needed every few years.  For me it was time, I had a lot of rot.  I super don't recommend the old deck "stain" that is actually opaque rubbery paint.  It locks in moisture and accelerates damage.  Plus it only looked good for about 2 years anyway then was peeling and ugly.
Comment: Question #2 is pure opinion.
Comment: Please post some picture showing the supporting boards underneath. If there's an issue, that is what will need to be addressed first.
Answer: It appears to be somewhat weathered, but overall solid.
You can do as much or as little as you like to it, from there. It's a deck, not a living room floor. If it's not structurally compromised (and it does not appear to be) such that falling through it is likely, it's doing its job. If some boards are, replace them. If more than half the boards are, consider it might be time to replace them all, at that point.
Beyond that is cosmetics, with a touch of perhaps preserve its remaining life a bit. Sand if the splinters are bad enough to annoy you, or don't if they are not; then seal it, oil it, stain it, or paint it as you like, if you want to. Hopefully it's pressure treated material so rot should be limited.
Sanding back so it looks like "new wood" before you seal, oil, stain or paint is purely cosmetic and not needed for any reason other than trying to make a deck out in the weather more of a project than it needs to be. If it's stabbing you with splinters, that's a functional reason to sand, but making the wood "not weathered gray" is purely cosmetics. That's what happens to wood in the weather, and plenty of structures built like that function for decades with no further cosmetic treatments done to them.
Answer: I've worked on many decks that look just like that. Get a pressure cleaner/washer and go over the entire deck. You'll be surprised at how that cleans up the deck. Don't use a 4500 PSI (31 MPa) washer, stick to around 1600 PSI (11 MPa) so you don't damage the wood. There are deck washing fluids you can get at your home store but I've always just used water. After it dries,sand any rough spots and check for any rot and repair as needed. It's up to you on what finish you want. I've used clear water sealers, stain sealers, and paint all with great results. It depends on your personal preferences.
Answer: As a variant opinion, go underneath and look for deterioration in the structure supporting the decking. If that's showing significant issues (i.e. edges rotting off) then expect to replace the whole thing in a couple of years (and next time, make sure that the wood is properly treated and retain all certificates).
Apart from that, I'm a bit concerned about that board with "shakes" running across it, which suggests rot. However as others have said: clean everything up then apply preservative... I'd make that /copious/ preservative in dry weather, such that it runs onto any part of the supporting structure that water would normally contact.
Answer: Wood naturally will gray out like that. The sun and rain do that. If you want it to not do that as fast, that's where water sealer can extend the life of your deck.
The board in the middle of your second picture looks to be in worse shape than the rest of the boards. A single board isn't expensive and I would replace it solely because it may start to crack and curl on you (plus it looks worse). I don't think there's any obvious safety concerns there.
Your best bet is not staining, but a deck paint. They are designed to provide a uniform look in the end, and contain material so the surface will still provide traction without being uncomfortable.


What is the formula for fence height and fence post length?

Question: My neighbor has requested that we remove our current shared old/broken 6' cinder block wall and put up an 8' high horizontal slat wooden fence.
The distance between the posts will be ~5.5'.
My question is how deep do I need to put the fence posts? This will help me determine the length of the fence post.
We live in Los Angeles. I think the frost line is 12".
Answer: Are you setting the posts in the ground, or in concrete? How deep is the frost line in your area? Have you contacted your local building department? There may be local codes and ordinances that stipulate the depth.
A common rule of thumb, is to dig the hole 3 times as large as the post, and to a depth of 1/3-1/2 of the post height above ground. so for a 8' high fence, using 4x4 posts. dig the holes 12" in diameter, to a depth of 2 1/2 - 4'. Of course, that's assuming you're setting the posts in concrete.
If you're going to put gravel at the bottom of the hole, you'll have to dig the hole that much deeper. Gravel is optional, and dependent on the drainage characteristics of the local soil.
Comment: I think in Los Angeles it is 12"
Comment: @milesmeow Then you shouldn't have to worry about frost heave. I'd just follow the 1/3-1/2 rule, unless there are some special earthquake (or volcano) rules in your area.
Comment: Does wind force need to be factored in? Or does the depth formula that you've specified already take that into account?
Comment: @milesmeow For a typical installation, yes.  However, if you live in a place where it's common to have really strong wind gusts, or overall more wind. Then you might want to factor that in, and adjust accordingly.
Answer: The normal in ground length is 2 ft, so you buy 8 ft posts for a 6 ft fence. The normal wood fence has the boards on only one side of the posts so in your case you will have to decide who gets the more finished side and who has to view the posts, or you could put boards on both sides.
Comment: There are styles of fence that look equally the same from both sides. Often referred to as a "good neighbor fence" you can see examples here: http://fitzpatrickfenceandrail.com/good-neighbor/
Comment: If I want an 8' high fence, how many feet ground length? Is it still 2' or do I need more ground length?