How do you hibernate/suspend Ubuntu like Windows or both at the same time?

Question: I'm using an ASUS laptop with Windows 7, and I just installed Ubuntu alongside Windows yesterday, using the no-risk option. I noticed, though, that I can't hibernate Ubuntu the way I did with Windows to save time, and, every time I use Ubuntu, I have to shut down to go into Windows, which has a slow boot.
Is there any way that I could have Windows and Ubuntu hibernated at the same time so I can access both easily (preferably without having to hit a function key within seconds). When I try to hibernate or suspend Ubuntu with Windows shut down, the screen just turns blue and doesn't shut the computer off like a Windows hibernate or sleep.
Comment: [This thread](http://askubuntu.com/questions/94754/how-to-modify-policykit-to-allow-hibernation-in-upower) may help you out
Comment: Check if your swap partition is crypted. Resume wont work if it is.
Answer: Hibernating is not supported with the wubi installation.
http://wubi.sourceforge.net/faq.php
You'll have to migrate to a dedicated partition or reinstall properly to be able to hibernate.
Answer: If you're using 12.04, Hibernate/suspend is apparently no longer supported or enabled by default, because it has been unreliable :(
See https://wiki.ubuntu.com/PrecisePangolin/ReleaseNotes/UbuntuDesktop#line-52


Extract city name from SQL Server Column

Question: Background:
I have a column  within my SQL Server table that consists of values that look like this:
 Location

 AM  -  Equi A2 Amsterdam
 AM  -  Equi A2 Amsterdam
 AM  -  Equi A2 Amsterdam
 GRU  - log Equ SP São Paulo(NUM)
 GRU  - log Equ SP São Paulo(NUM)
 GRU  - log Equ SP São Paulo(NUM)
 SJC1 - DR Santa Clara(FIS)
 IAD - Terremark NAV Culpepper
 HKG1 - Equin HK Hong Kong

Dilemma:
How would I extract only the actual places such as:
Sao Paulo, Amsterdam, Culpepper, Hong Kong etc in a new column?
Desired output:
 Amsterdam
 Amsterdam
 Amsterdam
 São Paulo
 São Paulo
 São Paulo
 Santa Clara
 Culpepper
 Hong Kong

The problem is that I cannot just split on the last blank space, due to the countries that have two words, split by a blank space. (Hong Kong, Sao Paulo)
What I have been working on:
SELECT TRIM( '- ' FROM '    Table    ') AS TrimmedString;

Comment: I wrote an answer having not understood the expected output correctly! It is possible and fairly simple to get all the text after the - but there is no pattern or logic as to where the province(?) becomes the city
Comment: Based on the data shown I expect its impossible to just split it as there does not appear to be a logic rule that could be followed. If you have an existing table containing country names you could see if the name exists in the string.
Comment: @DaleK I was wondering if SQL has a pattern logic such as Python  Regular Expressions (regex)
Comment: What regex pattern would find it? Given you don't know whether the city name has 1 or 2 words? If you have a regex pattern that works we *might* be able to find a way to do it in SQL, but I think its a logic issue, not a technology issue.
Comment: Perhaps with:  finding the hypen and ignoring everything that occurs before the hyphen.
Once we've found the hyphen, find a substring that contains only capital letters and/or numbers and this substring must be surrounded by 1 or more spaces
Comment: As I say, if you can provide a regex we can see if its possible in SQL. I don't think that works anyway, you have a different number of words following the hyphen, with both lower and upper case *before* the city name.
Comment: I am actively working on this. Thanks for the input
Answer: Since there is no extraction pattern

Create a table with all major city names, you can find csv's online for this. (example)
Write a query that joins using like. ( notice this query is not sargable.)

Example
SELECT t.Locarion
, c.CityName
FROM Table t
LEFT JOIN City c on t.Location LIKE '%' + c.CityName + '%'

Insert missing cities based on null values in the previous query.

Depending if this is a one time query or running it multiple times a day, you may want to change your model to have a foreign key to a cities table.


Formatting toolbar in document editing app

Question: I'm working on a web app (not mobile) which allows the creation and collaboration of legal documents.  The business owner wants to have a fixed toolbar, as per this editing tool I'm using to write this question, or as per Microsoft Word, etc.
I personally like the way Medium works, in that you have to highlight the text you want to edit and then it brings up mini toolbar, just above the text.
What do you think works best from a UX perspective?
Comment: Can you show your current work?
Comment: I personally hate the mini toolbar popups, so much that I go to the pain of disabling these where possible. What did you learn from testing with future users and/or asking the business owner for their reasons?
Comment: It's so early on that we're only just working on wireframes.  I will be testing everything when we get to a front end prototype.
Comment: The business owner thinks that her customers would want to use an existing understood paradigm.  The issue is that there is going to be a lot on the page and I'm trying to keep the default view as simple as clean as possible...
Answer: This is a bit of an opinion based question, but I will attempt to answer it nevertheless...
It is probably best to stick to that which the end users are already used to.
Remember that this is UX (user experience), and as such, the user's previous [user] experience counts greatly, as you don't really want to change their expectations too much.
I am not at all familiar with legal documents, or their editing, but assuming that they are created on standard word processing tools, then it would seem best to stick to what they already know, use and love.
If, however, Medium is common in their line of work and a greater proportion of your users use that, and are familiar with the need to select a portion of text in order see the menu and to be able to edit it, then fine. However, to me, it sounds like a GUI version of a line editor, to be honest.  Having to select something and then have a movable menu, does not sound particularly consistent, although, I can see that having the menu nearer the text, would result in less mouse movement.
Basically you have a conflict between:

less mouse movement (for the pop up menu), and;
familiarity and automatic (subconscious) hand movement (for the static "normal" menu).

You say that you are primarily concerned with having a clean display, so how about a compromise, à la WordPress, where there are a number of familiar tools immediately on display, and then there is a More... menu? Or have a very simplistic toolbar, for the common actions, like TextEdit on the Mac, or the StackExchange editing tool, and then have the more advanced features, either in menus or in optional toolbars. Letting the user decide how they want their toolbars to appear, if at all, is generally the best approach (within reason).
You probably don't have the market clout (or do you?) to change the UI drastically, in the same way that MS did when they introduced Office 2007 and the Fluent User Interface, and user's productivity, arguably, dipped for a while, until the user's got used to the new design, or switched to using something more familiar, like OpenOffice, which still had the old style menus and toolbar. So, in order to encourage people to adopt your UI/UX and hence your application, it is best to draw them in with something familiar. Thereafter, once you have built up a firm and loyal user base, then you could bring in the new UI (maybe).


Setting up Latex with Texmaker

Question: I want to setup latex environment on Ubuntu 12.04 64bit Machine. As I am making a backup system for Windows 7 machine.
I have installed the latest version of Texmaker 3.3.4.
Now I want to know which latex distribution to install for making PDF files.
I seen few like XELATEX, tex live etc.
Can you suggest the one which very well maintained and up to date like MikTex (for Windows)?
Answer: First, just to be sure: you did install texmaker via the software center right? If I got it right, you're coming form Windows world, and an habit to change in Ubuntu is the google/download/install cycle.
Instead, Ubuntu a package manager that will take care of the updates for you. I think that also answer your question: as long as you take a latex distribution from the software center, you don't have to worry about maintenance. I personaly use texlive, and haven't had to complain so far. I installed the packages called texlive-fonts-extra which installed the rest of the texlive distribution, plus some fonts for some weird latex template I had to use.
If you prefer command line rather than GUI, you can type:
sudo apt-get install texlive-fonts-extra
Comment: I would argue that the delay between a release and an update of the package is actually a feature: it should correspond to the time that maintainers need to test and maybe tune the package to your system. That's another thing you lose if you install the package yourself.  I agree that sometimes it can be a problem. My rule of thumb is that unless I know exactly what feature I'm missing, I just stick to the package version. In the case of texlive, I hardly imagine what are the changes between releases, but I'm no latex expert at all.
Comment: I installed the Texmaker from developer's website because it was more up-to-date.   The problem I found with installing Tex-Live-Full from the ubuntu software centre is very old, while the currently available version on TUG website is TL2011, and TL2012 will be release sone.

Setting up Latex with Texmaker


How to change permission dialog UI in Flutter?

Question: How to change permission alert UI on Flutter(Ios and Android)?
Comment: I am not familiar with Flutter but i think you can not change the Permission dialog .. Its a System Dialog you have no control over it .. Dialog will be shown as per Android version . for instance Android 10 have a modified alert for location permission .
Answer: You can't change that, no modifications are allowed in both iOS and Android. What you can do is create your own dialog that matches this UI and show user the reason explaining why you need the permission in case they deny it. That's all you can do.


Generate a random integer between -2 and 1 inclusive

Question: How can one generate a random integer between -2 and 1 inclusive?
I know if I take rand*(b-a)+a I would get random real number between a and b
Thanks
Answer: $$\lfloor4\operatorname{rand}()\rfloor-2$$
Answer: You can use randi, which generates integers between 1 and the specified input argument:
randi(4)-3

If you don't have the randi function (it is included in newest versions of Matlab), you could use rand with ceil:
ceil(rand*4)-3


5th partition without format

Question: I have a 500gb hdd with 4 primary partitions: sda1: ubuntu, sda2: swap (2gb), sda3: win8.1, sda4: logical (sda5 & sda6) storage.
while creating all these partitions, i inadvertently left 7gb unallocated (adjacent to sda3) now i want to create a backup partition (probably bootable,don't know) to use with the dell backup utility but can't since i already have 4 primary partitions :/
i thought about removing the swap partition as i have 4gb of ram, but i read thousands of threads and i'm still lost.
is there a way that i can create such a partition without loosing any data? btw, if someone could tell me how, it would be very kind.
Answer: You could extend your logical partition to include that free space, then create a new partition there, if the space is between sda3 and sda4. If not, then just move sda3 so the free space is adjacent to sda4. Moving partitions can take a lot of time, up to several hours.
It's a relatively easy operation if you use a live DVD (or USB disk as I prefer) and gparted.
Note: Removing your swap partition is not recommended, it can ruin your day to run out of memory at some point. The recommended size for swap is at least the same as your RAM, but preferably, twice the size. See the Community Wiki for more details.
Comment: actually, sda3 is a primary partition. can i turn it into a logical/extended one (knowing it contains windows) and add the free space to create a backup partition that i could boot from in case something turn wrong with my win8.1?

in other words,i want to convert a primary volume to logical to create a fifth volume on a disk with 4 existed primary volumes all this without loosing data of course :)
Comment: I'm not sure if Windows will be able to boot if you convert the partition from primary to logical, I haven't used Windows for about 8 years now, but I remember XP having troubles with this. But you don't have to do that, as written in my answer, you can just attach the free space to the existing logical partition (sda4) and create a new partition within that.
Comment: could be a good solution too :) will i be able to boot from using any recovery tool? also i want to hide this partition from my desktop, how?
Comment: @Vgas You can hide a partition for Ubuntu by using Gparted to apply the "hidden" flag. I'm not sure if it will show up in Windows or not, but in Windows you can always just remove the assigned letter using Disk Management.
Comment: ok, i'll give it try and let you know ;)
tkx guys.
Comment: well, i tried what you suggested guys and it worked :) now my HDD looks like https://www.dropbox.com/s/9d6egciyb9ncnz3/HDD.png

btw, i've done some search an found what i was looking for:
http://en.community.dell.com/support-forums/laptop/w/laptop/how-to-clone-the-dell-diagnostic-utility-partition-onto-a-bare-drive-using-imagex-and-mkbt.aspx

but the thing is since i already have 4 primary partition and the one i just recovered (7gb) is part of an extended partition, i think it's no longer possible to get back my dell partition,isn't?
Answer: Since you've stated that your extended partition has 2 logical data only partitions on it, you could always move that
partition to the left, and then extend it to eat up the 6gb of space. You will then be able to create a 6gb logical
partition.
Steps:

In terminal type "sudo apt-get install gparted".
Go to the Unity Dash, and search "gparted". Click the Gparted result to run Gparted.
Right click on the extended partition, and choose "Resize/Move".
Change the "Free space preceding" entry to "0", and click "Resize/Move". [To make the button
clickable you may need to click into one of the other boxes first, but don't edit them.]
Click the checkmark at the top of Gparted, and then click "Apply" in the prompt to apply the changes.
When it finishes you can click "Close". Gparted will re-scan your devices, and you should now see the
free space listed in your extended partition.
Right click on the free space, and choose "New".
Enter you desired partition paramiters, and click "Add". Click the checkmark, and then click "Apply" to apply the
changes.
Click "close". You now have another partition! :)

Notes:

Never move partitions that have an OS on them, or are being used by a program that will expect them to be in
specific place unless you know what you're doing as this can have dire concequences like inability to boot and operating system.
Always backup your entire hard drive (or at least data on the partitions you're modifying) before engaging in any kind
of disk management activities, because it only takes one error to change your life forever.

Additional Resources:

Gparted Manual: http://gparted.org/display-doc.php?name=help-manual
What disk partitioning is: http://en.wikipedia.org/wiki/Disk_partitioning
What Are The Risks Of Partitioning Drives: https://superuser.com/questions/402569/what-are-the-risks-of-partitioning-drives
Disks, Partitions, Partition-tables, and Filesystems: http://paste.ubuntu.com/7682570/
Comment: You can use NTFS, I only put fat32 as an example because it's one of the most widely supported filesytems. NTFS is better since it supports large files. Using the manage flags section you can apply a hidden flag to hide the partition in Ubuntu. I'm not sure if it will show up in Windows, but if it does you can use Disk Management to hide it by removing the assigned letter. To access Disk Management go to control panel/system and security/create and format partitions. Right click on the partition, and choose "Change drive letters and paths". Then remove the letter.
Comment: great explanation.
but should it be in fat32 or could i use ntfs? also how to make it hidden? is it possible using the 'manage flags' section?

5th partition without format


Will a PVC weld cure to fill 1 mm?

Question: When we PVC-weld an ending with a flexible pipe, the pipe is usually very snug in the ending. The weld makes the bond permanent and ensures that no fluid can pass through.
I'm trying to double-purpose a shop-vac to become an air pump. The ending pictured (white plastic) is not quite snug in the shop-vac air outlet. It wobbles ever so slightly—to the tune of perhaps 1 mm on each side (1/32" or thereabout).
I'm concerned that the welding product meant for this sort of joint will not quite cure while filling such a big gap, that it will either fail by leaking or by not curing outright.
Will a PVC weld cure to fill 1 mm? What other bonding agent could I use as a filler before using, or in addition to, the PVC weld?
Comment: *I'm trying to double-purpose a shop-vac to become an air pump.* - I'm not sure what you're hoping to pump with this setup, but a Shop-Vac will develop an ultimate pressure of about 50"wc, or 1.8psi under ideal circumstances.  This will be a terrible pump.  Maybe enough to fill an air mattress but that's about it.  Shop vacs are optimized for airflow, not for pressure.
Answer: It might work or it might not work.
PVC pipe and fittings are not really 'glued' together but are solvent welded. The inside of the fittings are designed with a tapered hub (the inside diameter of the hub gets smaller further in, slightly smaller than the pipe's outside diameter). The solvent cement, 'melts' the PVC and when pushed together the PVC of the pipe and the fitting mix together. That is why the fittings are so tight.
Because this is a chemical weld, you need to be sure that you are using the correct chemical with the correct material. Are you sure that the outlet of your shop vac is PVC and not ABS or some other kind of plastic?
You might have better results using a two-part epoxy product designed for plastics.
Comment: Epoxy is not that harmful in the amounts we are talking. Get one of the two part epoxies or JB weld from the hardware store.
Comment: Epoxies are great for specific applications. They function as both fillers and adhesives, which is what this 1mm gap need.
Comment: @Sam  I hope you're not breathing PVC cement vapors either!  And yes, construction adhesive should work well.  In any case, always make sure your work area is well ventilated.
Comment: Ah... good point. It's indeed likely ABS, not PVC. But epoxy is rather  problematic. It's quite harmful if inhaled, and is best left for the professionals who know what they're doing? The pump is not that strong. It's only 5 HP—good for a shop vac, minuscule for a pump. Might a multi-purpose construction adhesive (that handles wood, drywall, plaster, ceramic, brick, concrete) not be a suitable substitute?
Answer:
Will a PVC weld cure to fill 1 mm? What other bonding agent could I use as a filler before using, or in addition to, the PVC weld?

As others have mentioned, PVC weld only works on PVC. The black part in your image reads <code>>PP<</code>, which means it is probably made of polypropylene.
My recommendation would be a flexible polyurethane or silicone based adhesive, e.g. construction glue. Even RTV silicone can work. As usual, clean the surfaces well and if possible, scratch them a bit with sandpaper to make the glue stick better.
Epoxy may work, but it does not bond very well to polypropylene and may start to come apart as the machine vibrates.
Comment: Yeah, the "resin identification code" triangle is more common. But also beware, the marking is part of the mold and it does happen that the material gets changed but the mold is not updated.
Comment: Good eye catching the `>PP<` (and how nice of them to identify the material). This is apparently a distinct form of identification. I'm used to a single-digit number inside a triangle (or an oval?), with some values indicating suitability as, say, a water bottle, and others not, but not to a pair of letters.
Answer: These things are not designed to go together.  They are not made of the same kind of plastic.
And PVC cement is not made to bridge gaps. That would never hold against pressure.
Since leakage is not mission critical here, all you need is a gasket of the right thickness shaped like a cylinder.  Nothing easier; wrap the white part with a few laps of masking tape until it is the right thickness.   "How many" will be found by experimentation, it's easy to peel off and re-do if wrong.
Keep in mind, average shop vacs are NOT rated to run at low airflow (unless they are).  When you hear the vac motor "whine up" because the inlet is blocked, that is what they cannot do continuously.  Certain vacs are made for this duty, they are built with a separate air stream to cool the motor, so "revving up" cools them even more.
Comment: I like the gasket idea; it's cheap and doesn't require messing around with sticky compounds that might or might not stick. Also, it is a good warning about keeping the motor cool. In the case of blocking the _outlet_ side of the vac, it might not actually "whine up" because you are not creating a "partial vacuum" in the impeller housing (or whatever the main fan is called). I've seen vacs used for inflating air mattresses and such-like, but would emphasize the warnings that these machines aren't really designed for low-flow, high pressure applications.
Answer: The PVC welding cements rely on the PVC fitting fitting together in a very tight fashion. I doubt that you'd have satisfactory results based on my experiences. Your best solution would be to get a two part epoxy and roughen up both surfaces with sand paper  to the maximum depth and apply the epoxy and let cure for the required time.
Answer: Another option might be to model the two parts combined, and 3d-print a replacement.  However threads are incredibly faffy to mock up.
The advantage is that if it breaks you can print another one reasonably easily.  Same if the part needs a minor tweak, and you can have a smooth(ish) bore through the middle for improved airflow.
Comment: I intend to do this on my dust extractor system, which has up to three adapters cobbled together.

Will a PVC weld cure to fill 1 mm?


"explode() expects parameter 2 to be string, object given" [ Laravel, Vue ]

Question: I want to implement a search functionality in laravel using vue.js and i got an error

explode() expects parameter 2 to be string, object given

i stucked at it and i still cant make it work.
What im doing wrong?
Here my Controller

     public function index(Request $request)
     {
        $query = Employee::orderBy($request->column, $request->direction)
                            ->paginate($request->per_page);
        if($request->search) {
            $query->where(function($query) use ($request) {
                $query->where('emp_name', 'like', '%' . $request->search . '%')
                ->orWhere('salary', 'like', '%' . $request->search . '%');
            });
        }
        return EmployeeResource::collection($query);
     }

My Template

            <input type="text"
                placeholder="Search"
                v-model="query.search"
                @keyup.enter="fetchUser()">

And My Vue.js code

  export default {

    props: ['source'],

    mounted() {
        this.fetchUser();
    },

    data() {
        return {
            emp: [],
            columns: [
       'ID','Emp_name','salary','phone_number','created_at'
            ],

            query: {
                page: 1,
                column: 'id',
                direction: 'desc',
                per_page: 5,
                search: ''
            },

            pagination: {}
        }
    },

    methods: {

        prev() {
            if(this.pagination.prev) {
                this.query.page--;
                this.fetchUser();
            }
        },

        next() {
            if(this.pagination.next) {
                this.query.page++;
                this.fetchUser();
            }
        },

        fetchUser() {
            fetch(`${this.source}?column=${this.query.column}&direction=${this.query.direction}&page=${this.query.page}&per_page=${this.query.per_page}&search=${this.query.search}`)
            .then(res => res.json())
            .then(res => {
                this.emp = res.data;
                this.pagination = {
                    prev: res.links.prev,
                    next: res.links.next,
                }
            })

        },

        toggleOrder(column) {
            if(column == this.query.column) {
                if(this.query.direction === 'desc') {
                    this.query.direction = 'asc';
                } else {
                    this.query.direction = 'desc';
                }
            } else {
                this.query.column = column;
                this.query.direction = 'asc';
            }

            this.fetchUser();
        }

      }
  }

I'll appreciate of all your help, Thanks you!!
Comment: move the  ->paginate($request->per_page); call to the end of the query.
Comment: can you provide more code? does it give a file name or line number where you are using `.explode`?
Comment: bro, i didnt use `explode`
Comment: But something you are calling does! And that will be identified by looking at ALL the error message and not just a summary. There should be a code file name and a line number
Answer: You're executing your query here
$query = Employee::orderBy($request->column, $request->direction)
                            ->paginate($request->per_page);

Meaning you have a result here, not a query builder instance anymore.
You have to move paginate() after the search queries to make it work.
     public function index(Request $request)
     {
        $query = Employee::orderBy($request->column, $request->direction);

        if($request->search) {
            $query->where(function($query) use ($request) {
                $query->where('emp_name', 'like', '%' . $request->search . '%')
                ->orWhere('salary', 'like', '%' . $request->search . '%');
            });
        }

        $employees = $query->paginate($request->per_page); // execute the query

        return EmployeeResource::collection($employees);
     }


Why is $t^2+1$ not irreducible in $\mathbb{Z}/2\mathbb{Z}[t]$?

Question: Is it because $t+1=t-1$ in this ring, and so $t^2+1=(t+1)(t+1)$?
Comment: Yep, that's right, since also $t+1$ is not a unit.
Comment: ... and nonzero, i.e. irreducibles are nonzero and nonunit by definition.
Answer: Yes, in that ring $ 1 = -1 $ (their difference is in $2 \mathbb Z[t]$) so $t+1=t-1$ and so $t^2+1=t^2-1=(t+1)(t-1)=(t+1)(t+1)$
Answer: There are many ways of seeing that $t^2+1$ is reducible. A polynomial with coefficients in a field $F$  of degree 2 (or 3) being reducible  is equivalent to having a root in $F$.(Then for such a root $a$ one can factorize with $(t-a)$ as a factor).
Here $t=1$ makes the value of polynomial zero thereby showing reducibility.
Now in any field of prime characteristic $p$ one has $(a+b)^p = a^p + b^p$.
Using this we can see $(t+1)^2= t^2+1^2= t^2+1$ thus showing this polynomial is reducible.(has repeated roots).
Answer: It has a root:  $1^2+1=2\cong0\pmod2$.


Why does my money disappear in the GTA V stock exchange?

Question: I recently watched a video showing me that if I ignored all of Lester's assassination missions until after the big score, I could make a ton more money. The first step after the big score was to invest all of the money you had into Debonaire Cigarettes, which should give you a huge return after you complete Lester's next assassination mission. I put all 41 million dollars I had into Debonaire, and it all disappeared. It said my portfolio was empty, and I only had $68 left. Luckily I turned auto save off, but can someone explain this to me? The only thing I can think of is that this is rockstars way of telling people not to exploit the stock market. ( Playing on Xbox One)
Comment: Did you try checking your portfolio on both markets?  What platform are you playing on?  As far I know, this isn't Rockstar telling people not to exploit the stock market.  The whole point of the Lester assassination missions is that Lester and Franklin are exploiting the stock market by causing certain companies to crash.
Answer: Exploiting the stock market is Rockstar's intended design choice when Lester's assassination missions, and is also why Lester tells you what companies are going to be affected by the assassinations.
Stock market portfolios are not shared between characters. It is possible you swapped characters between making the investments and reviewing the profits. While character Franklin has $500,000 invested in Debonaire, Trevor does not. It is also possible you are looking at the wrong investment portfolio as there are two portfolios: LCN and BAWSAQ. Looking at the LCN portfolio will not show you investments made in the BAWSAQ portfolio.
Another potential reason is that you invested in the wrong company. You might have unwittingly put your stock into Redwood while thinking it was Debonaire Cigarettes. Unlikely, but not impossible; you could have tanked your own shares and now can only be recovered for a fraction of it's original value.
Lastly, you may have encountered a glitch. Rockstar games have a solid reputation for producing glitch-free in comparison to, say, Bethesda Softworks but that does not mean it can't happen. Other players have reported losing their investment money while playing Lester's assination missions. It could be possible it happened to you too. In this case, your only options are to load from saved game, check for any available updates, restart your console and hope for the best. Sorry about that...


Find bootstrapped confidence interval with bootstrapped library

Question: So let's imagine I have an array of sample data which is normally distributed. What I want, is to compute the probability of another sample being less than -3 and provide a bootstrapped confidence interval for that probability. After doing some research, I found the bootstrapped python library which I want to use to find the CI.
So I have:
import numpy as np
import bootstrapped.bootstrap as bs
import bootstrapped.stats_functions as bs_stats
mu, sigma = 2.5, 4 # mean and standard deviation
samples = np.random.normal(mu, sigma, 1000)
bs.bootstrap(samples, stat_func= ???)

What should I write for stat_func ? I tried writing a lambda function to compute the probability of -3, but it did not work. I know how to compute the probability of a sample being less than -3, it's simply the CI which I am having a hard time dealing with.
Answer: I followed the example of stat_functions.mean from the bootstrapped package. Below it is wrapped in a 'factory' so that you can specify the level at which you want to calculate the frequency (sadly you cannot pass it as an optional argument to functions that bootstrap() is expecting). Basically prob_less_func_factory(level) returns a function that calculates the proportion of your sample that is less than that level. It can be used for matrices just like the example I followed.
def prob_less_func_factory(level = -3.0):
    def prob_less_func(values, axis=1):
        '''Returns the proportion of samples that are less than the 'level' of each row of a matrix'''
        return np.mean(np.asmatrix(values)<level, axis=axis).A1
    return prob_less_func

Now you pass it in like so
level = -3
bs_res = bs.bootstrap(samples, stat_func = prob_less_func_factory(level=level))

and the result I get (yours will be slightly different because samples is random) is
0.088    (0.06999999999999999, 0.105)

so the boostrap function estimated (well, calculated) the proportion of values in samples that are less than -3 to be 0.088 and the confidence interval around it is (0.06999999999999999, 0.105)
For checking we can calculate the theoretical value of one sample from your distribution being less than -3:
from scipy.stats import norm
print(f'Theoretical Prob(N(mean={mu},std={sigma})<{level}): {norm.cdf(level, loc=mu,scale =sigma)}')

and we get
Theoretical Prob(N(mean=2.5,std=4)<-3): 0.08456572235133569

so it all seems consistent consistent.


Kitchen dimmer dims lights in adjacent room, but not always

Question: I have a weird wiring fault.
The kitchen and the dining room each have dimmer switches that work fine individually. However, if the dining room dimmer is on and within a certain range of positions (about halfway), the kitchen dimmer dims both sets of lights (not fully, but to some extent).
I can't imagine this being by design. What type of miswiring could explain these symptoms?
edit: Both lights are on the same circuit.
Looking inside, the kitchen dimmer looks uninteresting:

The back box in the dining room is, frankly, a mess:

Suspiciously, the dining room dimmer has two wires connected to the L1 terminal:

I've not yet attempted to trace what goes where, but would love to hear your thoughts on what might be going on here.
P.S. The dining room has a single LED bulb which is well below the 60W minimum the dimmer is rated for. I doubt that's relevant, but am mentioning for completeness.
Comment: Are these dimmers on the same homerun circuit back to the consumer unit, or on different homeruns?
Comment: @ThreePhaseEel: They're on the same circuit.
Answer: In case someone runs into a similar problem, here is what I found and how I fixed the fault.
In the dining room, it turned out that the L1 terminal was connected to line and C to the load. This is the opposite to what I'd expect but I think is fine electrically (do correct me if I'm wrong). Anyway, swapping them round made no difference.
What did make a difference was replacing the dimmer in the dining room with one that's rated for the load (a single LED bulb). That made the problem go away completely.
(I'd still love to understand how the dimmer was picking up what was going on in another part of the circuit though.)


Virtual COM port works in PuTTy but not in my program

Question: When I connect a device to the computer using USB virtual COM port and open the port in my application (in Qt, QSerialPort), it receives nothing.
When I open the port in PuTTy, it works as expected.
Surprisingly, after closing PuTTy and opening the port in my application again, it started to work as expected.
This problem only occurs with some devices, namely Raspberry Pi Pico, but not with other devices like STM32 USB VCP and USB-UART transceivers.
Answer: The likely cause is that the USB device needs to have the DTR signal (which is part of RS232) set to high in order to start transmitting. (many devices disregard the value of DTR, some do not)
Use serial->setDataTerminalReady(true); on QSerialPort after opening it.
PuTTy seems to set it to high after opening, but not set it low on closing. That's why it makes it work in your app after opening it once.


Why is Undyne giving me a letter after finishing the Neutral Route and reloading my save?

Question: I defeated Asgore and Flowey then went back to the save point before the fights. I was travelling back to Snowdin just for fun, when I was told to bring the letter from Undyne to Alphys. I am doing a neutral route though.
Did the game glitch because I played it as if it was a pacafist route? Was this supposed to happen?
Answer: This sounds normal, assuming you have no EXP or LV.
Reloading before the final battle counts as having beaten the game. If you have no kills and have befriended everyone at this point, you fulfil all the criteria for a True Pacifist run.


Using Nokogiri to create XML element with namespace

Question: I use Nokogiri that would create XML. I want to have the following structure:
<content:encode>text</content>

I have tried this code:
xml.content['encoded'] {xml.text "text"}

but it gives me an error.
How do I write this correctly? A similar example is in Referencing declared namespaces.
Comment: Good job telling us what code you tried. In the future, you should always supply the exact error message you received, not just that you got an error.
Answer:
Your example doesn't make sense; you say that you want "encode" and then you attempt to write "encoded".
Your example doesn't make sense, as it is not valid XML. You have an opening encode tag with the namespace content, and then you try to close it with a content tag. You want either <content:encode>text</content:encode> or you want <encode:content>text</encode:content>. (Which do you want?)
You did not follow the example in the link you gave. If you want a content element with namespace encoded, then per the example you should write:
xml['encoded'].content{ xml.text "text" }

However, also per the example, you must declare any namespaces you want to reference. So do this:
require 'nokogiri'

builder = Nokogiri::XML::Builder.new do |xml|
  xml.root('xmlns:encoded' => 'bar') do
    xml['encoded'].content{ xml.text "text" }
  end
end
puts builder.to_xml
#=> <?xml version="1.0"?>
#=> <root xmlns:encoded="bar">
#=>   <encoded:content>text</encoded:content>
#=> </root>

Edit: If you really only need a single element with no root, using Nokogiri is overkill. Just do:
str = "Hello World"
xml = "<encoded:content>#{str}</encoded:content>"
puts xml
#=> <encoded:content>Hello World</encoded:content>

If you really need to use Nokogiri, but only want the first sub-root element, do:
xml_str = builder.doc.root.children.first.to_s
#=> "<encoded:content>text</encoded:content>"

Comment: Thank you. But we need to get just such a structure.
text
 ....  - extra lines, they are not needed
Comment: @Delaf I do not understand your comments. Did what I write not help you? Are you saying that you want/need no newlines in your Nokogiri XML output?
Comment: Your example-works. But it adds extra lines to the code http://pastie.org/1581058
Comment: @Delaf I've edited the answer to possibly address your needs.
Comment: You have no idea how much you helped me. Thanks.


Why can't I access view IDs directly in RecyclerView.ViewHolder?

Question: I'm developing an Android app using RecyclerView, and I'm trying to access view IDs directly in my ViewHolder class. According to the documentation, this seems to be possible:
"A ViewHolder describes an item view and metadata about its place within the RecyclerView.
Adapter implementations should subclass ViewHolder and add fields for caching potentially expensive results."
However, when attempting to access the views directly, I receive errors. The relevant code is as follows:
class AnimalAdapter(val animals: MutableList<Animal>) :
    RecyclerView.Adapter<AnimalAdapter.AnimalViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AnimalViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.animal_card, parent, false)
        return AnimalViewHolder(view)
    }

    override fun getItemCount(): Int = animals.size

    override fun onBindViewHolder(holder: AnimalViewHolder, position: Int) {
        holder.bind(animals[position])
    }

      inner class AnimalViewHolder(itemView: View) :
          RecyclerView.ViewHolder(itemView) {
          // Setting direct references (causes errors)
          // itemView.txt_animal_id =
          itemView.findViewById(R.id.txt_animal_id)

          // Using findViewById (works, but seems unnecessary)
          val animalIdTextView: TextView =
                              itemView.findViewById(R.id.txt_animal_id)
          val calvingDateTextView: TextView =
                           itemView.findViewById(R.id.txt_calving_date)
           // ... other references ...

          fun bind(animal: Animal) {
                // This generates an error
                // itemView.txt_animal_id.text = animal.animalID

                // This works, but seems redundant
                animalIdTextView.text = animal.animalID
                // ... other updates ...
          }
     }
}

The documentation suggests that this should work. What might be causing the error? Is there a way to enable direct access to view IDs, or is this no longer supported in newer versions of Android Studio?
I appreciate any help or clarification!
Answer: It doesn't enable direct access, and in this part of the documentation you quoted:

and add fields for caching potentially expensive results

"add fields" means you have to do it. It's not automatic. I don't see anything in the documentation you quoted suggesting that fields are generated automatically for you.
Directly accessing views by name is something that used to be supported a few years ago with an extension called kotlin-android-extensions which is deprecated an no longer works with recent versions of Kotlin. See this question for more information about that.
There is an alternate way to easily get your views by name, called View Binding that is the recommended way to do it.
In your code, your after enabling View Binding in Gradle according to the instructions linked above, your ViewHolder could look like:
inner class AnimalViewHolder(itemView: View) :
    RecyclerView.ViewHolder(itemView) {

    private val viewBinding = AnimalCardBinding.bind(itemView)

    fun bind(animal: Animal) = viewBinding.apply {
          // You can directly access views by name in here
    }
}

Comment: Thank you for your explanation. I was following an older tutorial where direct access to views by name was more straightforward. I appreciate your clarification about the recent changes in Kotlin and the suggestion of View Binding as an alternative. I will consider this approach for my project. Thanks again!


Fundamental group of $SO(3)$

Question: How can I show that the universal cover of $SO(n)$, for $n\ge 3$, is a double cover? And how does that reflect the fact that the fundamental group of $SO(n)$ has two elements? What is the relation between the fundamental group of a topological space and its universal cover? How come that $SU(2)$ is simply connected but $SO(3)$ is not? Thank you!
Comment: You are asking a whole lot of questions at the same time. This makes it difficult to give an answer, which is on the one hand comprehensible and on the other hand exhaustive. Maybe you should first ask how the fundamental group of a topological space relates to its universal cover, illustrated with the example of $SO(n)$.
Answer: Adapted from this answer.
The fact that the sphere $SU(2)$ is a twofold cover of $SO(3)$ can be seen by viewing $SU(2)$ as the group of unit quaternions, which acts by conjugation on the real $3$-dimensional space of purely imaginary quaternions as explained here; the action can be seen to be by elements of $SO(3)$, and two unit quaternions that have the same action differ by a factor $-1$ (call these antipodes of each other).
This fact, together with the fact that $SU(2)$ is connected, shows that that $SO(3)$ is not simply connected. Indeed, one can take a path from a unit quaternion to its antipode, and map this path to $SO(3)$ (take the rotation action defined by each unit quaterion on the path), where it becomes a loop (in $SO(3)$ its starting and ending point are identified). This loop cannot be contracted in $SO(3)$: if it could, we could perform the corresponding deformation to the path in $SU(2)$ as well, contracting it to a point while keeping the endpoints antipodes of each other all the time, which is absurd.
And $SU(2)$ is simply connected because the set of unit quaternions is homeomorphic to the $3$-sphere $\{\,(a,b,c,d)\in\mathbf R^4\mid a^2+b^2+c^2+d^2=1\,\}$ (the $n$-sphere is simply connected for all $n>1$). Therefore forming a new loop in $SO(3)$ by going around the one indicated above twice, so that the result lifts to a loop in $SU(2)$, the new loop can be contracted in $SO(3)$ (just contract the loop "covering" it in $SU(2)$ to a point, and project that deformation back to $SO(3)$). One can conclude from this that the fundamental group of $SO(3)$ has two elements.
For $SO(n)$ things are more complicated to describe explicitly.
Comment: Not clear at all for a beginer
Comment: I disagree, I think it is clear enough.
Answer: There are advanced techniques that I am not familiar with (e.g. using fiber bundles, differential geometry) to show that $\pi_1(SO(n)) = \pi_1(SO(3))$ for all $n > 3$. Now $SO(3)$ is homeomorphic to $\Bbb{R}P^3$ which by the Van - Kampen Theorem has $\pi_1$ isomorphic to that for $\Bbb{R}P^2$. This of course is known to have fundamental group isomorphic to $\Bbb{Z}/2\Bbb{Z}$.
Comment: The intuition for the fiber bundle technique, on the other hand, is not so bad:  Any map from $S^1$ to $SO(n)$ is homotopic to one which lands in the top left $2\times 2$ $SO(2)$ block.  Any homotopy of such a map is homotopic to another homotopy which lands in the $SO(3)$ block, so once you get to $SO(3)$, you've seen all there is to see about the fundamental group.
Comment: How I need to use Van-Kampen theorem for proof that $\pi_1$ of $\mathbb{R}P^3$ is homeomorphic to $\mathbb{R}P^2$?
Comment: @kp9r4d $\mathbb{R}P^3 = \mathbb{R}P^2 \cup_{S^2} D^3 $

Fundamental group of $SO(3)$


Multiple possible termination conditions for while loops

Question: I am just started to learn Python and I have a probem. I want to make a program that adds books to a list, but allows these 6 possible answers to a question (yes or no), and if someone doesn't answer, it repeats the question.
add = input("Do you want add book?")

while True:
    add != ("no") or ("NO") or ("No") or ("yes") or ("Yes") or ("YES")
    add = input("Do you want add book?")
    if add == ("no") or ("NO") or ("No") or ("yes") or ("YES") or ("Yes"):
        break

Thanks for help.
Comment: That test doesn't do what you think, but you can write it as `if add.lower() in ["no", "yes"]:`
Comment: The first line in your *while* loop is irrelevant as you assign something to *add* but then immediately replace it with the return value from *input()* The subsequent test is equivalent to *if add == 'no'*
Answer: There are really only two answers because you can normalise the input to a particular case - either upper- or lower-case.
Thus you can simplify your code as follows:
while not (add := input('Do you want to add book? ').lower()) in {'yes', 'no'}:
    print('Please answer yes or no')

print(f'You answered "{add}"')

Comment: `while (add := input(...)) not in {'yes', 'no'}` would probably be clearer.
Comment: what ":=" do???
Comment: @YBG := is an assignment expression - a.k.a walrus operator. See: https://peps.python.org/pep-0572/


Best way to display contextual user entry errors in a tabbed html form

Question: I have a web application that has a very large form. That form is split into several tabbed areas, which divide the entry of the data in to logical blocks.
I have a single submit button outside the tabbed content area.
On submit I need to show the user errors, which may quite likely be on tabs that are currently hidden.

I need to highlight which tab contains errors
I need to tell the user why a particular element has an error (required, formatting, etc)

Can anyone suggest a good way to approach this? One way would be to turn the tabbed form into a wizard, but on a very large form like this, it is useful to switch from one tab to another and then go back if you want to, without be forced to go through a next/previous style navigation.
Answer: 1. Limit inputs to things that are required
It should be very clear to your users why they are being asked to input anything on a form.  I assume you are already doing this and there are still just too many inputs that different users may want to use on your very large form.  In that case, consider putting all required inputs up top and then grouping optional inputs in an advanced collapsible area that is hidden by default.

2. Provide real time validation on each input
There are very few cases where it makes sense to prevent a user from typing certain characters as they fill in an input field.  Don't prevent invalid data from being entered but Do provide real time feedback so users know when the application is expecting something different.

3. Consider using vertical scrolling (accordion) instead of tabs
Horizontal tabs have limits and also suffer from having a universal order.  In some cultures the far right tab is considered first but in no cultures is the item at the very bottom considered to be first or most important.
Vertical scrolling is preferred on touchscreens and even on desktops with mouse wheels, page down key, and other hardware that we have all become accustomed to.
Answer: Consider using "badges" on tabs with an error: http://getbootstrap.com/components/#badges
(Even if you're not using Bootstrap, the concept is still relevant.)
This is a very popular technique, used by many major websites and apps, to prompt users to click on something because they want to investigate what the unread message is. Of course, you'll want to color it appropriately to reinforce that it's an error (e.g. red). You can even add a tiny hint of animation to the badge to draw attention to it, although it needs to be subtle.
This technique will only be effective if all of the tabs are always visible at the top of the screen. If they are not, for example if they've scrolled down on the page, you may need something more aggressive. When they click the submit button, you can display a dialog box that says something along the lines of:

You have X entry errors on step X. Would you like to go there now?

(If there are multiple errors, you can start with the first one just to keep it from being overwhelming.) This is slightly more intrusive, but it gives them a convenient shortcut to jump to the error. And considering they've already clicked the submit button and they're expecting the form to submit, the dialog box won't be interrupting them while they're filling out the form.
I would still recommend the first, more subtle option (badges), and switch to the dialog box if user testing reveals that they simply aren't obvious enough.


How should I clean my slate and stucco outdoor patio area?

Question: I have a patio with a slate floor, with (what used to be) a bright white grout of some sort, surrounded by stucco half-walls that are topped with additional slate. The stucco has a rough surface. There is a buildup of dirt and mold/algae on the slate, grout and stucco.
I think that I want to power wash the area. I'm concerned about damaging the slate, grout or stucco. I'm also clueless about aftercare. A bunch of questions:
Is powerwashing appropriate? Is there a recommended PSI or power level?
Other than using minimum pressure, is there anything special I should do to avoid damaging the patio?
Is sealing slate and/or stucco recommended after power washing? I prefer a natural look. I wouldn't want the slate to be shiny. Are there classes of sealant products I should stay away from or gravitate towards?
Answer: If you are not sure about whether a  your paving is capable of withstanding the jet of water from a power washer, test a small hidden area first.
Natural stone and slabs have the highest resistance to power jet water stream. It is not uncommon to see small pieces of stone or slate taken of by the water stream. You should wear glasses because this can ricochet and get lodged in your eyeball ... ouch.
You need to take care with "wet-cast" slabs and paving.
I would recommend using karchers dirt blaster ...

It has a weird cone shape on the end that actually spins the water at high pressure making the cleaning much more effective.
You should then regulate the distance and angle at your own consideration.
I usually pull away when cleaning the concrete joints as the water stream can easily rip them out. Then do a quick sweep on the tile and only concentrate on areas where tough stains are left. There have been times where small pieces of stone were forced out of the slab and nearly blinded me -- Wear safety goggles!
There is also patio cleaner that does not spew water and debris all over the place and is a bit safer to use on sensitive material.

Power-washing is particularly effective at removing mosses and algae
  that seem to thrive on certain types of paving, most notably
  'textured' patio paving and clay brick pavers. We find that the
  addition of Jeyes Fluid tends to inhibit the return of this type of
  vegetation for a short time, whilst not affecting the pavement
  surface. Certain quality sealants are also reputed to inhibit or
  prevent algal growth, but are an expensive way to eliminate a minor
  problem.

You would need to find some local advice on sealants that you can use on the particular slabs you have got. They can work well sometimes -- but also can be a waste of time the rest of times.


Parent div with height: 100% doesn't work

Question:
Possible Duplicate:
CSS - 100% height doesn't work

I have 3 divs, the div-1 is a background and div-2 and div-3 are two containers (one for text and one for photo).

#div-1 {
  width: 100%;
  height: 100%;
  padding: 40px 0;
  margin: 0;
}

#div-2 {
  width: 500px;
  margin: 0;
  float: left;
}

#div-3 {
  width: 200px;
  margin: 0;
  float: right;
}

This is what I get:

Why height: 100% doesn't work?
Comment: try this: `html,body{height:100%;}` The height of these elements is automatic.
Comment: This worked for me. Looking at the standard default css rules, I see no reason for these elements to have auto height. Oh, I guess because html has no parent its 100% height is zero? Strange.
Answer: This can work

Comment: Unnecessary complexity.
Answer: The height of #div-1 is 100% but 100% of nothing, as it relies on the parent tags height I believe. Try setting your body to 100% height in css.
Comment: That doesn't work: https://jsfiddle.net/qecd1r3y/
100vh does.
Answer: Remove height: 100%; in #div-1 and add position: absolute;. It will work just fine.
Answer: you need to add clear flow after you applying floating properties to elements, more about it here: http://www.quirksmode.org/css/clearing.html


Making Ubuntu Download Bootable from USB

Question: How can I make the Ubuntu download bootable from a USB stick without downloading third party software?
Thanks!
Comment: what is the host OS from where you want to create the bootable USB?
Answer: Assuming you're on Linux,

Open a terminal and type sudo su
lsblk to note which device is your USB.
mkdir /mnt/myusb && mount /dev/sdb1 /mnt/myusb (replace b1 with your actual usb device id, /dev/sdb1 in my case)
grub-install --force --no-floppy --boot-directory=/mnt/myusb/boot /dev/sdb (replacing b if necessary)
cd /mnt/myusb/boot/grub
wget pendrivelinux.com/downloads/multibootlinux/grub.cfg
Copy the iso to the root of your pen drive and modify the grub.cfg file in order to load the isos from the correct location.
set timeout=10
set default=0
menuentry "Run Ubuntu Live ISO" {
loopback loop /ubuntu-xx-xx-i386.iso linux (loop)/casper/vmlinuz boot=casper iso-scan/filename=/ubuntu-xx-xx-i386.iso splash --
initrd (loop)/casper/initrd.lz
}

(replace "/ubuntu-xx-xx-i386.iso" with the correct file name)

Open any disk utility software and make sure that the partition has got the "boot" flag. If not, set it.

DONE!
Answer: Open a terminal window and enter this command
sudo apt-get install unetbootin
to install Unetbootin from the Ubuntu repositories.
Once added to your system, plug in the flashdrive, launch unetbootin, select the version of *buntu you have already downloaded, and unetbootin will create a bootable LiveUSB drive.


Markdown Reference Link with shields.io badges

Question: How to make sure that the shields.io badge points to the site, and do that using reference-style markdown links.
This works fine
<code>[![](https://img.shields.io/badge/code%20style-black-black.svg?style=for-the-badge&labelColor=gray)][http://github.com/psf/black]
</code>
[][http://github.com/psf/black]
This doesn't works
<code>![]([black-shield])[black]

[black]: http://github.com/psf/black
[black-shield]: https://img.shields.io/badge/code%20style-black-black.svg?style=for-the-badge&labelColor=gray
</code>
Answer: The correct syntax is
<code>[![General badge](https://img.shields.io/badge/<SUBJECT>-<STATUS>-<COLOR>.svg)](https://shields.io/)
</code>
Example
<code>[![Stack Overflow Badge](https://img.shields.io/badge/Stack%20Overflow-F58025?logo=stackoverflow&logoColor=fff&style=flat)](https://stackoverflow.com/users/12299287/cryptocode)
</code>
Produces
Comment: Thank you, but my objective was to use it with reference-style links
Comment: This works. I tested it just now. Thanks for this!
Answer: Works using square brackets!

<code>[![][black-shield]][black]

[black]: http://github.com/psf/black
[black-shield]: https://img.shields.io/badge/code%20style-black-black.svg?style=for-the-badge&labelColor=gray
</code>


What is the name of this type of form and what alternative are available?

Question: I'm designing a form for a web app and I'm looking for the name of this type of form element:
Also, I'm trying to find alternative for small screens (mobile). I can't find any way to do this properly.
Answer: Matching Information
Is an evaluation test type.

The matching test item format provides a way for learners to connect a word, sentence or phrase in one column to a corresponding word, sentence or phrase in a second column. The items in the first column are called premises and the answers in the second column are the responses. The convention is for learners to match the premise on the left with a given response on the right. By convention, the items in Column A are numbered and the items in Column B are labeled with capital letters.

From theelearningcoach.com

About small screens solutions there's already a helpful answer here.
To save space I would not hesitate to use a double screen with horizontal scrolling animation after selecting the first item and after clicking the second one to check the solution:


How to safely upgrade ec2 instance type in amazon web services? m4.large to m4.xlarge?

Question: We have created an instance (m4.large) where we installed Windows Server 2012 r2. It is currently used as a terminal server for SAP business one software with license Remote Desktop Service per device (CAL). We made a mistake in choosing the instance type for it is recommended to use m4.xlarge for terminal servers. We would like to upgrade our instance type to resolve memory requirement issue.
We are new to AWS and would like to seek advise on what would be our best approach. Is it safe to directly upgrade the instance? We have no concerns of downtime for now.
We are also considering in making a snapshot first then launch it on an new and upgraded instance. We would like to ask if RDS licenses will also be migrated?
Thanks you for your kind replies.
Comment: If you dont care about downtime. Just go to aws EC2 console, stop your instance. Select dropdown list > change instance type to new type. Then start your instance again. Just want to make sure your instance must be EBS backed instance type. If your instance is Storage Backed type, you will lose all data in ephemeral storage.
Answer: You can change instance type anytime, but the instance must be stopped. If you are not concerned with some minutes of downtime just stop the instance, change the instance type and start the instance. Taking a snapshot as a backup before and frequently is a good precaution.
This change will have no impact on RDS, as that is a separate service.
Answer: One way would be simply to stop instance and upgrade it.

Warning
When you stop an instance, the data on any instance store volumes is
erased. Therefore, if you have any data on instance store volumes that
you want to keep, be sure to back it up to persistent storage.
Any Amazon EBS volumes remain attached to the instance, and their data
persists.
Any data stored in the RAM of the host computer or the instance store
volumes of the host computer is gone.

Another Way if you want minimal Downtime is you can create an AMI of it and Spin up new instance with Instance type and size what ever you desire and assign the domain or Elastic IP of current instance to new one and terminate old instance.
Also Regarding The RDS Licensing Please Mention what you mean by upgrading , but there will an outage when you apply for instance upgrade or License is Modified.
Also Upgrading EC2 Instance has no affect on Existing RDS as both are different services.
For Reference on Ms SQL DB , Please read these AWS Documentation:
Modifying a DB Instance Running the Microsoft SQL Server Database Engine
Microsoft SQL Server on Amazon RDS
Answer: As m4.large is EBS backed instance. so the loss of data is not a concern in the above question. Just select->right click-> stop the instance and change the instance type to m4.xlarge by right click->instance settings->instance type.
Also for your second question RDS is a separate service, so it won't get affected.


WPF Listbox focus from viewmodel

Question: I've stumbled upon the well-known problem with Listbox and focus. I'm setting ItemsSource from the viewmodel and at some point I need to reload them and set selection and focus to a specific item, say:
private readonly ObservableCollection<ItemViewModel> items;
private ItemViewModel selectedItem;

private void Process()
{
    items.Clear();

    for (int i = 0; i < 100; i++)
    {
        items.Add(new ItemViewModel(i));
    }

    var item = items.FirstOrDefault(i => i.Value == 25);
    SelectedItem = item;
}

public ObservableCollection<ItemViewModel> Items { /* usual stuff */ }
public ItemViewModel SelectedItem { /* usual stuff */ }

Binding may look like:
<ListBox ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}" />

After calling the method item gets selected, but does not receive focus.
I've read a lot on the Internet and on StackOverflow, but all answers I found involve manual filling of the listbox, not via binding from viewmodel. So the question is: how can I properly focus newly selected item in the presented scenario?

To add some context, I'm implementing a sidebar file browser:

I need keyboard navigation on the listbox below treeview.
Comment: I think this could be done with a Behavior attached to the ListBox. Hookup to the SelectedItemChanged-event and manually check/set the focus accordingly. Apart from 'can be done' the queations remains 'should it be done'. If you hit  for example a button to trigger your update, isn't it normal then that any item/ the ListBox looses focus??
Comment: @SanchoPanza, Look at my edits. I've tried that, but then listbox steals focus even if it weren't focused earlier. Upon selecting item in the treeview, I select first element in listbox afterwards. This effectively disallow navigation on the treeview, because listbox immediately becomes focused...
Comment: @SanchoPanza, regarding *should it be done*, scenario is: user chooses ".." and presses Enter; I reload files to show upper folder contents and I'd like to select the folder user was in to improve navigation. Since elements were reloaded, there is none focused and if I didn't set focus on my own, user would end up with first item being focused and selected after pressing the down-arrow key...
Comment: @Spook Have you tried to set `IsSynchronizedWithCurrentItem` in `ListBox` xaml?
Comment: @Spook: The `ListBox` must be focused for the item to get highlighted unless you modify the control template for the `ListBoxItem`.
Answer: I ended up with the following code in control's codebehind:
public void FixListboxFocus()
{
    if (lbFiles.SelectedItem != null)
    {
        lbFiles.ScrollIntoView(lbFiles.SelectedItem);
        lbFiles.UpdateLayout();

        var item = lbFiles.ItemContainerGenerator.ContainerFromItem(viewModel.SelectedFile);
        if (item != null && item is ListBoxItem listBoxItem && !listBoxItem.IsFocused)
            listBoxItem.Focus();
    }
}

This method is available for calling from within viewModel, which calls it every time it sets the selection:
var file = files.FirstOrDefault(f => f.Path.Equals(subfolderName, StringComparison.OrdinalIgnoreCase));
if (file != null)
    SelectedFile = file;
else
    SelectedFile = files.FirstOrDefault();

access.FixListboxFocus();

The access is view passed to ViewModel via interface (to keep separation between presentation and logic). The relevant XAML part looks like following:
<ListBox x:Name="lbFiles" ItemsSource="{Binding Files}" SelectedItem="{Binding SelectedFile}" />

Comment: Instead of calling the method from VM, you could have used the SelectionChanged event of the ListBox
Comment: @NawedNabiZada, no, I can't, because this method should be called *only* when selection changes from within viewmodel. Otherwise it ends up with listbox stealing focus every time its selection changes (ie. items being reloaded)
Answer: Here is a solution that might work for you:
The control:
class FocusableListBox : ListBox
{
    #region Dependency Proeprty

    public static readonly DependencyProperty IsFocusedControlProperty = DependencyProperty.Register("IsFocusedControl", typeof(Boolean), typeof(FocusableListBox), new UIPropertyMetadata(false, OnIsFocusedChanged));

    public Boolean IsFocusedControl
    {
        get { return (Boolean)GetValue(IsFocusedControlProperty); }
        set { SetValue(IsFocusedControlProperty, value); }
    }

    public static void OnIsFocusedChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
    {
        ListBox listBox = dependencyObject as ListBox;
        listBox.Focus();
    }

    #endregion Dependency Proeprty
}

The ViewModel:
 class ViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private Boolean _IsFocused;
    private String selectedItem;

    public ObservableCollection<String> Items { get; private set; }
    public String SelectedItem
    {
        get
        {
            return selectedItem;
        }
        set
        {
            selectedItem = value;
            RaisePropertyChanged("SelectedItem");
        }
    }

    public Boolean IsFocused
    {
        get { return _IsFocused; }
        set
        {
            _IsFocused = value;
            RaisePropertyChanged("IsFocused");
        }
    }

    public ViewModel()
    {
        Items = new ObservableCollection<string>();
        Process();
    }

    private void Process()
    {
        Items.Clear();

        for (int i = 0; i < 100; i++)
        {
            Items.Add(i.ToString());
        }

        ChangeFocusedElement("2");
    }

    public void ChangeFocusedElement(string newElement)
    {
        var item = Items.FirstOrDefault(i => i == newElement);
        IsFocused = false;
        SelectedItem = item;
        IsFocused = true;
    }

    private void RaisePropertyChanged(String propName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
    }
}

The XAML:
<local:FocusableListBox ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}"
                            HorizontalAlignment="Left" VerticalAlignment="Stretch"
                            ScrollViewer.VerticalScrollBarVisibility="Auto"
                            Width="200"
                            IsFocusedControl="{Binding IsFocused, Mode=TwoWay}"/>

The update call:
 _viewModel.ChangeFocusedElement("10");

WPF Listbox focus from viewmodel


Is a weakly differentiable, $L^{2}$ function over $\mathbb{R}_{+}$, bounded?

Question: Consider $u \in W^{1,2}(\mathbb{R}_{+})$. Is there always a bounded representative of $u$?
I have come across this sort of question multiple times, but I just cannot wrap my head around it. This is connected, at least from my point of view and from my experience, to this more generic question: given a function $u \in L^p(\mathbb{R})$, for $p \neq \infty$, under which additional hypothesis (if any) is $u$ bounded?
I have often found myself with integrability hypotheses over unbounded sets such as $\mathbb{R}$ and have hoped to deduce some boundedness, but I can't think clearly about it.
Comment: $u(x) =\chi_{[-1,1]}(x)\cdot |x|^{-s}$, $s>0$,  are in $L^p$ (with a certain condition between $s$ and $p$), so $L^p$ functions are not bounded.
Comment: Of course, right. Thank you for the remark!
Answer: We have the continuity of the embedding $W^{1,2}(0,1)$ into $C([0,1])$. That  is there is $c>0$ such that for all $u$
$$
\|u\|_{L^\infty(0,1)} \le c \|u\|_{W^{1,2}(0,1)} .
$$
This is true for all intervals of length $1$, so we can sum this up:
$$
\sum_{n=-\infty}^\infty \|u\|_{L^\infty(n,n+1)}^2 \le c^2 \sum_{n=-\infty}^\infty \|u\|_{W^{1,2}(n,n+1)}^2 = c^2 \|u\|_{W^{1,2}(\mathbb R)}^2.
$$
Hence, the series on the left is converging, in particular $\|u\|_{L^\infty(\mathbb R)} \le  c \|u\|_{W^{1,2}(\mathbb R)}$.
Moreover, the series tells us that
$$
\lim_{|n|\to\infty}\|u\|_{L^\infty(n,n+1)}=0,
$$
i.e., $u$ kind of vanishes at infinity.


Can a java object serialize itself?

Question: I have a JPanel that handles a bunch of settings that I would like to save and load by file name.
It seems natural that since the panel already exists and knows all about itself that the load and save should be handled by the panel itself through a Save(String filename) and Load(String filename) actions attached to buttons.
However all the serialization and/or persistence examples I find require an external overseer that passes the object into the serializer functions.
Can I simply serialize the panel object using something similar to writeObject(this) and this=readObject() or is there a standard way to do this that I haven't searched properly for?
Comment: Yes, you can. But do you want to? The MVC pattern is there for a reason.
Comment: I freely admit that this is C++ reasoning but it just seems odd that application settings are a fit for MVC style partitioning.  I totally agree with you in 99% of the rest of the application, however.
Comment: Interesting point, but where do the settings go once you load them? If you app has to access them somehow, why should you load a (relatively) heavyweight JPanel for that, instead of only a model class?
Answer: I am not sure I understand the question entirely but all the serialization logic definitely resides in the Object methods (readObject and writeObject).
When talking about who would invoke those methods, it all depends on your use case. There are several reasons for serializing an object, like for ex: if one wants to pass the object across the wire to another JVM, or you want to persist the state of the object between JVM restarts, or any other use case where the entire state of the Object needs to be saved outside of the JVM its running in.
In your use case, can it be done? yes. Is that a good practice, maybe not. An abstraction is better because what if you have a need to persist other objects not accessible to JPanel? What if there is a need perform some other logic before serializing an object? What if there is a need for ordering or some other requirement that cannot be handle by your JPanel?
You can learn more about Java Serialization here
Comment: Just to close this out: I've converted the initial quick-and-dirty class layout to one based on MVC principles and the friction that brought me to ask this question disappeared.  Score 1 for the Java team, and thanks also to @Jochen

Can a java object serialize itself?


How to solve this error in tab menu with database?

Question: In my app I have tab menu : Add tab,View tab.
in Add tab: I add data to database
in View tab: I select data from database into listview
now I have problem: when I add a data from add tab and switch into viewtab I can't view last adding into database, but if I close app and open it new time, i can get last adding
any idea about solve of this problem please
Code :
`view tab code:
public class ViewEvents extends Activity {
DBAdapter DB=new DBAdapter(this);

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.viewevents);

    final ListView myListView = (ListView)findViewById(R.id.MyList);

    //  final EditText myEditText = (EditText)findViewById(R.id.myEditText);

      // Create the array list of to do items
      final ArrayList<String> todoItems = new ArrayList<String>();
      final ArrayAdapter<String>  aa = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, todoItems);

       DB.open();
     Cursor c=DB.select();
      c.moveToFirst();
      Integer n=new Integer(c.getCount());

    for(int i=0;i<c.getCount();i++)
    {
         todoItems.add(0, c.getString(0));
         c.moveToNext();
    }

       // todoItems.add(0, c.getString(0));
        aa.notifyDataSetChanged();
        myListView.setAdapter(aa);

}

}
add tab code:
public View getView(int position, View convertView, ViewGroup parent) {
        ButtonHolder holder2;
        if (convertView == null) {

            holder2 = new ButtonHolder();

            convertView = mInflater.inflate(R.layout.item, null);

            holder2.caption = (Button) convertView.findViewById(R.id.Bte);

            convertView.setTag(holder2);

        } else {

            holder2 = (ButtonHolder) convertView.getTag();

        }

        holder2.caption.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub

                TextView names = holderpartner.caption;
                TextView date = holderdv.caption;
                TextView time = holderviewmtime.caption;
                String address = "sdfgkhj";

                event e=new event( names.getText().toString(), address,date.getText().toString(), new java.sql.Time(9, 30, 30));

                DB.open();
                DB.insertTask(e);

                date.setText("");
                time.setText("");

                Toast.makeText(getBaseContext(), "Done",Toast.LENGTH_LONG).show();

            }
        });`

Comment: are you notifying the URI of changes? are you calling setNotificationUri on the cursor when you query? It's hard to tell without seeing your code
Answer: Add addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); flag to your intent in your TabHostActivity, so everytime you select your tab it's content gets refreshed. Do something similar to this :
intent = new Intent().setClass(this, Notices.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        spec = tabHost.newTabSpec("notices").setIndicator(getString(R.string.notices),
                res.getDrawable(R.drawable.ic_tab_notices))
            .setContent(intent);
        tabHost.addTab(spec);

In my situation it's working.


How to insert PHP value in jQuery Datepicker

Question: I have the following code to set the minimum date of datepicker.
$( "#sd" ).datepicker({
    // before datepicker opens run this function
    beforeShow: function(){
        // this gets today's date
        var theDate = new Date();
        // sets "theDate" 2 days ahead of today
        theDate.setDate(theDate.getDate() + 2);
        // set min date as 2 days from today
        $(this).datepicker('option','minDate',theDate);
    },
    // When datepicker for start date closes run this function
    onClose: function(){
        // this gets the selected start date
        var theDate = new Date($(this).datepicker('getDate'));
        // this sets "theDate" 1 day forward of start date
        theDate.setDate(theDate.getDate() + 1);
        // set min date for the end date as one day after start date
        $('#ed').datepicker('option','minDate',theDate);

    }
});

If today's date is 11/14/2012 then the value of datepicker is 11/16/2012. However, since the date should be based on server's datetime I cannot use javascript date because it will get the current date of the computer instead of server's date.
So what I did is change it to the following code:
$( "#sd" ).datepicker({
    // before datepicker opens run this function
    beforeShow: function(){
        // this gets today's date
        var theDate = new Date();
        // sets "theDate" 2 days ahead of today
        //theDate.setDate(theDate.getDate() + 2);
        theDate.setDate(<?php echo $this->session->userdata('checkin') ?>);
        // set min date as 2 days from today
        $(this).datepicker('option','minDate',theDate);
    },
    // When datepicker for start date closes run this function
    onClose: function(){
        // this gets the selected start date
        var theDate = new Date($(this).datepicker('getDate'));
        // this sets "theDate" 1 day forward of start date
        theDate.setDate(theDate.getDate() + 1);
        // set min date for the end date as one day after start date
        $('#ed').datepicker('option','minDate',theDate);

    }
});

Please take a look at this line:
theDate.setDate(<?php echo $this->session->userdata('checkin') ?>);

BTW, I am using codeigniter session.
This works great but the problem is the minimum date in datepicker is not set to 11/16/2012 instead it was set to 11/2/2012.
Anyone know how to insert the PHP value correctly into jQuery?
Comment: You're sure the value of $this->session->userdata('checkin') isn't actually 11/2/2012..??
Comment: I am sure the value is 11/16/2012..
Comment: Based on what you're showing here that just doesn't seem to be the case.  You're simply echoing that value, and you're getting a value, so that must be the value stored in that session variable from what I'm seeing.

What if you dump the entire session array to the screen at this point?  What do you get then?
Comment: seems that if you worked with UTC dates on both ends would help
Answer: I have already found the answer. Here it is:
$( "#sd" ).datepicker({
    // before datepicker opens run this function
    beforeShow: function(){
        // this gets today's date
        var theDate = new Date();
        theDate.setDate(<?php echo date('d', strtotime($this->session->userdata('checkin'))) ?>);
        // set min date as 2 days from today
        $(this).datepicker('option','minDate',theDate);
    },
    // When datepicker for start date closes run this function
    onClose: function(){
        // this gets the selected start date
        var theDate = new Date($(this).datepicker('getDate'));
        // this sets "theDate" 1 day forward of start date
        theDate.setDate(theDate.getDate() + 1);
        // set min date for the end date as one day after start date
        $('#ed').datepicker('option','minDate',theDate);

    }
});

It should extract the day only and not the whole date.
theDate.setDate(<?php echo date('d', strtotime($this->session->userdata('checkin'))) ?>);

Instead of
theDate.setDate(<?php echo $this->session->userdata('checkin') ?>);


Detect definitions of same name of enum and #define in C++ source

Question: We have a C++ source with a large number of definitions made using #define and enum. Recently while analyzing a bug, we found out that there were a few definitions made using the #define pre-processor directive which were also members of an enum. The values assigned to them were different though.
For example,
#define ABC 100

typedef enum
{
  ABC = 1,
  DEF
} MY_ENUM;

ABC is defined in two places.
Amazingly, Visual Studio did not give us an error. Not even a warning.
We are worried that there might be other definitions that were defined in the same manner and want to find them out.
Increasing the warning level of the compiler did not give us any errors. We can still build the source without errors when such re-definitions are present . The number of warnings increased massively and there are too many warnings to go through one by one.
Does anyone know a way to detect these multiple definitions?
We are using Visual Studio 2010 Professional as the IDE.
Comment: This is why you shouldn't use all-uppercase for anything other than macros.
Comment: Sounds like a good moment to have a cleanup day. Replace the `#define` by `const int ABC = 100;` and Visual Studio will complain.
Answer: Use enum class instead of enum. This way, you can make sure that you are using the right  thing in the right place
You can go through the following answers to get a better idea
Enum vs Strongly typed enum
NOTE: enum class is a C++11 feature and is not among those supported by Visual Studio 2010.
Comment: Thanks. Even though I cannot use it if VS2010 support it, I would keep this in mind. I didn't know about enum class.
Comment: If is solves your purpose, please mark it as correct.
Answer: Even VS wouldn't compile the code you've shown. But it could do what you describe if the #define came after the enum definition. And if that's the case, all compilers will do exactly what you describe. The code is in no way invalid (or even warning-worthy) then.
As @TheApache suggests, a C++11 solution would be to use an enum class instead of a plain enum, but that would require you to go through all use cases and add qualification. Not to mention that fact that Visual Studio 2010 doesn't support it.
Using a macro and an enumerator of the same name in a project is a colossally bad idea, so you should definitely resolve your situation by removing this condition. Ideally, you would simply remove the macro definitions and use the enumerators only.
Comment: Thanks, though if VS2010 doesn't support it, I cannot use it.
Comment: @nushydude What *I* think you should do (and what the answer says) is simply get rid of the macros altogether.


Bathroom faucet drip

Question: I had a faucet drip in my bathroom sink. I determined it was the hot water (confirmed by the warm drip and it stopped when I shut off the hot under the sink). I assumed that the stem went (which happened before, to the cold stem) but after replacing it and tightening everything, I still have the drip. Can I assume the faucet needs to go?  It's an old Price Pfister.
Note: The plumbing and shutoff valves are new but the faucet assembly is old.
Answer: There should have been a 'packing' in the stem assembly.  This is usually a gasket or a series of gaskets that prevent water from seeping around the stem when the stem is in the off position.  If the packing was in good shape (no cracks or brittleness) and was seated properly then I would say it's time to replace the whole fixture.
In my past experience if the leak doesn't come from the stem or the packing around it, then the time finding the problem and the cost to fix it usually is not worth it for a cheaper fixture.
Answer: Replacing the stem assembly complete with rings/washers etc should have solved your problem. Did you carefully check the bottom seat and assure there was nothing stuck to it or if it was cracked or worn? There were a lot of different seating arraignments on these older sets. I have to say however, most Price Pfister models are not high end quality even though they have a good warranty. You can fuss with this thing, but if you don't find the problem easily and cheaply, bite the bullet and go with a new higher end Delta or Kohler fixture with ceramic cartridges.

Bathroom faucet drip


How do I make Codeblocks work on macOS big sur?

Question: I recently installed Code::Blocks (version 17.12) on my MacBook Pro 2020 which runs on macOS Big Sur, but something is not working and I can't figure out why. I also installed Python Launcher and IDLE and Xcode and XQuartz. Maybe I installed the wrong version? Can anyone help me? Or maybe recommend an alternative that works on macOS? I print screened the error it shows every time I try to run codeblocks and attached it here
Answer: I had the same problem with you. I searched on Google and found this. This was written by Xaviou from the Code::Blocks community. I used revision 12286's CB_20210102_rev12286_macOS-11.1_x64-wx3.1.5.dmg and it worked perfectly on my MacBook running macOS Big Sur 11.1.
Code::Blocks won't work on macOS Catalina and above because Catalina dropped support for 32-bit apps, and Code::Blocks is a 32-bit app. Xaviou rewrote and compiled the code from Code::Block's GitHub repo to make it 64-bit and usable.
Comment: 2 links mentioned above:
https://forums.codeblocks.org/index.php/topic,24306.0.html
https://drive.google.com/drive/folders/1-r9cbW1I8ZkaCt6iYDhcXH981n5FJTpV
Comment: Remember to uninstall and delete any Code::Blocks files you had before installing!
Comment: Thank you! I just installed the version you sent and it works, but it doesn't run my code. This is the error it shows: error: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun at: /Library...  I tried installing Xcode but it still doesn't run. Do you know what I have to do?
Comment: Have you tried this? https://stackoverflow.com/a/52522566/15017153
I'm sorry it took so long to reply -- I forgot about this
Answer: Code Block is not supported to work on BigSur at the moment and the developers need to update it unfortunately.


Do niche web applications still strive for legacy browser support?

Question: I'm developing a web application that work on mobile, tablet and laptop/desktop.
I'm curious about how common it is for niche web application developers to disregard legacy browser support, especially when supporting them will more than likely introduce problems surrounding integral application specifications.
The user-experience and overall quality of my application will be far greater if I don't spend time problem-solving and making concessions for legacy browsers.
Anything I should be conscious of if I decide not to support legacy browsers?
Comment: Yes, all applications should still support legacy viewers that are relevant in their target market. It's just that what constitutes legacy browser changes over time.
Answer: I would go ahead with your intuition of not supporting legacy browsers if you feel they only constitute a small part of your target population. However, I would recommend clearly highlighting that the browsing/interaction experience would be greatly enhanced if the user uses one of the modern browsers (mention those browsers clearly) and ensure the users see this information prominently.
The way you display this information is dependent on your application but ensure that people are aware of it and don't tend to skim past it.
From an anecdotal point of view, I work on projects for a client which uses only IE and one of our projects required me to design a internal portal for them. The client had certain requirements which would have needed CSS 3 support and though 80 % of the client uses IE 9, there were reservations about whether the remaining 20 % would get affected by this decision. We decided to go with the CSS3 emphasis and we introduced logic in the code so that any detected IE8 users were immediately informed that though they would be able to use the portal, some functionalities would be unavailable to them. Within one month of rolling out, we found that 60 % of the users who had visited the site using IE8 were now using IE9.
Comment: One warning though,find out the weight age of those 20 % ,if they are the senior directors or some senior management who have significant influence in your project,you will need to accommodate it.It wont be applicable in your case but a point of view
Answer: Another nice point with StatCounter is that you can easily spot the trends too, so if you know how long your project will take to develop you can get a good idea of the usage of that browser in the future too. ("Currently only 3% of our target audience use IE7, and by the time it is actually release that figure will be less than 2%...")
Not only that; take into account the expected lifespan of the product. If you're spending an additional 20% of development trying to get it to function in a browser that only 2% of people are using right now, if the product lifespan is expected to be several years then you'll have built in redundant code early on that isn't needed soon after launch. The more redundant code the more there is to go wrong (and the harder it is to debug) during the life of the application.
Comment: Great point !! This is another tactic I should use :)
Answer: Supporting legacy browsers can add significant costs to development and those costs compound when considering maintenance of the code. Legacy browser support shouldn't be as problematic if your methods of building the site/application make use of progressive enhancement.
For example, CSS is great when browsers ignore features it can't support. Nothing crashes.
I would inform the users that they may experience issues with the browser they're using and recommend an upgrade for the best experience with the newer version.


Do I need to create a ntfs partition for Windows running in a virtual machine?

Question: I plan to install 14.04 on my laptop,and then install Windows 8.1 inside a virtual machine (not yet decide which software for virtual machine).
When I install 14.04, do I need to create some ntfs partitions for Windows (one ntfs partition for installing Windows, and another ntfs partition for storing personal data files which can be shared between Windows and Ubuntu)?
Thanks!
Answer: No, you do not need to create any NTFS partitions. If you are going to install Ubuntu on your laptop and then install Windows inside a virtual machine, you do not need to create an NTFS partition to install Windows nor would you need to create an NTFS partition to share personal files between Ubuntu and Windows.
For the installation, what the virtual software does (for example: Virtual Box or VMWare) is it creates a file (with an extension of .vmdk or .vdi for example, depending on what software/option you use). That file acts as the "hard drive" for the virtual machine. The file is created and stored on your host operating system (your Ubuntu), so it doesn't need an NTFS partiton. If you want to think about it another way, "inside" the file itself is an NTFS filesystem, that's what the virtual machine uses, but you don't have to worry about that at all.
For sharing folders, the virtual software you use gives you an option to share folders between the host and guest OS. When you "share" a folder, your Windows machine will "mount" it as if it was a file server, so it doesn't need to be an NTFS partition either. Take a look at this page and this question for more information on how you do this folder sharing.


Install GParted 1.0

Question: What's the easiest way to install this brand new version of GParted?
There is a download link over here: https://sourceforge.net/projects/gparted/files/gparted/gparted-1.0.0/gparted-1.0.0.tar.gz/download
But it seems to require compilation. Is there an easier way to do it?
Comment: How does it require compilation, it's an image you burn to flash drive and boot from it.
Comment: Nope. And be warned: the readme on your link says 1.0 but the download is the ISO for version 0.33 Seem dubious to me.
Answer: The download link you provided downloads the 0.33 version. I found another source for 1.0.

But it seems to require compilation. Is there an easier way to do it?

The download I link to is an ISO. So you burn it to a dvd/cd/usb. That is the more usual way since you need to unmount partitions you want to alter. And the root disk is mounted if you use an installed version.
If you want it as a direct installation the method where you need to compile it/install it from a tar.gz is the only method. There is no debian installer yet, nor a PPA on launchpad for this version.
Comment: Thanks for pointing out the problem with the link. I corrected my post with the link to gparted-1.0.0.tar.gz. That's what I was asking about, not the ISO. So you might want to edit your answer to reflect that.
Comment: The last sentence is the one you want: no there is no easier method (yet).
Comment: Indeed. But the readme file is pretty explicit, it even says how to download and install all the dependencies in one shot. Alas, after compiling and installing, GParted would not launch on my system. I have gained new respect for the official software repository...

Install GParted 1.0


Creating a string with items separated by commas from an array results in undefined variable

Question: I have an array with email addresses. I need to send a PHP mail to multiple email addresses at once, so I need to have my $to variable like this:
$to = 'email@example.com, firstname.lastname@example.com, firstname.lastname@example.com';

I use this code to achieve this:
$prefix = '';
foreach($result AS $recipient_row) {
    $to .= $prefix . '"' . $recipient_row['email'] . '"';
    $prefix = ', ';
}

This results in an undefined variable: to on line 225... Line 225 is the line with $to .= $prefix . '"' . $recipient_row['email'] . '"';.
The email is being sent to multiple people, so the code does work, but it just produces this error. Why does that happen and how do I stop this error from appearing?
Answer: You can do something like this,
$to = implode(", ", $recipient_row);  // output: email@example.com, firstname.lastname@example.com, email@example.com

implode join array elements with a string.
Comment: Do I have to add this to my already existing code? Or should I replace the $to variable with your code?
Comment: No, instead of `foreach` loop you can use `implode` to get multiple email addresses in a string. You don't have to use `foreach` loop.
Answer: You need to initialize $to if you want to use .=, like this:
$prefix = '';
$to = '';
foreach($result AS $recipient_row) {
    $to .= $prefix . '"' . $recipient_row['email'] . '"';
    $prefix = ', ';
}


Create a bulit-in Like button

Question: I'm using the Javascript SDK , and I can't create a built-in Like button. I read the following source: https://developers.facebook.com/docs/opengraph/actions/builtin/likes/
And it said to invoke this:
<code>curl -X POST \
     -F 'access_token=USER_ACCESS_TOKEN' \
     -F 'object=OG_OBJECT_URL' \
     https://graph.facebook.com/[User FB ID]/og.likes
</code>
I really don't know how to use that in the JS SDK . I have intermediate knowledge with JS and PHP , but i never used that.
What can get me started with this?
Comment: The answer on http://facebook.stackoverflow.com/questions/11315195/why-is-open-graph-built-in-like-not-working-anymore has a JS SDK example
Answer: That just means to make a POST request with certain parameters/data in the body.  You can do that with jquery
Comment: No, you can – see not on the page you linked: _"Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol."_

Create a bulit-in Like button


Error showing :Ethernet Cable unplugged in Ubuntu 14.04?

Question: I have been using dual boot OS one is windows 10 and another Os is Ubuntu 14.04. in windows10 ethernet working perfectly fine.but when I using ubuntu it showing ethernet cable is unplugged. I have changed the LAN wire but no use. am kind of new to ubuntu please help me? I have read similar questions here but no solution given by anyone.
System Information:
Dell Vostro 3000 series;
3gb Ram
500gb hardisk
Comment: Please edit the question to include the results of `lspci`
Answer: I had this kind of trouble, I'm not sure is the best way but it use to help doing :
sudo ifconfig eth0 down
sudo ifconfig eth0 up
depending on your system "eth0" may be something else, just have a look whith
sudo ifconfig
This will show you all your interfaces
hope this help !


What am I supposed to do in Riddler's "Drain Pain" challenge?

Question: I see the Batman Reserved spot, but nothing happens when I land on it. I've landed on the wall inside the green neon circle with no results.
It looks like I'm supposed to turn the hole so it's over the room at each level, but I can't figure out how to rotate the circle.
What am I supposed to do in the Drain Pain challenge?
Comment: Ah, this is the area that I confused my other answer with the fans on.  You basically have to lower the Batmobile down to the ledge on the same level as the spikes and move left and right.  The wheels of the Batmobile will cause the ring of spikes to rotate.  Keep rotating to clear paths to go down as far as you can go.
Comment: @JeffMercado So obvious it just might work. :-) If you add that as  an answer, I'll accept it. This game sometimes makes me feel dumb. At least I figured out the spoiler ending: Bruce Wayne *is* Batman.
Comment: Was working on getting a video up for another question. Was thinking about doing a video for this but I've already cleared that area, it wouldn't be the same.
Comment: @JeffMercado I've got a video I'll add.
Answer: You basically have to lower the Batmobile down to the ledge on the same level as the spikes and move left and right. The wheels of the Batmobile will cause the ring of spikes to rotate. Keep rotating to clear paths to go down as far as you can go.
The different slopes you can go down are numbered one to three.  Just follow the order of the slopes to get down to the next level.  For the first and second slopes, you'll want to turn it until you are over the spray painted bat logo for each level.  The third level, you'll have to backtrack and go to the first and second slopes to open up the path.