autostart compton on Lubuntu 16.04 LTS

Question: The command /usr/bin/compton -I 0.04 -O 0.04 -D 10 -m 1.0 -C -f -i 1.0 -e 1.0 -G --vsync none --unredir-if-possible --unredir-if-possible-delay 0 -b does exactly what I want, when I run it from a terminal after booting my system as usual. However, putting this command into autostart, causes Lubuntu to fail loading the graphical environment after boot, i.e. no taskbar appears, no windows can be opened using shortcuts, rightclick on the desktop does nothing, etc. Only the default desktop background remains visible (I haven't changed it), but that's all.
It seems to be completely irrelevant, which of the multiple options for autostarting I use, at least I tried:

The graphical wizard from Preferences -> Default applications for LXSession -> Autostart -> Manual autostarted applications -> Add
Adding the command to ~/.config/openbox/autostart
Adding the command to ~/.config/lxsession/Lubuntu/autostart
Placing a compton.desktop file in ~/.config/autostart/ (this works for me with other applications)
Using systemd as explained in this highly related question (works for me with other applications, but gives me exact same error here as described in the question)

I assume that my command is correct, because it does what it should when being run from a terminal after boot is complete, and I assume that my error is not related to my use of autostart, because it works for me just fine with other applications.
I'm also using a freshly set up and updated Lubuntu 16.04 LTS VM under Virtualbox to make sure it does not interfer with other configurations on my productive system.
Comment: Each line, including the last line, in `~/.config/openbox/autostart` has to end with a space followed by `&`. You could also insert `sleep ns` (where `n` is the number of seconds) at the start of a line and that may help.
Comment: @DKBose Alright - now my grapical interface does appear again. But it seems, that `compton` hasn't started at all, no effects are present, and `ps -e` doesn't list it either.
Answer: The experienced behavior consists of two separate problems.

The problem with the disappearing graphical interface is related to the use of the option --unredir-if-possible. While this option works fine if used when invoking compton after boot, it causes the graphical interface to disappear if used when compton is invoked as part of the autostart procedure. I think this is an undocumented bug, at least I haven't found any note (while similar notes appear to indicate that this option has been proven to be problematic already). I haven't found a workaround, except for not using this option as part of the compton autostart command. So far, it appears that applications in fullscreen mode work fine anyways, therefore this solution appears to be acceptable.
The problem with compton not starting or not showing the expected effects seems to be related to the point where compton gets invoked during the autostart procedure. The only point I have found that appears to work consistently, is via an entry in ~/.config/lxsession/Lubuntu/autostart. Here it is important, to write neither a leading @ nor a trailing &, despite what can be found amongst various examples on the web.

autostart compton on Lubuntu 16.04 LTS


Leaking whirlpool tub; in alcove, but no tile flange at bottom of walls

Question: In brief: my alcove whirlpool tub has always leaked at the seam between the tub and tile wall, and it needs to be fixed. I just discovered that this tub has no tile flanges where it meets the walls; does this mean that leaks are inevitable?
In detail: when we bought our house 20 years ago a previous owner had joined two bedrooms to make a master bedroom and en-suite bath with a whirlpool tub set into an alcove. I've never been impressed with the construction (e.g. no apparent floor reinforcement). Specifically, we've always had leak problems along the edges of the tub, although recaulking has seemed to fix it.
Now, after a carpenter ant infestation and opening up the wall behind the tub, I've found that the leaks were far worse than I thought, and there's significant water damage to the underlying floor. I'd consider recaulking yet again, but only if I knew it could be "done right"; if not, then I'm thinking to rip it all out and start from scratch (we plan to be here for a while).
The leak is in the center of the long side of the tub where it meets the tile wall. I've removed the drywall on the opposite side of the wall, exposing the back of that joint, and I just noticed that the tub (an American Standard model 00-2720, if anyone has a pre-Internet catalog they could dig out) has no tile flange along that wall (I assume there's none along the two short walls as well). In fact, this tub may have been designed to be set into a platform, not into an alcove.
The lack of tile flanges would be an obvious cause for the problem: when we fill the tub with water, the sides sag, and tear open the caulking; after that, there's no gravity barrier to keep the water from just heading out and down.
Is it a lost cause to try and patch this? Now that I have the back exposed I could try caulking it to within an inch of its life. However, I suspect that I'll just get leaking (and ants) again, and I don't want to have to keep checking for water damage.
Edit: for clarity, here is a diagram of the edge of an alcove tub with a flange:

Again, my tub does NOT have such a flange. so the cement backer board just rests on the edge of the tub, with a bead of caulk (attempting) to keep water coming through.
Edit 2: this is indeed a drop-in tub, which is meant to drop into a horizontal platform. It is not meant for an alcove installation.
Answer: If you clean the old caulk off, properly prepare the joint, use 100% silicone caulk ,and your tub or walls do not move more than they are suppose to (natural flexing is ok), then you should have no problems with water at the caulked joint.
For best results, fill the tub with water before caulking, and keep the tub filled until the caulk is completely dry. This will open the joint as much as possible and then leave it under compression.
If it is flexing too much and that is breaking the caulk (you mentioned it but 100% silicone should be able to flex a lot), then maybe remove the tub and reinstall with a proper mortar base.  If it still moves too much is the floor structurally deficient?
Comment: I've used 100% silicone, and it still failed. Perhaps it was poor surface prep, but my guess is that it's movement of the edges of the tub when loaded with water. The gap between the tile/cement board and the tub is 1/16" or less, and must be filled with caulk; 1/16" of movement would double this, and no way would caulk expand that much without failing. Having a tile flange would have meant the caulk joint could be wider, handle movement better, and even if it failed water would stay inside the tub.
Comment: We typically install tubs into a mortar base.  The flange of the tub is not typically designed to hold the weight of the water; the base needs to be properly supported.  I am guessing your tub may not be properly supported on the bottom.
Comment: I finally got down on the floor and looked under the tub, where I'd assumed there was support. Bingo: no support whatsoever. So, it's hanging from the three alcove edges. I'll be fixing that, and probably amending my question. (Thanks, @Damon.)
Comment: I've supported the tub by wedging various thicknesses of wood between it and the old flooring at about twenty different locations. I then removed all the old caulk, cleaned the heck (and everything else) out of the joints, sanded it, cleaned it with alcohol, and applied 100% silicone caulk. I'll be watching, but for now it isn't worth it to do more. Thanks again, @Damon.
Comment: Go you for actually taking the time to do what you can!  That is no easy fix on the back end, post install.


Site Properties with JS Continued

Question: As a result of my question here:
Passing site properties with javascript
I'm using the code below to pass text from one div to another in any instance that the data-target is equal to some elements class on a page.
$('#sp').children().each(function() {
    $($(this).data().target).html($(this).html());
});

However, I'm wondering if instead of passing text to an html element, if i could type text on the page that is equal to the data-target value - then have that text be replaced by the text in data target. For example:

My Great Company

sp.busFullName has been around since 1920

My Great Company has been around since 1920

This way I don't have to create an extra tag every time i use a property created.
Any insight would be appreciated. Thanks.
Comment: You can do that, but semantically the code would be meaningless and without JavaScript it would be unintelligible. Still want to do it?
Comment: @JonathanSampson
Yes i would like to still know how to do it. I know a small group of people will have js turned off, but in that case, much of the site functionality will be broken anyhow.
Answer: I don't think you should take this approach since it renders your code semantically meaningless and somewhat unintelligible if JavaScript isn't available in the client environment. That being said here is how I would have gone about it:
(function(){
    // Containing element's ID
    var boxID = "#sp";
    // All data-target elements within containing element
    $("[data-target]", boxID).html(function(a,b){
        // Pattern of #id.targetValue
        var pattern = boxID.slice(1) + $(this).data("target");
        // Find everything in body that contains this pattern
        $(":contains("+pattern+")", "body").html(function(c,d){
            // Replace instances of pattern in html with html
            return d.replace(pattern, b);
        });
    });
})();

Demo: http://jsfiddle.net/rpHB2/3/
Comment: What way would you suggest that is better? I'm not as experienced in server side coding so i am up for suggestions. If anything, it may be helpful to call to a separate html page that holds the property data-target values, as appose to rendering it on the page. Any thoughts you have on that would help too. Thanks.
Comment: The property is displaying correctly, but the code is breaking alot of other things on the page. Im not sure why at this point, but its removing the body tag from the page when i use it.
Comment: what does (a,b) and (c,d) mean in your script? I believe its being used on another function, and there is a conflict.
Comment: @trobbins26 I've updated it; it shouldn't affect the body element. Be sure to replace `"body"` with an element much closer to all of the elements that may contain your target values.
Comment: Ran into one small snag. When there is more than 1 instance of the name on the page, it will not recognize beyond the first one... any thoughts?
Comment: @trobbins26 The only way that could be true is is you're re-using the ID value, which you shouldn't be. ID values are supposed to be used only once per page.
Comment: Ok your right. I had an instance of my old code on the page which referred to the actual ID of the property. Thanks for your help. your final code worked perfectly.
Comment: Final question... is there any way to call the property values from another page, so i dont have to hide the values on the actual page?
Comment: @trobbins26 That is also possible; but that is an entirely different question. I would encourage you to instead use a JavaScript object-literal to store your values if you wish to approach the problem from this particular angle.
Comment: I just realized that the script is wiping out other scripts within the body of the page when searching for matching content. Is there a way to tell it not to do that?
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/19112/discussion-between-trobbins26-and-jonathan-sampson)

Site Properties with JS Continued


Use a Variable in a Query SQL

Question: I have a database with my media in it. And a query with the following line:
WHERE (((LPofCD.LPofCD) = MyKeus()))

Public Keus As String
Function MyKeus() As String
    MyKeus = Keus
End Function

In a Form I can choose: Keus=1 for LP, 2 for CD, ect. This is working fine.
Now I also want to choose >0 : so I can select ALL the items.
This is what I tried:
I fill 'Keus' with a part of the sql WHERE, like this:
Keus = [Forms]![Output_Catalog]![Kies_Medium]
Keus = "((([1_Medium].LPofCD_ID)=" & Keus & "))"

WHERE MyKeus()

But this does not work.
Anybody that can give me a solution?
Comment: you would need dynamic sql for such a think see https://stackoverflow.com/questions/28093543/writing-dynamic-sql-statement
Answer: I found the answer:
make the selection not in the query, but in the DoCmd OpenReport, like this:
If MyKeus() > 0 Then
  DoCmd.OpenReport ReportName:="Catalog_Band_Medium", _
    View:=acPreview, _
    FilterName:="Catalog_Band_Medium_Query", _
    WhereCondition:="[1_Medium].LPofCD_ID = MyKeus()", _
    WindowMode:=acWindowNormal
  DoCmd.SelectObject acReport, "Catalog_Band_Medium"
  DoCmd.Maximize
Else
  DoCmd.OpenReport "Catalog_Band_Medium", acPreview, acWindowNormal
  DoCmd.SelectObject acReport, "Catalog_Band_Medium"
  DoCmd.Maximize
End If

So, the problem I had is solved, after a long search and tried the different possibilities.

Use a Variable in a Query SQL


Will Microsoft continue to improve WebGL support in IE11?

Question: Current support for asm.js based WebGL apps (such as apps exported from Unity5) run extremely slowly on IE11. Is this feature still in active development?
Answer: No, it is extremely unlikely that Microsoft will now continue to add or significantly improve any features in IE11, because all their development effort is going into the Edge browser.
With Edge being released this month alongside Windows 10, IE11 should now be considered a legacy browser.
The flip side is that the kind of improvements you're looking for are extremely likely to appear in Edge, and since Edge is now intended to be continually updated, once it becomes established, you should see users getting new features and improvements much more quickly than has traditionally been the case with IE.
Comment: This is illustrated by the [platform status page](http://dev.modern.ie/platform/status/?filter=f3e0000bf&search=webgl), especially when you filter it down to WebGL.
Comment: Agree that most of the effort will now go into the Edge browser. The wild card is that Edge will only run on Windows 10 and forward so there will likely be a large base using IE11 for a while.


Drivers for nvidia graphics card

Question: how can I install nvidia GM107M (gtx 960M)? I use inspiron 15 7566.
Logs from lshw:
stoton@stoton-Inspiron-7566:~$ sudo lshw -C video[sudo] hasło użytkownika stoton:
  *-display UNCLAIMED
   description: 3D controller
   product: GM107M [GeForce GTX 960M]
   vendor: NVIDIA Corporation
   physical id: 0
   bus info: pci@0000:01:00.0
   version: a2
   width: 64 bits
   clock: 33MHz
   capabilities: pm msi pciexpress bus_master cap_list
   configuration: latency=0
   resources: memory:e2000000-e2ffffff memory:d0000000-dfffffff memory:e0000000-e1ffffff ioport:e000(size=128) memory:e3000000-e307ffff
*-display
   description: VGA compatible controller
   product: HD Graphics 530
   vendor: Intel Corporation
   physical id: 2
   bus info: pci@0000:00:02.0
   version: 06
   width: 64 bits
   clock: 33MHz
   capabilities: pciexpress msi pm vga_controller bus_master cap_list rom
   configuration: driver=i915 latency=0
   resources: irq:126 memory:e4000000-e4ffffff memory:c0000000-cfffffff ioport:f000(size=64) memory:c0000-dffff

@edit I use sudo apt-get instll nvidia-367
for now I have only this:
stoton@stoton-Inspiron-7566:~$ sudo lshw -C video
*-display
   description: VGA compatible controller
   product: HD Graphics 530
   vendor: Intel Corporation
   physical id: 2
   bus info: pci@0000:00:02.0
   version: 06
   width: 64 bits
   clock: 33MHz
   capabilities: pciexpress msi pm vga_controller bus_master cap_list rom
   configuration: driver=i915 latency=0
   resources: irq:126 memory:e4000000-e4ffffff memory:c0000000-cfffffff ioport:f000(size=64) memory:c0000-dffff

and my external monitor doesn't work :/
@edit2 after second restart I've got something like this:
stoton@stoton-Inspiron-7566:~$ sudo lshw -C video
*-display
   description: 3D controller
   product: GM107M [GeForce GTX 960M]
   vendor: NVIDIA Corporation
   physical id: 0
   bus info: pci@0000:01:00.0
   version: a2
   width: 64 bits
   clock: 33MHz
   capabilities: pm msi pciexpress bus_master cap_list rom
   configuration: driver=nouveau latency=0
   resources: irq:130 memory:e2000000-e2ffffff memory:d0000000-dfffffff memory:e0000000-e1ffffff ioport:e000(size=128) memory:e3000000-e307ffff
   *-display
   description: VGA compatible controller
   product: HD Graphics 530
   vendor: Intel Corporation
   physical id: 2
   bus info: pci@0000:00:02.0
   version: 06
   width: 64 bits
   clock: 33MHz
   capabilities: pciexpress msi pm vga_controller bus_master cap_list rom
   configuration: driver=i915 latency=0
   resources: irq:126 memory:e4000000-e4ffffff memory:c0000000-cfffffff ioport:f000(size=64) memory:c0000-dffff

but external monitor still doesn't work
Comment: sudo apt install nvidia-367
Comment: my external monitro doesn't work :/ look my edit
Comment: `sudo apt install nvidia-367` and reboot.
Comment: Disable Secure Boot in BIOS.
Comment: Secure boot in BIOS is disable
Comment: and still I can't see monitor in settings
Comment: When I reboot computer by moment my external monitor's working ... but after two second disable
Answer: Try additional software. That's how I installed the drivers for my GeForce GT 635M.
Go to dash (super key by default) and type in 'additional drivers' and launch the additional drivers program. Once it loads, you should see that nvidia binary driver is available but not selected. Select it, and restart when prompted.
Comment: Ok I install my graphics card, but my external monitor still doesn't work..
Comment: @Kichiin At this point I have to doubt about you actually doing what has been suggested. In the comments above it was suggested to install a specific driver version but all your edits show `nouveau` being used and that usually means the proprietary driver hasn't been installed. If you really tried to use the commands in comments above and something for whatever reason isn't working there should be error messages. Where are they? You only mention reboots, did this did that not working...
Comment: I do  sudo apt install nvidia 367. But without result, i mean hdmi monitor still doesnt works

Drivers for nvidia graphics card


Finishing moves when an enemy is on the ground

Question: Just started playing Gears of War 3 online - and I saw that when an opponent is on the floor there is a possibility to make several finish moves.  Some of the cool stuff:

Pickng up an opponent and using him as a shield.
Tearing his arm and beating him with it.

How can I perform these (and any other) finishing moves?
Answer: These finishing moves are known as executions. You can perform these on a downed enemy by standing next to them and holding Y. There are also weapon specific executions that can be performed by executing an opponent while having a specific weapon active.
See this page on the Gears Wiki for a detailed list of the different executions and how to perform them.
http://gearsofwar.wikia.com/wiki/List_of_Gears_of_War_Executions#Gears_of_War_3_Executions
Comment: Picking up an opponent and using him as a shield is not an execution, and you do it by hitting A.
Comment: @IanPugsley While not necessarily an execution in the strictest sense, using an opponent as a meat shield does kill them, and it can lead to the bag-and-tag execution.


Does Google App Engine's git Push-to-Deploy also update backends?

Question: When using appcfg.py, I had to specify backends to update them.
What about when I'm using Push-to-Deploy?
I ask because I see two of my Versions don't have the same "deployed" date -- the backend still says "6 days ago". I didn't change backends.yaml, but I did change the code that runs on that backend.
Should I see a new "deployed" date? Is git Push-to-Deploy working?
Answer: No -- It doesn't update backends.
(My cron jobs ran last night and failed because they were running old code.)
Nothin' like good ol' appcfg.py update ./ --backends


grub rescue after ububtu removing

Question: I've red plenty articles but i got no answer.
i had improperly installed ubuntu 13.04 so i wanted to remove ubuntu from my hard drive. so through live cd -> gparted i removed everything linux partition and swap then formated both to ntfs. now i have this error.
on the hdd was only the linux. nothing else.
ls output in grub rescue is (hd0,msdos1) .
set output is
prefix=(hd0,msdos1)/boor/grub
root=hd0,msdos1
hopefully it will help and you would be able to help me.
cheers lama.
Answer: You should install another boot loader and address your MBR or UEFI to the installed boot loader.
I assume you had a dual boot windows. In that case you can use windows installation cd to recovering your windows installation.

boot to installation media (cd, dvd, flash memory, etc)
go to recovery option (don't go to installation)
select reinstall MBR or bootloader
reboot

but you will miss ubuntu ;)

grub rescue after ububtu removing


error: no known conversion from 'foo1*' to 'const foo2&'

Question: May i know what to do to the parameter a in main() so that i can call the copy constructor?
class foo1 {
public:
    virtual void display() = 0;
};

class foo2 : public foo1
{
public:
    foo2();
    foo2(const foo2& a);
    void display()
    {
        cout << "Copy constructor works\n";
    }
};

int main()
{
    foo1* a = new foo2;
    foo1* b = new foo2(a);
}

thanks if anyone could help
Comment: i've tried, but i faced another error: no known conversion from 'foo1' to 'const foo2&'
Comment: downcasts need to be explicit - try `*dynamic_cast(a)`, here's the [documentation](http://en.cppreference.com/w/cpp/language/dynamic_cast)
Comment: @UnholySheep it doesn't work, error : `undefined reference to `foo2::foo2(foo2 const&)` . My code is like this `foo1* b = new foo2(*dynamic_cast(a));` , correct me if i typed wrongly
Comment: No, that is correct - it compiles, but you get a linker error, because you haven't actually defined a copy constructor - you only declared it. You need to actually write a definition for it in order to link as well
Comment: @UnholySheep i got it, thanks for your help!!
Comment: One last note: `*dynamic_cast(a)` is unsafe - you should always first check if the cast actually succeeded. So you should in reality do something along the lines of: `foo2* tmp = dynamic_cast(a); if(tmp) { b = new foo2(*tmp); }`
Comment: alright, thank you :)
Answer: Your copy constructor needs reference (address ) and you trying to pass a pointer. so ether you want to create actual object and not a pointer or deference pointer


Count all occurences in a table with mulptiple columns (SQL)

Question: I have a table that has partner id followed by multiple column combinations. My task is to count how many partners, each of those combinations have.
Here is an example of a table I'm working with:

And here is what I am looking to do:

Does anyone knows how to sort this out?
thanks
Answer: SELECT
  MAX(COMB_1) AS COMB_1,
  MAX(COMB_2) AS COMB_2,
  MAX(COMB_3) AS COMB_3,
  MAX(CATEGORY) AS CATEGORY,
  COUNT(*) AS PARTNER_COUNT
FROM NoOneNamesTheirTableInSQLQuestions
GROUP BY CONCAT_WS(';', COMB_1, COMB_2, COMB_3);

This uses a MySQL function CONCAT_WS(), but there should be equivalent ways of doing this in each of the other databases you tagged your question: Oracle and SQLite.
Comment: Hi @Bill, thank you for your solution! It suited well to what I need in a real scenario. And sorry for forgeting about the table name lol.


How to invert a System.Predicate

Question: Let's say I have a Predicate<T>, and I want to call method foo with said predicate returning true, and I want to call method bar with a predicate returning false, how can I do this:
Predicate<int> p = i => i > 0
foo(p);
bar(!p); // obviously this doesn't work

If the predicate was a Func<int, bool> f, I could just !f(i)
Comment: A `Predicate` is like a `Func`, so I don't see the problem... `!f(i)` is the right answer.
Comment: This is *not* a duplicate of the question that was linked - that's about creating an inverting expression tree. This is just delegates.
Comment: @JonSkeet: sorry, what about this one? http://stackoverflow.com/q/2166591/993547
Comment: @PatrickHofman: Yes, that looks like a better dupe. Although I prefer my answer with the extension method :)
Comment: @xanatos: The OP's `foo` and `bar` methods have a parameter of type `Predicate`, not `int`. `!p(i)` is the negation of `p(i)` and yields an `int`, not a `Predicate`, so your suggestion does not apply in this case.
Comment: @stakx in the question, the sentence: *If the predicate was a Func f, I could just !f(i)*, my comment was connected to that sentence. He says that he knows how to create the negative of a `Func`, I say that he can do the same for a `Predicate`
Answer: You can easily create a method to return an "inverted" predicate - you could even make it an extension method:
public static Predicate<T> Invert<T>(this Predicate<T> predicate)
{
    // TODO: Nullity checking
    return x => !predicate(x);
}

Then:
bar(p.Invert());

Basically it's exactly what you'd do if you had a Func<int, bool> - there's nothing "magic" about either of those delegate types.
Comment: This is perfect, I'll mark as answer in 9 minutes :)
Answer: You could wrap the predicate in a lambda.
bar(x => !p(x));

Comment: Sorry, I meant in addition to the accepted answer. I removed the word also from my post.

How to invert a System.Predicate


C - fgets skips CR character

Question: I have a c code, simply reads a line from a txt file. The file has only one line which is as below:

The code snippet to read this line is:
int** readFile(char* filename){

    int col=0, row =0;
    int i=0;
    int* numList[2048];

    for(int i = 0; i<2048; i++)
        numList[i] = (int*) malloc(6*sizeof(int));

    if(NULL == numList){

        printf("Memory error!");

    }

    char * token = NULL;

    char currentLine[25] = {'\0'};

    FILE* file = fopen(filename, "r");

    if(NULL != file){

        printf("File is opened successfully\n");

        if( NULL != fgets (currentLine, 60, file) )
        {
            int i = 0;
            while (NULL != currentLine[i]){

                printf("%d ", currentLine[i]);
                i++;
            }
        }
    }
    else
    {
        printf("File I/O Error");
        return NULL;
    }

    fclose(file);

    return numList;
}

When this code runs, I get the following output:

I observed something suspicious, which is, as you can see in the first screenshot (Content of txt file), Notepad++ shows CR LF at the end of the line. But in the output, I see 10 as the last character which is LF.
Probably I am missing a very primitive point but, I couldn't understand why CR character is not there.
Needless to say, platform is windows and this is a console program.
Thanks&Regards.
Comment: 1) In the windows environment, mutual conversion (LF <-> CRLF) is done in text mode input / output.
Comment: 2) `60` <-> `25` are doesn't match size.
Comment: You have declared `numList` as an array with automatic storage class (i.e. it is a local variable on the stack), and you have `return numList;` at the end of your function. This will return a pointer to a variable on the stack, which results in _undefined behavior_.
Comment: In fact... you really ought to make sure that you are not reading more data than the amount of memory that you have allocated... You're reading up to 60 bytes into a 25 byte array.
Comment: You really ought to read the man page for fgets, especially as it relates to newlines.
Comment: @Ian Abbott yes you are right, but I think it is another thing to discuss. Also the code is a little bit modified and some parts are removed for simplicity to ask the question.
Answer: You're opening the file in text mode. This mode ensures you can handle text files the same on any platform.
C specifies '\n' as the end of line. In Windows, the end of line is the sequence "\r\n". C (in this case, the standard library implementing stdio) will automatically translate this for you. Reading from a file on Windows in text mode will give you just \n for \r\n.
If you want to see exactly the byte contents of the file, you have to open it in binary mode instead:
FILE* file = fopen(filename, "rb");

Comment: @UgurKAYA YW. Still have a look at all the comments you received, there are quite some serious problems with the code snippet you show. I only answered your immediate question, ignoring these issues.
Comment: Thank you! This is the answer I was looking for.
Comment: yes you are right. This is not the exact code in the project, it is little bit simplified. And also it is not the exact txt file for the project, but still, yes, there are some issues and I thank everyone depicting them.

C - fgets skips CR character


User Confirmation

Question: Let me give a example:

in this case is redundant ask for the user the confirmation?
Is better just put:

I think the second way I can say to for the user 'you can return for your activities, we will inform when the export is ready' is a good way to do this journey?
Answer: First screen is correct. You're asking a question that requires an answer via an interaction. This can be answered in natural language by user's interaction. Moreover, a simple Yes would be a lot better.
The second screen isn't right. The system is not asking anything, just providing an information. Having 2 buttons for this isn't correct. If you want to use buttons, a simple "I understand" button should suffice.
However, what you mentioned in your last paragraph is a good idea, instead of having the user wait for the process to be finished, just do as you say, let the user do whatever she wants and get back to this process once she's notified everything is ready
Comment: agreed. I'd put the status (spinner or progress bar) in line with the item that you just requested the export for. Possibly replacing the export button to avoid duplicate requests.
Comment: @Devin If i ask for the user, whats the  formatted he would like to export a file inside the body of the modal is okay do that? Is like Sketch ask for u 'wich artboard would you like to export?'
Comment: I'm not sure I understand your question, but just in case it's what I understand, I'd recommend to keep all elements of a flow together. for example, the format (I assume you mean extension or type here, is that correct?) should be added **before** user clicks the **Export** button. If this is what you mean and you need additional help, please create another question so it doesn't mix with this one since both questions are different :)
Answer: I think you don't need a confirmation for this action since there is no harm done if they export the file. I only use confirmation dialogs for things that can't be un-done.
In the instance you've illustrated, I'd suggest that you replace the "export" button with a status indicator (ideally a progress bar, but a spinner if that's easier) letting the user know that they successfully requested an export and to prevent duplicate requests.

User Confirmation


Facebook API Permission Page

Question: Well i want to allow Facebook login on my site. I have created the API and user's can login to the website. But for the first time a pop up comes to the users asking for Permission.
https://developers.facebook.com/docs/concepts/login/login-architecture/
Can i just skip the users from this permission page and directly logs them in.
Thanks
Comment: tell what you want clearly do you want to check the login credentials the 1st time the user logs in and upon the subsequent login you dont want to check is it??
Answer: Any person must accept the basic permission for getting their Facebook profile data for use in your website
Comment: so it means there is no way we can skip that basic authentication part! thanks

Facebook API Permission Page


What to do with private bug reports on launchpad?

Question: Over time I gathered more than 10 launchpad bug reports that were reported with apport, initially marked as private and never responded to.
There was one I've discussed additionally on IRC and that's the only one I can remember being processed.
What should I do with them? How can I make sure they don't contain anything really private before making those bugs public?
Comment: int_ua, as a member of Bug Control myself, I've provided guidelines here.  I have also removed the list of bugs you have identified as "private" here, because until those bugs are public, the bug numbers should only be discussed with Bug Controllers or people who can see those private bugs.  I've copied the bug list to my clipboard, and if you would like me to assist you with looking at these bugs (assuming i can see them), please [join me in the chat system](http://chat.stackexchange.com/rooms/11384/private-bugs-discussion) so you and I can discuss these.  Or on IRC, whichever you prefer.
Comment: However, I would prefer to work with you on private bugs over IRC, because we can coordinate with other bugcontrollers on it, but I can try and answer any other questions you have via the chat channel I've linked in my previous comment.  :)
Answer: As a member of Bug Control, I've had to work with these private bugs on occasion.  There is a specific policy on handling private bugs, and checking for specific information.
For crash bugs, the general thing you have to look for in the private bugs are core dumps and any stacktraces that may be on the bug.  If a core dump is attached, remove it.  If there's stacktraces attached, look through them and identify any possibly private data in the stack trace.  If there looks to be private data, then what you have to do is download the stacktrace, edit out the private data, upload the edited version, then remove the old version.
As well, find any other Personally Identifiable Information, or private information, such as social security numbers, account numbers, passwords, etc., and try and edit those out as well.
For other private bugs, it depends, since there are separate policies for private security bugs which I am not privy to as those are handled by the Security team, and it likely would only be "Private Security" marked if the bug was legitimately a security risk that they could not publicize the information for.
There can also be private bugs that are not against the Ubuntu packages but are against other projects on Launchpad (i.e. not the Ubuntu project or an Ubuntu package).  For those bugs, the managers of that project will be setting forth the policies for those bugs.

Additional information on how to triage Apport crash reports and other private bugs in Ubuntu can be found on the Ubuntu Wiki, in the How to Triage guide, as part of the Bug Squad's knowledge base.  The link will automatically point you to the "Apport reports" section, however for the most up to date information on triage guidelines you should refer to that wiki document.
Comment: @int_ua As far as I am aware there is no specific recommended time period for when you should make a private bug public.
Comment: Nice answer. Bookmarked.
Comment: What is the recommended period after which I should make a bug report public myself? Week? Month?


How to retrieve JSON data inside an JSON object?

Question: I have a JSON Object that looks like this :
"TripList":{
  "noNamespaceSchemaLocation":"http://api.vasttrafik.se/v1/hafasRestTrip.xsd",
  "servertime":"11:27",
  "serverdate":"2013-04-02",
  "Trip":[{
    "Leg":{
      "name":"Spårvagn 3",
      "type":"TRAM",
      "id":"9015014500300079",
      "direction":"Kålltorp",
      "fgColor":"#004b85",
      "bgColor":"#ffffff",
      "stroke":"Solid",
      "accessibility":"wheelChair",
      "Origin":{
        "name":"Brunnsparken, Göteborg",
        "type":"ST",
        "id":"9022014001760004",
        "routeIdx":"19",
        "time":"11:27",
        "date":"2013-04-02",
        "track":"D ",
        "rtTime":"11:31",
        "rtDate":"2013-04-02",
        "$":"\n"
        }

to get the name inside the Leg object is working fine.
But if I wanna get thetime inside the Origin object how do I do that?
My code is like this so far:
    JSONParser parser = new JSONParser();
    Object obj = parser.parse(Planner.getPlanner().getJsonDataForTrip(Planner.getPlanner().getStartLocationID(), Planner.getPlanner().getDestinationID()));
    JSONObject topObject = (JSONObject) obj;
    JSONObject locationList = (JSONObject) topObject.get("TripList");
    JSONArray array = (JSONArray) locationList.get("Trip");
    Iterator<JSONObject> iterator = array.iterator();

    while (iterator.hasNext()) {

        JSONObject jsonObj = iterator.next();
        jsonObj = (JSONObject) jsonObj.get("Leg");
        String line = (String) jsonObj.get("name");
        Planner.getPlanner().setLines(line);
        System.out.println(jsonObj.get("Origin"));
        Long time = (Long) jsonObj.get("time");
        String track =(String) jsonObj.get("track");

        System.out.println(line);
        System.out.println(time);
        System.out.println(track);

    }

}
And in the console it say like this :

{"routeIdx":"19","id":"9022014001760004","rtDate":"20130402","time":"15:02","$":"\n","name:"Brunnsparken, Göteborg","track":"D ","rtTime":"15:06","date":"2013-04-02","type":"ST"}
Spårvagn 3
null
null

So basiclly i am getting the name Spårvang 3 already. But I wanna get the time.
so the time that I am trying to get out by using jsonObj.get("time"); is giving a null value.
Whats the problem and how can I get the time from the object "Origin"??
Comment: "time" is inside "Origin" and not "Leg". Also, **time is not Long**. You need to use SimpleDateFormat to parse it. perhaps you'd like to use "date" to parse it.
Answer: Since "Time" is part of the "Origin"-object, you would need to extract the "Origin"-object first:
JSONOject origin = (JSONObject) jsonObj.get("Origin");

And then:
String time = origin.getString("time");

Answer: You are getting 'time' and 'track' properties of 'Leg' object, not the 'Origin' object..
It should be:
    JSONParser parser = new JSONParser();
    Object obj = parser.parse(Planner.getPlanner().getJsonDataForTrip(Planner.getPlanner().getStartLocationID(), Planner.getPlanner().getDestinationID()));
    JSONObject topObject = (JSONObject) obj;
    JSONObject locationList = (JSONObject) topObject.get("TripList");
    JSONArray array = (JSONArray) locationList.get("Trip");
    Iterator<JSONObject> iterator = array.iterator();

    while (iterator.hasNext()) {

        JSONObject jsonObj = iterator.next();
        jsonObj = (JSONObject) jsonObj.get("Leg");
        String line = (String) jsonObj.get("name");
        Planner.getPlanner().setLines(line);
        System.out.println(jsonObj.get("Origin"));

        // Added this line
        jsonObj = (JSONObject) jsonObj.get("Origin");

        String time = (String) jsonObj.get("time");
        String track =(String) jsonObj.get("track");

        System.out.println(line);
        System.out.println(time);
        System.out.println(track);

    }

Answer: Do following code
JSONOject origin = (JSONObject) jsonObj.get("Origin");
String time = (String) origin.getString("time");

them use SimpleDateFormat to parse time string and get date object


Recurring local notification in iOS - objective c

Question: I have a date picker called timePicker that allows the user to select hour and minutes to receive the notification, and on button click I want to schedule notification at that time for the current day if the time has not yet passed, or for the next day if the time has passed. I then want the notification to repeat every day at the exact same time. I have the first part kind of figured out, but I can't get the repeating to work. The code is legacy, and as such is written in objective c. I would greatly appreciate as much of a code example as you are willing to write for me, but any advice at all would be greatly appreciated. Thank you!!
Comment: Possible duplicate of [Recurring Local Notification in iOS](https://stackoverflow.com/questions/35601515/recurring-local-notification-in-ios)
Comment: that is written in swift, I do not know swift.
Comment: First of all you didn't show any line of code that you are using currently, secondly it's 1 line of code in Swift as an answer in duplicated question - should be easy to figure out how to do it in Obj-c
Comment: @GrzegorzKrukowski You should not mark a question as a duplicate if said question is in an entirely different language, even if the languages are closely related. StackOverflow is meant to be referential in nature, so someone searching for this solution in this specific language may find such. Instead finding a closed question with no answer and a link to an answer in another language is not proper for the intended nature of this site.
Answer: Something like this is what you are likely looking for.
<code>UILocalNotification *notification = [UILocalNotification new];
notification.fireDate = /*Alert Date*/;
notification.repeatInterval = NSCalendarUnitDay;//Once per day
[notification setAlertBody:@"Your message"];
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
</code>
Set the repeatInterval to whatever NSCalendarUnit you'd like.
If you need something more custom just make an iterative loop and change the fireDate accordingly each iteration. (Make sure you unschedule them in the next session if needed).
Comment: Thank you! I really appreciate the answer.


Showing that there is an isomorphism on $\phi(x)=x^{1/3}$

Question: If you have a map from $\left \langle \mathbb{R},*  \right \rangle$ to $\left \langle \mathbb{R},*  \right \rangle$, defined by  $\phi (x)=x^{1/3} $ for all x ∈ $\mathbb{Q}$, how can you show that $\phi$ is an isomorphism of $\left \langle \mathbb{R},*  \right \rangle$ with itself?
My idea is to show one to one, onto, homomorphism.
Homomorprihsm seems simple:
$\phi (x*y)=\phi (x*y)^{^{1/3}}=x^{1/3}*y^{1/3}=\phi (x)*\phi(y)$
Onto seems tricker:
$\phi\sqrt[1/3]{q}=\sqrt[1/3]{q}^{1/3}=q$
and my idea for one to one is the same:
$x_{1},x_{2}$ ∈ $\mathbb{Q}$ such that $\phi(x_{1})=\phi(x_{2})$
= $(x_{1})^{1/3}=(x_{2})^{1/3}=\sqrt[1/3]{x_{1}^{1/3}}=\sqrt[1/3]{x_{2}^{1/3}}=x1=x2$
That seems to be the only approach I can see for one to one.
How is this approach all in all? Or could I do a better job some place?
Comment: $\left \langle \mathbb{R},*  \right \rangle$ is not a group. We need to exclude $0$.
Comment: Additionally, if you dislike roots, you can look at the map $\varphi(x) = x^3$ instead.  Show that it's an isomorphism, then then show that $\phi\circ\varphi(x) = x$, so it's the inverse of $\phi$.  It then follows immediately that $\phi$ is an isomorphism.
Comment: How is $\phi$ defined why $x\not\in\mathbb Q$?
Comment: I think it makes sense as a monoid morphism.
Answer: I'm not sure it is an isomorphism. And your "onto" doesn't make sense. To cancel the $\frac13$ you need you have a cube. This is mapping $\Bbb Q$ to $\Bbb R$ and $\Bbb Q$ is a proper subset of $\Bbb R$. This may work when mapping $\Bbb R$ to $\Bbb Q$ but I am not sure that it works in this situation. I think you need $\phi$ defined so that it encompasses all of $\Bbb R$.


Update Manager failed with "the package catalog has broken" error

Question: I installed Ubuntu 11.10 from a live DVD. Then went for updating through Update Manager. It downloaded everything. During installing them the update manager crashed. It showed the error message:

The package catalog has broken. Installing or removing
  software is not possible until the package catalog is repaired.

However opting for repair didn't work and it continued showing the notification obstinately. I was undone.
Please show me how I can repair it.
@int_ua
apt-get update -f did not work. Problem still persists.
@freecode
dpkg --configure -a did not remove the broken package. Nevertheless, I found details that the problem might be due to some third-party package. Now, how to check whether I am using any third-party package and if so how to disable them?
Comment: Do you get the same result if you run `sudo apt-get update`?
Comment: open your dash and type "software sources" - you can find any third-party ppa's installed there - untick them to disable them.  Rerun `sudo apt-get update && sudo apt-get upgrade` to check if you have resolved your problem.
Comment: @fossfreedomAfter disabling them and running apt-get update && apt-get upgrade I found that the problem is due to unmet dependencies of evolution-data-server : Depends: evolution-data-server-common (= 3.2.2-0ubuntu1~oneiric) but 3.2.0-0ubuntu1 is installed
 libedataserverui-3.0-1 : Depends: evolution-data-server-common (>= 3.2.2) but 3.2.0-0ubuntu1 is installed. But now, how to remove this unmet dependency. Update manager is not allowing removing or installing anything. I do not know how to tackle it in the terminal.
Answer: You can always try going to the command line and trying this command:
sudo dpkg --configure -a

and simply allow the package manager to repair itself. That will usually do the job.
Hope that helps. Have a nice day.
Answer: Had the same problem and solved it:
I ran software-center in a terminal and looking at the error messages, I did:
sudo chmod a+r /var/cache/apt-xapian-index/index.1/*
sudo chmod a+r /var/lib/apt-xapian-index/*

The command
dpkg -l

produced an error mesage, I solved that with
sudo chmod a+r /etc/dpkg/dpkg.cfg.d/multiarch

And now software-center is running as it should.


How can I use a foreach loop to check which elements of an array are equal to a given string?

Question: My foreach loop is not working as I wish it to. I want it to loop through the array and find when one element is present and when the element is not present. However, I get all of them saying Not an apple.
@fruit = ('apple','orange','pear');

foreach(@fruit){
     if(@fruit != 'apple'){
          print "Not an apple\n";
     }
     else{
          print "Is an apple\n";
     }
}

Comment: Always use `use strict; use warnings;`!
Answer: Strings are compared using eq (equal) and ne (not equal). $_ is implicit foreach variable and it should be used like,
if ($_ ne 'apple')

If you want to use explicit loop variable:
foreach my $v (@fruit) {

     if($v ne 'apple'){
          print "Not an apple\n";
     }
     else{
          print "Is an apple\n";
     }
}

Now, why do you get all "Not an apple\n" printed for all elements of @fruit? First, the != results in the left-hand side being evaluated in scalar context which gives the number of elements of @fruit, i.e. 3. On the other hand, 'apple', not being numeric, evaluates to 0 in this numeric comparison for equality. Therefore, the if condition, for each element of the array reduces to:
if (3 != 0) {

and, of course, that holds for every element of the array, regardless of what that array element is.
Answer: Using the modules strict and warnings will help you avoid these mistakes. http://www.perlmonks.org/?node_id=111088
Answer: Let's use a bit more modern way of writing Perl:
use strict;
use warnings;
use feature qw(say);

my @fruits = qw( apple orange pear );
for my $fruit ( @fruits ) {
   if ( $fruit ne 'apple' ) {
      say "$fruit is not an apple";
   }
   else {
      say "This is an apple.";
   }
}

You made several mistakes in your code, and if you had use warnings; in your code, Perl would have told you about them. This is why use warnings should always be included. The use strict forces you to use stricter syntax which means that you can't use barewords (you must quote strings and make sure functions are property declared). And, you have to declare your variables (usually with my).
You had:
foreach (@fruit) {

which means that each fruit would be in the $_ variable, but instead, you were using
if ( @fruit != ... )

In your if statements. That is, you're comparing the entire @fruit array to the value. Also, the != is for numeric comparisons only. You want ne for string comparisons. The use warnings would have caught both of these errors.
Your if statements should have looked like:
if ( $_ ne '...' ) {

However, I don't usually recommend to use $_ for a variety of reasons. It's original purpose was to make the code easier to read, but it usually fails at that. Instead, I usually will use an explicit variable name:
for my $fruit ( @fruits ) {

instead of
foreach (@fruit);

Also note that I use plurals when naming arrays and hashes (since they're usually groups of objects anyway), this way, I don't end up with @fruit, $fruit, and %fruit which can be confusing (although legal). You could add a suffix (i.e. @fruit_list) to help clarify an array from the individual variable too.
I also like using say instead of print because say automatically adds that \n to the end of my printed output. I get the say command when I add in the pragma feature qw(say); to my program.
I also like using qw(...) to define one word lists. It's cleaner and easier to read than using quotes and commas. Note I do not add commas between my fruit names.
Comment: +1 You might want to point out `@fruit` on the LHS of `!=` evaluates to the number of elements in the array.


AttributeError: 'bool' object has no attribute 'accept'

Question: i´m new to using python and PyQt, and i´m making a PyQt project for my university. I´m writing this code:
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4 import uic

class Ventana(QMainWindow):
    def __init__(self):
        super(QMainWindow, self).__init__()
        uic.loadUi("MainVentanaNew.ui", self)
        self.showMaximized()
        self.setMinimumSize(250,200)

#Menubar elements
        self.actionNuevo.setShortcut("Ctrl+n")
        self.actionNuevo.setStatusTip("Crea un nuevo archivo")

        self.actionSalir.setShortcut("Alt+F4")
        self.actionSalir.setStatusTip("Cierra la aplicación")
        self.actionSalir.triggered.connect(self.closeEvent)

    def closeEvent(self, event):
        self.statusBar().showMessage("Saliendo de la aplicación")
        preguntar = QMessageBox.question(self, "Salir...",
        "¿Seguro desea salir", QMessageBox.Yes | QMessageBox.No)
        if preguntar == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()

app = QApplication(sys.argv)
window = Ventana()
window.show()
sys.exit(app.exec_())

The indentation in my code is correct, maybe i made some mistakes copying it in here, but it´s ok. So, my problem is that when i build it, it throws me this error:
"AttributeError: 'bool' object has no attribute 'accept' ",
when i want to close the main window using the menubar's element "self.actionSalir". But,when i close it in any other way, it works.
What can i do to accomplish this? I mean, closing the mainwindow using the menubar's element?
Thanks for your time and your answers.
Comment: `self.actionSalir.triggered.connect(self.close)`.
Comment: @ekhumoro: why didn't you put this in an answer? That way the question can be marked as *answered* and shows up that way in the overview. I realize it might a small remark for you but it's a proper answer nevertheless.
Comment: @titusjan. It's a minor fix that is unlikely to help other users - the question should probably be closed (no pun intended).
Comment: @ekhumoro sorry to disagree, but a "minor fix" like this can help users that starts with python and/or pyqt like me, or maybe anothers who can´t see the solution because, i don´t know, their code is too long and it´s dificult to see. Don´t misunderstand me, i´m telling you this in the best way, as a grateful user. Thnak you again for your answer, it helped me a lot.
Answer: self.actionSalir.triggered.connect(self.close)

Works pretty well for me.


Garage door opens abruptly

Question: My garage door opens very abruptly and it's only a year old. Does it need oil or wd-40 and where?
Everything shakes like it's going to fall off the ceiling or come off rails.
Brand: Chamberlin
Lift master pro
1/3 hp
Comment: Have you checked the rollers and the axles they rest on? Have you disengaged the opener and tried opening it manually?
Comment: What would I be checking for when I manually roll the door up and down
Comment: You want to rule out the door opener as the source of the shaking. Also, what kind of door is this? I assumed it was a track and roller, but I forgot it could be a cantilevered outward swing door as well.
Comment: Track and roller is correct
Comment: You want to see if the door works.  If it rolls easily without the opener, the problem is the opener.  If it has problems without the opener, the opener is just forcing a damaged door, which will eventually make the door tear itself apart and potentially maim someone.
Answer: From my research for that particular model, I can see that it's a chain drive lifting system. If this is incorrect, please advise. The videos I've seen show a centrally located coaxial spring acting on a rod over the width of the door. Not visible in the video would be a set of spools with cables lifting the door from the edges/ends.
Machavity would be suggesting to disengage the lift mechanism by pulling on the red handle. The door springs should be powerful enough to allow you to lift the garage door manually, as when the power goes out and you want to leave anyway, or maybe return home, or just mow the lawn.
If you are unable to lift the door, examine the spools/pulleys at each end to ensure the cables are not wrapped over previous layers causing excessive friction and possibly wear.
Examine also the spring for breaks or slippage. Some people recommending using a spray lubricant on springs of this type. I'm not sure if the reasoning is to reduce friction, prevent rust, or both.
If you are able to easily lift the door, make note of the rollers in the tracks. They should move freely as well. Lubrication on the axles of the rollers is a good idea. Lubrication of the wheels in the tracks is not particularly effective, although it may quiet the roller noise by an insignificant amount.
If you have spring or pulley problems, the drive mechanism may be taking on a greater load than design allows. If the internal gearing is plastic (which is likely), the gears can slip, wear and occasionally have broken teeth. Manually lifting the door will bypass such failures.
With the door in the down position, with the red handle disengaged, actuate the opener and listen for slipping or skipping gears. Reverse direction once it reaches the open position until it locks into the red handle. It may be necessary to lift the door somewhat to make the red handle click into place.
A big part of repairing a problem of this sort is to isolate the source. The above steps may provide you the key information to solving the problem.

Garage door opens abruptly


sizeof union in C

Question: The sizeof a union is equal to the size of the largest member in it. But in the following union, the size is being shown to be 8 Bytes. Size of int and float is 4 Bytes. Why does it show 8 Bytes?
union data {
    int i;
    float f;
    char *str;
};

Comment: I have X, Y and Z. This is causing W. I've checked X, Y and they are not the cause of W. What could cause W?
Comment: Maybe try printing the `sizeof` each of the elements separately as one of them is obviously 8 bytes
Comment: If `int` and `float` are 4 bytes wide on your system, but the size of your union is 8 bytes wide, then it's pretty clear that on your system `char *` is 8 bytes wide.
Comment: *Size of int and float is 4 Bytes.* How did you determine this? And what about the `char *`?
Comment: `char * str` has 8 bytes length in 64 bits CPU.
Comment: @SergioFormiggini It has a pretty loose relation to the CPU bitness.
Comment: What kind of machine architecture and compiler are you using
Comment: minus for unbelievable laziness.  You wrote this silly post, wasted our time and you did not check what your pointer size is.
Comment: Did you check the size of the char*? It could be the cause.
Comment: Also consider the alignment problem! Try using __packed
Comment: @JonnySchubert Its `union`, not a `struct`.  How would packing affect a `union`?
Comment: @EugeneSh. On my I3 with Linux 64 the pointers are 8 byte length. On the other hand is very easy to verify what the compiler generates. I'm sure that the result is due to the pointer length!
Comment: All three `i`, `f`, and `str` are members of `union data`.
Comment: @SergioFormiggini What is happening is not related to what *might* happen. Moreover, sizes to different types *on the same machine* are not guaranteed to be the same size. https://stackoverflow.com/questions/1241205/are-all-data-pointers-the-same-size-in-one-platform-for-all-data-types
Comment: @Eugene Sh. Another useless discussion. Ridiculous topic .Graet companion
Comment: @EugeneSh. It was long ago I saw such a burning sarcasm! :D
Answer: sizeof(char *) is the size of the pointer.
It's usually 4 for 32-bit machine, and 8 for 64-bit machine.
Given your result, I take it you're on a 64-bit machine.
Answer: #include <stdio.h>

union data_t {
  int i;
  float f;
  char *str;
};

int main()
{
  union data_t data;
  printf("%zu\n%zu\n%zu\n", sizeof (data.i), sizeof (data.f), sizeof (data.str));
  printf("\nsizeof(char*): %zu\nsizeof(char): %zu\n", sizeof(char *), sizeof(char));
}

Output:
$ ./a.out
4
4
8

sizeof(char*): 8
sizeof(char): 1

Comment: @chux Fixed it.
Answer: Size of union = size of the largest data type used
The memory occupied by a union will be large enough to hold the largest member of the union. It doesn't matter what is currently in use. For example,
union Data
 {
   int i;
   float f;
   char str[20];
 } data;

Now, a variable of Data type can store an integer, a floating-point number, or a string of characters. It means a single variable, i.e., same memory location, can be used to store multiple types of data. Data type will occupy 20 bytes of memory space because this is the maximum space which can be occupied by a character string.
Answer: Try the code below on a Windows 64/Linux 64 and the result should be 8, on a 32 bit system should be 4.
int main(void)
{
    char * str;

    printf("%d\n",sizeof(str));

    return 0;

}

sizeof union in C


Does anybody know why i'm getting "error: class, interface, or enum expected"?

Question: i'm making a simple class in JCreator and i'm not sure why i'm getting the "error: class interface, or enum expected". This is my code:
    public int class javatest
    {

        public javatest()
        {
            double coin=168.22;
            int quarter=0;
            int dime=0;
            int nickel=0;
            if (coin>.25)
            {
            coin-=.25;
            quarter++;
            return coin;
            }
        }
     }

Comment: You have an illegal token before the `class` keyword. Remove `int`
Answer: Change
public int class javatest {....
to
public class javatest {


Do achievements work for Netflix?

Question: (I don't know if this is an off topic question since this isn't about a game but
I don't know where to go to ask this)
So I've done most of the achievements for Netflix on Xbox but I haven't gotten any. I've watched much more than 10 episodes in a row but I haven't gotten that achievement yet. Is there a way to get the achievements or do they just not work?
Comment: _Netflix_ had achievements. _Netflix._ Someday, my grandchildren will ask me what life was like in the late 20-teens and I will not know what to tell them.
Answer: From what I can gather from the True Achievements forums, the Netflix achievements may have been discontinued back around August 2017.
https://www.trueachievements.com/forum/viewthread.aspx?tid=823659
Comment: Killing off achievements is clearly a sin in gamer-world.  It isn't clear whether this was caused by MS or Netflix.

Do achievements work for Netflix?


CSS boxes problems

Question: I've created this box model and I want three more same boxes in column.
The CSS:
#box {

}

#box .circle
{
    width:120px;
    height:120px;
    border-radius:50%;
    font-size:2em;
    color:#fff;
    line-height:120px;
    text-align:center;
    background-color:yellow;
    left:75px;
    top:95px;
    position: relative;
    z-index: 1;
}

#box .box1 {
    -webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
    -moz-box-sizing: border-box;    /* Firefox, other Gecko */
    box-sizing: border-box;         /* Opera/IE 8+ */
    width:270px;
    height:130px;
    top:160px;
    left:1px;
    background-color:black;
    padding:70px 40px 15px 40px;
    position:absolute;
}

#box .box2 {
    -webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
    -moz-box-sizing: border-box;    /* Firefox, other Gecko */
    box-sizing: border-box;         /* Opera/IE 8+ */

    width:270px;
    height:250px;
    top:280;
    left:1px;
    background-color:blue;
    padding:70px 40px 15px 40px;
    position:absolute;
}

#box .box3 {
    -webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
    -moz-box-sizing: border-box;    /* Firefox, other Gecko */
    box-sizing: border-box;         /* Opera/IE 8+ */

    width:270px;
    height:70px;
    top:530px;
    left:1px;
    background-color:black;
    padding:70px 40px 15px 40px;
    position:absolute;
}

And the markup:

10GB

    </form>

Comment: _"I want three more same boxes in column"_ Explain.
Comment: That's not an explanation, that's just repeating what you already said; and people didn't understand you the first time.
Comment: where is your `` ?
Comment: mate can you post a http://jsfiddle.net/ with your code?
Comment: say more, what exactly you need ?
Comment: I wanna three same form boxes :(

like this http://s17.postimg.org/tkwx45ohb/bbbb.png
Answer: Avoid absolute positions for main layout elements as boxes, wrappers, etc. The solution for you shoul be learn how to float elements correctly.
First read about the CSS float property and clearfix and after that this demo should be easy a nice template to work on.
Comment: I've small time. if you help me it will be great :(
Comment: Then just use the [demo](http://andrestorres.com.ar/junk/clearfix.html) as a template. Reduce the `width` of `.box` so you can place more than 2 boxes as colums.
Answer: First of all;

You shouldn't use "position:absolute" as you can.
Use "float:left" for combining vertical aligned elements.
Use a "clearfix" solution (like http://www.webtoolkit.info/css-clearfix.html) for clearing "float:left" overflowing.

Here is the solution:

        <form class="clearfix" action="#">

10GB

10GB

10GB

        </form>

Comment: The one thing i dont like about your answer is using floats. i would use Display: inline-block. Its way better imo.

CSS boxes problems


Help! Condensate pump is so loud and working when minisplit is off

Question: Help! New homeowner here. We have a carrier minisplit in our bedroom, which works well. We live in a rowhouse (so two brick walls on the side), so a condensate pump is used to pump water onto the roof and to the back of the house. The problem is that the pump makes a loud buzzing sound every 1-2 minutes. Is that frequency normal?
The annoying part is that it does this even when the unit is turned off. I'm very new to this HVAC stuff but after doing some research, it seems like there's an issue with the float switch. What should I do? Get a new pump? The HVAC tech didn't seem like could help with this but I'm pretty useless with this level of DIY. I can't sleep with it buzzing constantly -- help!
Comment: Thanks, Ed! The minisplit filters are clean but I don't think anyone has cleaned the pump for awhile. I don't know how to do that. The pump is in a little white box-type thing (see? I'm very clueless with this stuff) and screwed shut. Should I open it up to take a look? Should I get a new pump?
Answer: I can see the pump turning on a couple of times after being in cooling mode but it should not have a lot of water to pump once the unit warms up.
if the pump is pushing water I would be concerned about the amount of ice in the head.
Is the filter being cleaned low air flow can cause icing.
Don't run the ac when the outside temps are below 65F this can cause icing.
If there is ice on the evaporator coil it may take several hours to melt and your pump is doing it's job.
I would be concerned about that much ice, floats usually stick closed and won't turn off or fail to close and turn the pump on.
I have not seen a float cycle unless it has to lift the water and then a long horizontal run. What happens in some cases the water is syphoned back into the pump.
A simple check valve close to the pump is needed in this case this theory is easy to check by watching the water level in the pump tray.
Comment: With the mini split off , no water in the drip pan that drains to the pump, add just enough water to get it to turn on. If it pumps out turns off then 1-2 minutes later turns on it is probably sucking the water back in the pipe and this could continue for hours, is hard on the pump and your sleep. A simple check valve will prevent this from happening.
Comment: Erin thanks are ok but on this site clicking on an up arrow or giving an answer a check mark shows others that have a similar issue this answer was helpful or accepted.


Wrong Universal time on my Ubuntu server

Question: On Ubuntu server the time is wrong:
Time from Google:
UTC: Wednesday, May 18, 2016 5:31 AM (UTC)
Asia\Riyadh: Wednesday, May 18, 2016 8:31 AM (GMT+3)
Time on my server timedatectl:
      Local time: Wed 2016-05-18 11:27:27 AST
  Universal time: Wed 2016-05-18 08:27:27 UTC
        RTC time: Wed 2016-05-18 08:27:27
       Time zone: Asia/Riyadh (AST, +0300)
 Network time on: yes
NTP synchronized: no
 RTC in local TZ: no

Note: I am not dual booting with Windows. Ubuntu Server is the only OS on my server.
Comment: Is your computer a dual-boot computer?  For example, Ubuntu and Windows?  If so, take a look at this:  https://help.ubuntu.com/community/UbuntuTime .  Scroll down to "Multiple Boot Systems Time Conflicts".  A similar question on this site (with the same site as the answer):  http://askubuntu.com/questions/169376/clock-time-is-off-on-dual-boot .
Answer: Install the network time protocol daemon. This will allow you to sync your system time over the internet.
sudo apt install ntp ntpdate

Once installed, run the following command:
ntpdate pool.ntp.org

This will link your computer with the time servers of the NTP Pool Project. For me my clocks fixed themselves quickly after running the command. And that was it.
After running the following command and setting the system clock, run:
hwclock --systohc

Comment: Simply installing ntp and let the service run should be enoough from my point of view. Forget about pacman - that was a false advice by User123
Comment: The program 'ntpdate' is currently not installed.
Comment: The program 'pacman' is currently not installed.
Comment: I fixed the commands in the post of User123 - please re-try now
Comment: Is there a solution other than installing `pacman` and the deprecated `ntpdate`?
Comment: After running commands and then restarting, it solved my Ubuntu 16.04 UTC time
Comment: just minor: the two `ntpdate` and `hwclock` commands need `sudo`


Is there a Kotlin-Multiplatform feature or pattern that can help to implement a common abstraction for, say, the Closeable interface?

Question: The Closeable interface in Java provides a convenient abstraction that facilitates the management of resources that can be closed. In the context of multi-platform kotlin, is there a pattern, practice or feature that can help breach the gap between a shared/multi-platform Closeable interface and the actual Java Closeable interface knowing that these are necessarily two different types?
The effects of not being able to close the type difference and/or having a standard-lib closeable are the proliferation of Closeable interfaces that can't be combined across libraries even though they are fundamentally the same thing.
Answer: This is already done for you in kotlinx-io library from the Kotlin team.
https://github.com/Kotlin/kotlinx-io
For Closeable you should use that library directly, no need to create your own.

But if you want to create your own similar cross-platform abstraction, this acts as a nice sample. Here is what it is doing underneath the covers...
The common implementation which actually does the logic of closing and just expects each platform to have the interface available: (source)
expect interface Closeable {
    fun close()
}

inline fun <C : Closeable, R> C.use(block: (C) -> R): R {
    try {
        val result = block(this)
        close()
        return result
    } catch (first: Throwable) {
        try {
            close()
        } catch (second: Throwable) {
            first.addSuppressedInternal(second)
        }
        throw first
    }
}

@PublishedApi
internal expect fun Throwable.addSuppressedInternal(other: Throwable)

The JVM version is just a simple type alias that matches the expected interface meaning that it is compatible with existing code, and implementation of suppressing the inner exception. (source)
actual typealias Closeable = java.io.Closeable

@PublishedApi
internal actual fun Throwable.addSuppressedInternal(other: Throwable) {
    AddSuppressedMethod?.invoke(this, other)
}

private val AddSuppressedMethod: Method? by lazy {
    try {
        Throwable::class.java.getMethod("addSuppressed", Throwable::class.java)
    } catch (t: Throwable) {
        null
    }
}

And the JS version is a new interface: (source)
actual interface Closeable {
    actual fun close()
}

@PublishedApi
internal actual fun Throwable.addSuppressedInternal(other: Throwable) {
}

For native it is similar to JS, and so on for each platform...
Comment: Thank you this is the common denominator I was looking for. Is there an analogous thing for the rx Observable interface to bridge reactive streams across platforms? This would allow declaring a multi-platform Observable interface that can be bound to the corresponding platform implementation (e.g. rxjava, rxswift, etc).
Comment: That is more complex, but you could do the same, although you can't abstract Swift under Kotlin because the interoperability is the other way around.  You would need a custom implementation in kotlin-native to use from Swift which would be a lot of work.  Many people are using coroutines instead of rxwhatever these days anyways.
Comment: I was about to ask for some rationale to `expect` different `actual` implementation of interfaces and your answer just brought up a strong example.


IE 10-11 flex-basis property behaves differently than webkit browsers

Question: I'm trying to use the Media object, consisting of a Media-body and a Media-figure. The HTML and classes follow this form (order shouldn't matter).
.Media
   .Media-figure
   .Media-body

The simple CSS is (no prefixes):
.Media {
   display: flex
}

.Media-figure {
   flex: 0 0 auto;

   /* same as...
   flex-grow: 0;
   flex-shrink: 0;
   flex-basis: auto;
   */
}

.Media-body {
   flex: 1 1 0;

   /* same as...
   flex-grow: 1;
   flex-shrink: 1;
   flex-basis: 0;
   */
}

Notice that I'm tweaking the Media-figure flex-shrink factor to be 0 (as opposed to the link I posted). I'm assuming that the Media-figure is some fixed size, and we'd rather not make it smaller if we have too little room.
Using flex-basis: 0 for the Media-body should set the element to have no initial size, which then allows it to consume the rest of the available space since it is the only element with flex-grow: 1. However, in IE10-11, the flex-basis: 0 causes the Media-body width to be that of the interior elements, and destroys any wrapping behavior if there is too much content.
http://jsfiddle.net/sgardn04/3enpp4wg/
(Note: if you view these in chrome, they'll look exactly the same. Use IE10-11!)
My current workaround is to set the Media-body { flex-basis: auto }, which seems to work. I make the assumption that IE is at fault here, since I like the behavior of the webkit browsers better. Is there a legitimate interpretation of the spec that supports IEs rendering? Or any case where we could expect different behavior for webkit browsers based on the classes I have defined here? The two properties seem to behave exactly the same in this case.
EDIT: I found this handy graphic, which seems to suggest that the flex-basis property determines whether the space is distributed before or after the width of the elements is taken into account (flex-basis: 0 vs flex-basis: auto).
Answer: The difference is due to not having a unit on the value of flex-basis. Adding this (or omitting the 0) gives you the expected behaviour in IE: updated fiddle
The MDN documentation on flex mentions this:

A preferred size of 0 must have a unit
  to avoid being interpreted as a flexibility. Defaults to 0% when
  omitted.
Comment: I've been reading through the documentation and have come to the same conclusion. Microsoft refer to "Width as specified by a number, **followed by a length unit**." in their MSDN documentation, and MDN state "Defined as a number **followed by a absolute unit** such as px, mm or pt, or a percentage of the parent flex container main size property"
Comment: MSDN also state for the flex property "You need to specify a zero flex-basis component with a unit or precede it by two flex factors to avoid misinterpretation or invalid declarations." - although with the flex-grow and flex-shrink the original code should be valid based on that statement. The specification concurs with MSDN and states "A unitless zero that is not already preceded by two flex factors must be interpreted as a flex factor. To avoid misinterpretation or invalid declarations, authors must specify a zero 'flex-basis' component with a unit or precede it by two flex factors."


What is best way to create .NET6 class with many non-nullable properties?

Question: I trying to create class with some number of non-nulable properties (>7).
If I do like this:
public class Meeting
{

    public Name Name { get; set; }
    public Person ResponsiblePerson { get; set; }
    public Description Description {get; set; }
    public Category Category { get; set; }
    public Type Type { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
    public List<Person> Attendees { get; set; }

    public Meeting()
    {
        Attendees = new List<Person>();
    }
}

I get warnings like this:
"Non-nullable property '...' must contain a non-null value when exiting constructor. Consider declaring the property as nullable."
There is a list of variants I thinked of:

Default values removes this warning, but I think, that it will just add useless values, that in the future will be needed to be changed anyway.

If I init all properties in constructor this warning gets away, but then constructor will have >7 params which is nightmare.

I have seen that some people use "Builder" pattern to init classes with many params. But the builder itself can't prevent 'null' values (The builder will get same warnings).

There is easy way to remove warning, by making nullable property in .csproj file from true to false, but I don't want to just remove that warning. I want to make class itself safe from null values.

Whats clean way create that class?
Comment: So, is the idea that whoever instantiates that class will initialise each and every one of those properties?
Comment: What problem are you trying to solve?
Comment: If the properties cannot be null then you either must initialise them with default non-null values, or require non-null values to be passed to the constructor and set the properties there. Anything else will allow the object to contain null properties after construction.
Comment: If you're certain that the person who instantiates that object will assign all of those properties, you can forcefully initialize them to null, with `{ get; set; } = null!;` (or wait for required properties in C# 11)
Comment: Does this answer your question? [Non-nullable property must contain a non-null value when exiting constructor. Consider declaring the property as nullable](https://stackoverflow.com/questions/67505347/non-nullable-property-must-contain-a-non-null-value-when-exiting-constructor-co)
Comment: @canton7 Kinda yes, kinda no. At the initialization class can be half empty, but I need to be sure that before serialization (Or smth else) that every property will eventually have these values
Comment: @Yoro Currently, the only way to ensure that all properties are non-null when the object is instantiated is to use a constructor. `required` properties are coming in C# 11, which will improve this.
Comment: @canton7 can you give a link where I can read of future *required*? That's interesting.
Comment: @Yoro https://github.com/dotnet/csharplang/issues/3630
Comment: *Whats clean way create that class?* - use a record?
Comment: @canton7 Looks cool. I found this with good examples https://exceptionnotfound.net/bite-size-csharp-11-required-properties/
That would be perfect solution.
Comment: [See here for Roslyn language feature status](https://github.com/dotnet/roslyn/blob/main/docs/Language%20Feature%20Status.md) - The item you're looking for is "Required Members" in the table.
Comment: @CaiusJard If I understood correctly, editing a *record class* properties after init is impossible without creating new one. I need ability to edit.
Comment: records are immutable by default, but they don't have to be
Comment: Right, but if you have a mutable record, you can't make use of primary constructors, which means OP isn't gaining anything here
Answer: Since C#11 you can add a Required modifier.
public class Meeting
{
    public required Name Name { get; set; }
    public required Person ResponsiblePerson { get; set; }
    public required Description Description {get; set; }
    public required Category Category { get; set; }
    public required Type Type { get; set; }
    public required DateTime StartDate { get; set; }
    public required DateTime EndDate { get; set; }
    public List<Person> Attendees { get; set; } = new List<Person>();
}

This feature aims to improve how we initialize objects that do not rely on constructor parameters.
More detailed info:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/required
Comment: > Required members must be initialized, but they may be initialized to null.

So with `required` you can't escape someone setting a null value and get the same warning there as the property was meant to be non-nullable
Answer: The whole point of non-nullable is to initialize class instances in a "valid" state.
If Meeting is part of a domain, having some logic inside, you can't initialize Meeting without initial values. I.e., new Meeting() doesn't make any sense.
On the other hand, if Meeting is a so-called data transfer object and it may be initialized partially, if not even empty, then setters are fine, and you don't need a constructor.
Comment: So as I understand the best practice is to configure "non-nullable" warnings to ignore DTO's directory?
Comment: No, it would beat the purpose. I wouldn't go for warning suppression. Instead of that you should explicitly declare property as nullable. See @GazTheDestroyer comment at your question.


Why is the home directory created larger than the root directory?

Question: I've just installed Ubuntu recently, and according to suggestions online, I created my home directory much larger than the root directory. However, I found that the system automatically installs software in the root directory, which takes up a lot of space, and my home directory is almost empty.
I'm a bit confused why it is actually created larger. Should software be installed in the home directory instead? And where should I put the folders of prebuilt binaries downloaded from other sources?
Comment: 25Gb for / is more than enough unless you intend to use it as  server.
Comment: @Rinzwind: Depends… if you install a bunch of games in `/opt` or `/usr/local` or even in `/usr` (think 0 A.D. from the repositories) you can fill 20 GB very quickly.
Comment: Could you please tell us to to which suggestion(s) you're referring in your question? They seem sensible for the majority of Linux desktop systems (see above) but they may be wrong or you may have misunderstood something and it would help to see where this disparity between expectation and reality comes from. In any case you can always resize or even merge file systems and partitions.
Answer: Before directly answering your question, it's important to be clear on the distinction between a directory and a partition. A single partition can hold multiple directories. In Linux, partitions that hold filesystems are normally mounted (made accessible) using a directory as a mount point. Thus, /home could be simply a directory on the root (/) partition or /home could be the mount point for a separate partition. Your question uses the word "directory" in a context that makes it clear you meant "partition." I'm clarifying this distinction because this distinction is important to part of the answer to your question. In fact, there's yet another complication, because logical volume manager (LVM) enables a partition to hold multiple filesystems that are mounted at different places. For the below, though, I'll assume you're not using LVM, so that "partition" and "filesystem" can be considered synonymous (except for the swap partition).
The optimum sizes of various partitions depends on what you expect to install to them. For instance, with separate root (/), /home, and swap partitions, but no other (Ubuntu) partitions:

If you install a lot of software, you'll want a larger root (/) than if you install little software. Even so, the demands of software packages seldom exceed about 30 GB.
Some non-software goes in root (/). This category includes log files, databases (which normally go in /var), content for Web servers, and the system-wide temporary directory (/tmp). If you have big needs for any of these things, you may need either a bigger root (/) partition or to split off the location of these big directories to their own partitions. You might split off /var, or a subdirectory of it, to its own partition if you expect to be storing huge files there, as might be true on some types of network servers. Such non-software demands on root (/) are typically modest for desktop systems, but they can be significant for network servers.
For a typical desktop computer, the space consumed on root (/) won't go up very much over time, because personal files don't go there -- just program binaries, log files (which get rotated out and deleted in time), and other system files. Root (/) consumption goes up mainly because you install new software. If you install a program and then discover you're not using it, uninstalling it can be worthwhile, particularly if root (/) is filling up.
The /home directory is where the vast majority of user files reside. (Some temporary files go in /tmp and there are some other exceptions, though, at least one of which is very important -- see the next bullet point.) On an Ubuntu-only installation, this means that your personal photos, MP3 files, videos, word processing documents, Web browsing cache, etc., all reside in /home. Thus, the space demands on /home tend to go up over time as you use the computer -- you copy photos from your digital camera here, add music here, save word processing documents here, and so on.
One complication is that many Ubuntu installations are to computers that dual-boot with Windows. On these systems, most user data files reside on the Windows C: partition, not in the Ubuntu /home partition. If you continue with this pattern, the /home partition will hold relatively few files and so should probably be smaller than the root (/) partition; or it could be eliminated entirely, leaving the /home directory on the root (/) partition.

Thus, if Ubuntu is your only OS, and if you're installing on a modern hard disk or even SSD (200GB or more, and often in excess of 1TB), chances are /home should be much bigger than root (/).
OTOH, if your disk is unusually small by modern standards or if you're dual-booting with Windows and you want to keep most of your files (especially big ones) accessible to both OSes, it's probably best to either omit a separate /home partition (leaving its files in the root [/] partition as a simple /home directory) or keep a relatively small /home partition -- perhaps even smaller than root (/).
One further variant is worth mentioning: In a dual-boot configuration, experts often prefer setting aside one or more separate partitions to hold files shared between the OSes. That is, you'll have the Ubuntu root (/) and perhaps /home partitions, the Windows C: partition to hold Windows and its program files, and another partition (perhaps D: in Windows and /home/{yourusername}/shared in Ubuntu) to hold shared files. The advantage of this is that you can restrict access to the Windows C: partition from Linux, making it less likely that a bug or user error will trash the Windows installation. You'll also be able to do a full re-install of Windows without wiping the shared-data partition. You can use any filesystem you like on the shared-data partition, so long as both OSes understand it. NTFS is the most common choice for this, but you can use FAT if you don't mind its limitations; and some Linux filesystems have Windows drivers, so you could use one of them if you prefer.
With those generalities out of the way, it's helpful to consider some real sizes:

root (/) -- Ubuntu can install to a root (/) partition as small as about 5 GB, IIRC; however, if you start installing big programs, it can easily climb to two or three times that value. Thus, the usual recommended range is something like 10-30 GB, with the caveat that it can go even higher than that for some users -- but for the majority of "normal" users, even 20 GB is probably adequate if you have a separate /home partition.
swap -- I haven't mentioned swap much, but will for this question of sizing. In the old days (~15 years ago), the general recommendation was to make swap space about twice your RAM size. Today that's usually overkill. If you use suspend-to-disk (which is not configured in Ubuntu by default), swap space should be at least as big as your available RAM. If you don't use this feature, it can be smaller than that, but having some swap space is desirable, because it enables the kernel to optimize RAM use to improve performance. Note also that swap space can be a file on a filesystem rather than (or in addition to) a swap partition. (IIRC, suspend-to-disk requires a swap partition, though.) Overall, in most cases I'd say half your RAM size is probably a decent size for a swap partition.
/home -- As a first approximation, once you've figured out how much space you need for root (/) and swap, you should give everything else to /home. The exception would be if there's very little space left. For instance, if you're dual-booting with Windows and want to give Linux just 30 GB, then you'll have next to nothing left over by the time you allocate, say, 20 GB to root (/) and 4 GB to swap. Something similar would happen if you're installing on a tiny tablet or very old computer with a small disk. In this case, you might as well omit /home.
Other partitions -- In some cases, you might want other partitions for /var, /tmp, and so on. These aren't needed for typical desktop configurations, though. Smallish (~500 MB) /boot and/or /boot/efi partitions are sometimes required, too -- but if you don't already have these and your system is booting, don't worry about them. As noted earlier, you might want a shared-data partition for use with Windows. If you want most of your data to be shared in this way, you might omit /home and allocate the space to a shared-data partition. (You should not mount an NTFS or FAT volume at /home because Ubuntu relies on features not provided by these filesystems for some files in your home directory. You could mount a shared-data partition in a subdirectory of your home directory, though. If you use Windows filesystem drivers for Linux filesystems, you could also give Windows access to your Ubuntu /home partition.)

In the end, designing an optimized partitioning system depends on an intimate knowledge of your own needs, available disk space, and what's already been used (by another OS, for instance). If you stick with Ubuntu, you'll eventually figure this out for yourself; but there is no one-size-fits-all solution, so I can't simply give you a set of numbers. Even generalities like whether /home should be bigger or smaller than root (/) vary from one installation to another -- although if /home is smaller than root (/) when you follow my outline above, there's a good chance (but not a certainty) that omitting /home and increasing the size of root (/) by that amount would be best.
Answer: Software in current Linux distros tend to be really small. The reason is because the way software is packaged (using apt or rpm), all softwares shares a lot of common components.
It's different then OSX or Windows, where every software will install all the required libraries.
And today, a lot of game managers (like Steam) and development libraries (like RVM) will store data and libraries in your home folder. Additionally, probably you'll have high quality movies (around 5 GB), pictures (really big from current mobiles) and music.
I have a 1 TB hard drive. I manually partitioned: just 100 GB are for root, with just 14,0% used. In the other side (excluding swap), everything is the home folder, which is 79% full.
Additional note: The downside of this software package management is it'll require a bit more work from who is creating the installer, as some investigation about which library is used by your distro, and exact version. To mimic the way of OSX and Windows (i.e., provide the full library stack required by the app), some Linux companies (like Canonical and Red Hat) had created new software managers, like flatpack and snaps), with some advantages, like being able to be installed in different distros, use a sandboxed environment, etc.
Answer: How large the / (root) file system on your system is compared to the one backing /home depends largely how you (intend to) use the two. Let's look at some alternatives below.
1 Most common Linux desktop use case
The vast majority of people using Ubuntu install the base system plus a handful of applications (of non-trivial space requirements), e. g. for web browsing, media playback, office productivity, graphics editing, or software development, and store their personal user data in /home, e. g. documents, images/photos, music, or videos.
The space requirement of the former (Ubuntu itself) is easily satisfied with 20–30 gigabytes while the latter (user data) can quickly pile up, especially for multi-media content, to the range of terabytes these days.
As an example, on my system I have:
$ df -h /home ~/medien
Filesystem          Size  Used Avail Use% Mounted on
/dev/sda9           500G  264G  218G  55% /home
/dev/mapper/media   1,4T  1,1T  304G  78% /home/david/media

2 Gaming desktop
Games change things quite a bit because major titles often take multiple gigabytes or even tens of gigabytes1.
On Linux games are typically installed in one of the following locations:

/opt and /usr/local when installed via "custom" installers,
/usr when installed from a package repository2,
$HOME/.local/share/Steam/SteamApps when install via Steam to the default installation path, or
$HOME/.wine or ~/.PlayOnLinux/wineprefix for Windows games installed via Wine or its front-end PlayOnLinux.

Depending on this a Linux gamer may have different space requirements than in the above case 1.
What else?
If your use case deviates significantly from the above then you will most likely have different amounts of data in different areas of the directory tree which means different size requirements if you use more than one file system for your Ubuntu installation.
One other use I see more frequently these days is what Google's Chromebooks are geared to do: beyond a base system there is little more than a web browser and maybe a text editor, image viewer and media playback application on the system while everything else, user data as well as other applications, is stored online and accessed through the web browser.

1 On Linux that is; recent Windows titles are an order of magnitude ahead of that.
2 There aren't many spacious game titles distributed that way. The only large title I can think of is 0 A. D. clocking in at ~1.5 GB.


How do I seal off a small closet so smells there don't escape?

Question: I've got a small pocket closet in a study right next to where I work that is actually a partition of a hall coset in an adjacent building entrance, and therefore not well isolated from it. Recently someone using the adjacent entrance piled some clothing for a few days in the hall closet that appears to have been exposed to mothballs, and the smell lingers. I don't really need my bit of the closet and would like to seal it off so that the mothball smell doesn't get through. I'm a renter (and not handy, and can't have a crew over under current circumstances) so I can't do anything permanent or complicated.
How do I seal off a small closet temporarily with so that the smells there don't leak into the adjacent space? Perhaps there's something I can tape around the opening (a few layers of some airtight material perhaps)?
Comment: Why not tape aluminum foil over the adjacent wall? It will still take a few days for the smell to completely dissipate, though.
Comment: @DrMoishePippik: I only have access to the closet on my side, not the neighboring entry (and I'd like to be discreet: I think the person who caused the smell is a bit embarrassed by it all and want's to avoid the topic).
Answer: I would get some painters plastic it is thin plastic and it will block smells, I use non bleeding (blue masking tape) to hold it in place so it can be removed without leaving the adhesive residue. Cheap and easy to install , easy to remove.
Comment: That would be a second question but they do make small "make up air" fans that are pressure based they keep a small positive pressure in your house to keep smelly neighbors odor with a common wall from invading your space. The problem is these are designed to be mounted in a wall with a hole cut to the outside the fan keeps the house at a slight pressure based on the setting except when doors or windows are opened They are quiet and some have options for filters to filter the outside air I don't know of any a renter would use but one may be able to set something like this up in a window.
Comment: Are there choices of materials from which the painters plastic is made? I want to be sure to get one that's not going to also be off gassing into the confined space of the study.
Comment: All plastics off gas's to some extent, when purchasing open the bag it comes in and sniff if a strong Oder it's probably not the right type for you.
Comment: So are there products that don't have a strong odor?
Comment: To me they all are fine if anything the "new car smell" when you first open the bag but I have never noticed it later but that may be because the paint is drying. I did use some to seal up the hole in the wall when I removed a fireplace in my current house and I really did not notice any smell
Comment: It's in expensive enough that I can give it a try and save it for another day if it's not suitable for this use. I'll report back on how it goes.
Comment: I think what I really need is [some positive pressure](https://diy.stackexchange.com/a/182309/54011) to make sure the mothball smell doesn't get in to the apartment (it comes in via a few other paths as well). We manage that easily in winter with just a bit of heat, but in summer the apartment sucks air from other apartments. Any thoughts on that would be great!
Comment: So far this is looking good. I still haven't stress tested it under the right kind of conditions, but the plastic off gasses quickly and smell from the mothballs hasn't been as bad. More once we've had the right conditions here.


Configure CloudFront distribution with Origin server for static content only

Question: I have run in to a problem while setting up my CloudFront.
What I want to do is to create a CDN for my images only that are hosted on my own server rather than S3 bucket. So the directory on the server with all the images is at mysite.org/images/ which if accessed directly without the file name should kick 404 error instead of 403. Now the way I need it to be set up is, for example someone accessing a page on my site misite.org/wedding/georgetown.html or misite.org/wedding/london.html all images that are served on those pages should come from location cdn.mysite.org/wedding/images/, which if accessed directly without the file name should serve 403 error.
So what I have done so far that pretty much did not get me anywhere is, I set up cloudfront distribution that points to my origin server mysite.org, but now the entire site is accessible via cdn.mysite.org and mysite.org, which is not really what I was trying to achieve.
Any help or suggestions please
Thanks in advance
Answer: Here is what you need to do,
Create multiple origins,
In the Behaviour enter pattern to,
map, /images/* to  cdn.mysite.org/wedding/images/   for your static resources
while rest of them come from different origin.
Hope it helps.
Comment: Hey Kannaiyan, thanks for your answer, I have tried it this way and mapped /images/* to the origin server, but it did not work, I only get 404 for every request.
Comment: 404 is coming from origin. Make sure you have the right origin pointed to the behaviour.


Index out of range for the list?

Question: '''
marksheet=[]
scorelist=[]
for i in range(0,int(input())):
    name=input()
    score=float(input())
    marksheet.append([name,score])
    scorelist.append(score)
second_marks=sorted(list(dict.fromkeys(score_list)))[1]# @here code is reflecing error that it list index is out of range.

for name,marks in sorted(mark_sheet):
        if marks == second_lowest_mark:
            print(name)
'''
Comment: This code doesn't make much sense--please fix the indentation and describe what you're giving to `input` (better yet, just hardcode in failing data). `score_list` is undefined. Please provide a [mcve]. What is the expected output? Thanks for clarifying.
Comment: marksheet and scorelist are the empty list and user will enter any no. and based on that no, user will enter that no of times name and score.
Answer: The error here is NameError: name 'score_list' is not defined. Change it and see.
marksheet=[]
scorelist=[]
for i in range(0,int(input())):
    name=input()
    score=float(input())
    marksheet.append([name,score])
    scorelist.append(score)
second_marks=sorted(list(dict.fromkeys(scorelist)))[1]

I think this is the problem you have. unless what is your expected output?

Index out of range for the list?