What is this columnar cactus?

Question: I am trying to identify my cactus that I planted when I xeriscaped last year. I never saved the little stick thing. I thought it was just a saguaro variation, but then it popped out all these red fingers. Any ideas?
Comment: Did you do this landscaping yourself or did you hire a professional?  If so, they would have design and plant materials used on file.  One note of something I see in your photos...that rock is too close to your siding of stucco.  I'd move those river stones away to try to get 4" below your siding or at least so they don't touch.  Believe it or not rocks can hold and splash water up onto the bottom of your siding and cause it to disintegrate.
Answer: It's a Cleistocactus variety, just not sure which, maybe C. smaragdiflorus, though the flowers on that one usually have a greenish tip, see here http://zipcodezoo.com/index.php/Cleistocactus_smaragdiflorus. The hairs/spines on the stems of your plant don't look silvery enough to be C. straussii either. C. hyalacanthus is another possibility, and that variety does have 'hairy' or furry flowers, like yours, but often has a non hairy or darker patch on top of the stems which I'm not seeing in your pics, so I'm afraid I can't say 100% which variety it is. Information about Cleistocactus generally here  http://dendro.cnre.vt.edu/dendrology/syllabus/factsheet.cfm?ID=933

What is this columnar cactus?


Command and Option keys on Windows keyboard

Question: I am using an external keyboard which is a Windows keyboard. I am not able to use copy and paste command with ctrl and there is no command key or the option key in this keyboard. What is the shorcut for copy paste or cut paste on such keyboard?
Answer: The Windows key will operate as the Command key, so cmd-c is win-c.
Further, the Alt key will operate as the Option key.
Answer: In macOS the copy command is invoked by the key combo command + C. The Windows key is normally the command key. As your keyboard does not have a command key you can map that key behavior to another key.
To swap the behavior of keys, go to System Preferences --> Keyboard --> Modifier Keys, select the right keyboard and set the desired behavior per key.
An option would be to set your alt \ option key to act like command and have your Caps Lock act like alt \ option.

Alternatively you can use Karabiner-Elements to set more advanced key remaps.


Is a 18% gray card intended for exposure metering, and its use to set white-balance is just a bonus?

Question: I've heard that 18% gray cards are intended specifically to aid on determining the right exposure for photography, and only coincidentally for white balance. Is this true? Is it better to use a different type of aid for setting white balance?
Comment: Questions are definitely related but I'm not sure they're really duplicates.
Comment: 18% cards are an old film concept (Ansel Adams promoted them in the 1930s), and are not "perfect" for digital. Our histogram is gamma encoded, and 18% should come out about 46% (but not because it is middle of anything digital).  18% is pretty dark for WB, and the 18% cards are not spec'd for accurate neutral color.  WB cards are white or light gray.  For WB, look at Porta Brace White Balance card, $5 at B&H. Include it in SAME LIGHT in your scene (first test picture, or at far edge to be cropped out).
Answer: Short answer, black is too dark to not clip reliably, white is too bright to not clip reliably.  You need something that is pleasantly in the middle to give you an idea of proper curves and balance.  A medium grey card is ideal for the purpose of determining the curves and the color of the lighting in the scene.  The percentage is chosen for exposure, the color is chosen for the white balancing.
Answer: My understanding is that your camera attempts to expose the mid range of your photo to be 18% grey so these card are most useful for exposure. However an incident light meter will be a bit more effective.
Depending on your camera model you should be able to measure a scene and set a custom white balance based off off a reference photo. This reference photo can be of any neutral coloured thing from white to dark gray, or even better a colour chart, and does not need to be even in focus, so I doubt you specifically need a grey card for this purpose, however it would be useful.
I think this would probably be the most effective way to set the white balance, although given that you could have multiple light sources at a different temperature even this is not fool proof.
To set a custom white balance on my D600 I use PRE setting for white balance. For more information:
http://www.digitalcameraworld.com/2012/05/23/how-to-set-custom-white-balance-for-perfect-colours/


How do I open multiple terminals, so I can have multiple shells open?

Question: I have been slowly learning Gnu/Linux commands, and I'm using it to get more serious about my python programming. While reading about python on Gnu/Linux its uses and integrated shell, plus using the terminal. I'm curious how to have multiple terminals open, as when I try to open a new shell, it just brings my current terminal to the front. I'm using Fedora on a laptop.
Comment: What desktop are you using? This will be the deciding factor. (Try right clicking on the icon.)
Comment: And if all else fails, you can start a new terminal emulator window from your existing shell, e.g. `xterm &` if you are using `xterm`.
Answer: To open multiple terminals in Fedora, Open the terminal, go to the menu bar, and click File > New Window or File > New Tab. Personally, I prefer the latter as you can just switch between tabs and then bring the whole window up and have all of them available. Each tab is a different shell session just as each window is.
Answer: As I understand, you want more terminals open and to view all of them in the same time. If you are using GUI you can grab your tab and move them around, resize them, and stick it anywhere on the screen,like you move any other app. If you are using CLI you can use tmux program.


To get the checkbox value on checking checkbox in datagridview

Question: I have a datagridview in which i have fourth column as checkbox.On clicking checkbox i want to get checkbox value in codebehind.Can anybody help?
Answer: You should not try to access the CheckBox.Checked value directly, rather get the value from whatever it is bound to.
If you really want to get it from the checkbox you can do something like myDataGridView.Rows[0].Cells[3].Value


Best practice for volume aliases in config files

Question: I'm wondering about using a config/volumes.php file to specify volume aliases (instead of putting them in config/general.php). There's a comment in a previous codebase mentioning https://docs.craftcms.com/v3/config/#overriding-volume-settings but that seems to have been removed and now we can't find documentation about creating additional config files.
I see this somewhat related post and that @robin-schambach posted with a suggestion to put volume aliases alongside of other ones in config/general.php.
Craft 3: how can I set dynamic Base URL in sites setting?
So, is it best practice to create a config/volumes.php just for volume aliases or should they be kept in config/general.php?
Answer: Ah, the power of commit history.
@brandon-kelly removed the volumes config section from the v3 docs back in February, mentioning

Environment variables solve the same problem better.

So it seems that the best practice is to create volume aliases in config/general.php.


Is Prokofiev's Suggestion Diabolique an etude?

Question: I am playing Prokofiev's Suggestion Diaboliqe (the real translation of the title of the piece would be Obbsesion). Does anybody know the backround of this piece and was it supposed to be an etude? Thanks a lot.
Answer: The piece comes from a collection, 4 Pieces for Piano, op. 4. The pieces are student works, originally written in 1908, when Prokofiev was 16 or 17, then revised, before being published in 1913. They are character pieces, and not intended as etudes.
Comment: Thank you. I was asking for that because I am going to a competition in which you have to play 1 etude so I tought this piece might come wright.


Would a Hot Air Balloon work in an O'Neill Cylinder?

Question: We had a long discussion in my office about this - if we were in a smallish 500m diameter O'Neil cylinder would hot air balloons work?
Comment: I assume that, like a conventional O'Neil design, it's spun to generate gravity?
Comment: @Cadence Yes correct.
Comment: Well, yes, obviously. Why wouldn't they? The apparent gravitational force is due to the rotating frame of reference. With respect to the rotating frame of reference the ballon would appear to be rising in the air. To make the question interesting it would be helpful to indicate *why* you think that they might not work.
Comment: @AlexP I can understand your response. It's just sometimes that things that seem obvious, may not be so obvious. The nature of the physical world is quite often non-intuitive. Personally I'm glad to see the question. Nothing like seeing an issue clarified.
Comment: Thanks for asking the question. I tend not to take for granted that things work the same with centrifugal gravity compared to normal gravitation. Hot air balloons in O'Neil cylinders is one of them. This puts my mind at rest.
Answer: Yes, certainly.
The rotation creates a gravity-like effect for everything that follows the rotation, which includes the air. If the hot-air balloon is lighter than the air, it will rise. Even in so small a cylinder, there will be a small density gradient between the air at the rim and that nearer to the center, since the inner air will not carry as much weight of air as the outer air. This should make it possible to stabilize the hot-air balloon at a certain altitude-
There are some coriolis effects that create wind patterns, which will affect any hot-air balloons: As warm air rises, it moves to regions where the rotational velocity is smaller, creating wind in the direction of rotation in this region. As cool air falls, it enters regions where the rotational velocity is greater, creating wind counter to the rotation. This is likely to result in rolling vortices of air where air rises, moves forward, cools and falls, and moves backwards. The smaller the diameter of the cylinder, the more pronounced this effect will be, though the air will never move faster than the speed of rotation. Around the center of the cylinder, there will be a vortex rotating in the opposite direction as the outer vortices.
Comment: @Infrisios. Certainly, but you wouldn't need much of a gradient. Hot-air ballons are generally heated until they lift off the ground and quickly find a stable height at a few hundred meters. At (say) 250 meters on Earth, the air pressure is 97% of the surface pressure, not that much of a difference.
Comment: But wouldn't the density difference be marginal and most of the air pressure come from the cylinder being pressurized?
Answer: Simple answer: yes. Hot air balloons rise due to their low density compared to the air around them. Gas centrifuges exist which use centrifugal forces to cause density stratification in a gas (in the case of the link, separating lighter 235UF6 from heavier 238UF6. Uranium gas centrifuges are low pressure, but the technique works for gases more amenable to high pressure work (see this paper on natrual gas/CO2 separation, with a 5 bar fill pressure). Thus, in a spun habitat with an earth-like atmosphere (at least at the outer edge of the volume), your hot air balloon can rise, regardless of whether or not the air pressure is caused by pumping lots of air into a small volume, or by centrifugal effects.
You may get some odd coriolis effects (as you move up, you'll appear to be accelerated forwards, and as you move forwards you'll appear to be accelerated down, etc etc) but as the speed of a balloon is usually quite sedate this shoudl have negligible effect.

As the radius increases though, things start chaning a bit. For example, the flight profile won't be quite the same as they would on earth for various reasons.
From McKendree's paper on rotating habitats, section 5.2.3, you get this (not entirely legible) formula for atmospheric density:

suggesting that the scale height of the atmosphere is not dissimilar to Earth., so operating altitudes for a balloon in a large habitat would be similar to Earth. Conversely, in this Space Exploration SE answer (Radial variation of atmospheric pressure in rotating O'Neill cylinder-like ship?, answer by "Atmospheric Prison Escape" who sometimes shows up here) suggests that the scale height is very large compared to the radius of the station, meaning you could fly up Quite High, which will get you interesting gravitational effects.
$$P(r) = P_0 \exp(-\frac{\Omega_0^2}{c^2_s}\frac{r_0^2-r^2}{2})$$
I couldn't tell you who is right here (though I wonder if APE is closer to the truth due to more sensible handling of the effects of a rotating reference frame), but it seems that modelling of pressure and turbulence in a rotating station hasn't been done, and it isn't clear how hard the problem has been studied, if at all. You could, for example, have quite strong rotary winds that would just swing you round and round in a slightly unpleasant way and at mildly alarming speeds. Not like the sort of balloon flights you might get on earth at all.


If the Meteor BVRAAM is the best AAM, and the APG-81 is the best radar for detecting aircraft, then why don't all fighter aircraft simply use these?

Question: Why are some missiles incompatible with some aircraft?
If fighter A has better radar and missiles than fighter B, then why isn't it possible to simply integrate the better radar and missiles into fighter B?
Comment: Define what you mean by "better"
Comment: A glossary of acronyms would already help.
Answer: Several potential reasons.

The aircraft may lack the electronics or software to operate the weapon.
The missile may not have the required connectors and other hardware to interface with the aircraft

This prevents many Russian/Soviet style weapons from being used on American aircraft. It also prevents a lot of French weapons from working on aircraft being built anywhere else.
This was a major factor in the Dutch decision to purchase the F-16 instead of the Mirage 2000, as the latter would have meant not just replacing their aircraft but also replacing most their entire inventory of missiles, rockets, bombs, and everything else (and all the maintenance equipment).
Sometimes the differences are small enough that they can be retrofitted, for example if it's only a small software change. Sometimes it requires new hardpoints to be added to the aircraft, or adapters to be added to existing hardpoints. And sometimes the changes are just too great to make them worthwhile.
With aircraft that use internal storage (like the F-35) an additional factor is the available space in the weapons bays.
Comment: Presumably, Russian arms manufacturers aren't allowed to sell to the US Air Force and vice versa. That would be much more significant than any hardware incompatibility.
Comment: @DavidRicherby there's countries using both Russian and US equipment. They've a hard time integrating the disparate systems but that's not always a problem (e.g. Poland and Hungary slowly switching from one to the other, Turkey using some Russian stuff in isolated areas where the disparaties aren't problematic, Israel having some captured Soviet era equipment in service that they've upgraded with their own components to fit it into their overall system).


The origins of fork()

Question: Is fork() older than C? What are its origins? I might think that fork() was created along with C (1970s) but I recently read a reference to a 1963 paper where fork() was mentioned.
Comment: When learning about `fork()`, it's also worth exploring BSD's `vfork()`.
Answer: The fork() system call is definitely older than the C language because it already existed in the UNIX v0 draft, page 18 of the PDF, when the C language hasn't been conceived yet.
The mechanism was different from what we're used to:

Except while UNIX is bootstrapping itself into operation, a new
  process can come into existence in only one way: by use of the
  fork system call.
processid = fork(label)

When fork is executed by a process, it splits into two independently
  executing processes. The two processes have core images
  which are copies of each other, but they are not precisely
  equivalent: one of them is considered the parent process. In the
  parent, control does not return directly from the fork, but instead passes to location label; in the child process, there is a
  normal return. The processid returned by the fork call is the identification of the other, offspring process.
Comment: That looks like an editorial mistake, mixing parent and child – the parent would need the child's processid, not the child, right?
Comment: I don't have any documentation on Multics but could this have been taken from Multics - after all both the Unix (formerly Unics)  inventors were previously Multics programmers.
Comment: @PaŭloEbermann You're most likely right, as the last sentence indicates that the most recent phrase should be about the parent process.
Comment: @cup In a conversation the other day I was told that the concept of forking a process did exist in Multics, but the evolution of the calling convention is of interest as well.
Answer: An article on the history of fork appeared in the IEEE Annals of the History of Computing 2016 vol. 38.
This article states that fork was invented by Melvin Conway in 1962 when considering the allocation of tasks to processors in multi-processor systems.
Comment: @RichardT Here you go https://www.docdroid.net/oEodAHw/1963-11-24-pdf#page=146
Comment: @RichardT the lesson is clear.. never delete a PDF you've downloaded once ;) Best wishes, and glad you liked it
Comment: The original Conway paper can be found on page 164 of http://www.textfiles.com/bitsavers/pdf/afips/1963-11_%2324.pdf
Comment: @dmw Unfortunately, your link gives a 404; any chance you can find an active one? Please?
Comment: @dmw I'm VERY appreciative for you providing that link. As it was published less than two weeks before my birth AND as I have spent over 44 years in computing (and am still very active), this is a VERY interesting read! I've downloaded the whole thing and while I really don't have time to read ALL of it, I'd never have found it without your link! THANKS!

The origins of fork()


Is there any difference between " i was woken up by a ringing bell" and " i was woken up by a bell ringing"?

Question: I tried looking in the internet but could not find any appropriate answers.
Answer: There is no commonly understood difference in the practical meaning of the two sentences.

But since you're asking specifically about grammar, there is a possible difference in their theoretical interpretations.
In both possible interpretations, it's not a bell itself that's making noise.

I was woken up by a ringing bell.

This could mean you were woken up by a bell designed to ring. In other words, ringing could be interpreted as an adjective (attributive noun) rather than a verb. In this case, somebody could have picked up the bell that was designed to ring—but which was currently silent—and hit you over the head with it. (Perhaps it was an electronic bell and its battery had run out.) It wasn't actually ringing that woke you up, but the bell-designed-to-ring-but-which-was currently-silent hitting you on the head that woke you up.

I was woken up by a bell ringing.

In theory, a bell ringing could be some kind of ceremony or activity (like a house sitting), and it's being used as a noun phrase. So, those people involved in a bell ringing (bell-ringing ceremony) woke me up with the swishing of their robes.

Is there any difference between “ i was woken up by a ringing bell” and “ i was woken up by a bell ringing”?


Two oatmeal pies a day keep the doctor away?

Question: Is it "two oatmeal pies a day keep the doctor away" or "two oatmeal pies a day keeps the doctor away"?
Comment: Well, "pies" is the subject so it should take a plural predicate: keep. However, I have never heard that advice about oatmeal pies. I've always been told, "An apple a day keeps the doctor away." In fact, I don't think I've ever eaten an oatmeal pie.
Comment: The two conjugations of 'keep' here come from the possibility of the phrase being truncated at the start in common speech: "[(the act of) eating] two oatmeal pies a day keep[s] the doctor away". Accordingly, 'keep' agrees with either 'the act' or the 'oatmeal pies'.
Answer: Either one could be correct.
This question highlights an interesting feature of English called notional agreement.  Here's an excerpt from Merriam Webster:

Most English speakers know the basic rule of subject-verb agreement: a singular noun takes a singular verb, and a plural noun takes its corresponding plural...But there are times when the determination for what counts as "agreement" is not as obvious, because what sounds like a singular noun is really plural, or what sounds like a plural noun is essentially singular. This concept is known as notional agreement, otherwise known as notional concord or synesis.
Simply put, notional agreement occurs when the agreement between a subject and its verb (or, in some instances, a pronoun and its antecedent) is determined by meaning rather than form.
https://www.merriam-webster.com/words-at-play/notional-agreement-subject-verb-principle-proximity

A clear example of notional agreement is "peanut butter and jelly is my favorite sandwich." Peanut butter and jelly looks at first like a plural subject, but the intended meaning of the sentence is something like: [the combination of] peanut butter and jelly is my favorite sandwich.
Other examples cited in that article include, "two plus three makes five" => [the sum] two plus three makes five, "ten dollars is the cost of admission" => [a value of] ten dollars is the cost of admission.
So what about your "two pies"?
To answer the question, we'd need to know whether it was the two pies separately, each one working on its own, that kept the doctor away, or whether the pair of pies, as a unit, kept the doctor away. We can't definitely decide which of those is the case, since this is metaphorical language. I happen to read this statement as [Eating] two pies a day keeps the doctor away, and thus, I'd use the singular form, keeps.
Comment: Yes. Both is correct.
Answer: If we're describing what native speakers say, we'd have to say that both versions are acceptable.
It's possible to understand "two oatmeal pies a day" as a singular "prescription for health" and then use the singular verb.  Sometimes semantics trumps the grammatical number of the noun.
Comment: I had to read and compare OP's two examples several times to even see there was a difference.


UITableView Multiple Selection

Question: How can I add a UITableView into my View-Based Application where the user will tap on more than one cell, and it will become selected, exactly like the Clock app's "New Alarm" setting named "Repeat" (Clock>Alarms> + >Repeat), and how can I get all of the selected cells in an array?
Comment: Psh.  I didn't see Apple's example on this.
Answer: For multiple selection, add the line below in viewDidLoad()
tableView.allowsMultipleSelection = true

Configure each cell after dequeuing (or initializing) it in tableView(_:cellForRowAt:)
let selectedIndexPaths = tableView.indexPathsForSelectedRows
let rowIsSelected = selectedIndexPaths != nil && selectedIndexPaths!.contains(indexPath)
cell.accessoryType = rowIsSelected ? .checkmark : .none
// cell.accessoryView.hidden = !rowIsSelected // if using a custom image

Update each cell when it's selected/deselected
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let cell = tableView.cellForRow(at: indexPath)!
    cell.accessoryType = .checkmark
    // cell.accessoryView.hidden = false // if using a custom image
}

override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    let cell = tableView.cellForRow(at: indexPath)!
    cell.accessoryType = .none
    // cell.accessoryView.hidden = true  // if using a custom image
}

When you're done, get an array of all the selected rows
let selectedRows = tableView.indexPathsForSelectedRows

and get the selected data, where dataArray maps to the rows of a table view with only 1 section
let selectedData = selectedRows?.map { dataArray[$0.row].ID }

Comment: I don't understand why this is not the accepted answer... if you use a custom cell you can also change the appearance in you cell's setSelected:animated: method based on the cell's state
Comment: To get selected objects indexs NSArray *selectedCells = [self.tableView indexPathsForSelectedRows];
Answer: In your implementation of -tableView:didSelectRowAtIndexPath: you would set the table view cell's accessoryType property depending on its current value (so it would toggle on and off with multiple taps). For example:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)path {
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:path];

    if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
        cell.accessoryType = UITableViewCellAccessoryNone;
    } else {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
}

You could either maintain an array of selected states in addition to the cells' own accessory type state, or iterate over the cells in the table view querying for each one's state in order to read out the selected rows.
Comment: This won't work -- indexPath refers to the wrong cell when a cell is selected and you scroll.  As a result you will see multiple items checked.
Comment: -1 This solution has an issue, once you select certain rows and scroll you can see many check marks for those cell which you have not yet selected.
Comment: As in the previous comment, this won't work as you will multiple items selected as you scroll.
Comment: This solution have another issue when unchecking cell, you have to tap twice to make accessory type none, because when we select a cell it makes it accessory type checkmark and change its state to selected. So when you want to uncheck, it does not go to this method didSelectRowAtIndexPath but go to didDeselectRowAtIndexPath. So you have to implement this method also.
Comment: To solve reload issue, do this in cellForRowAtIndexPath:

      if(cell.isSelected)
    {
         cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }else
    {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
Comment: This will cause checkboxes to appear on table row items down stream because you are using the same cell.
Answer: @BrendanBreg implementation didn't worked for me. @RaphaelOliveira provided good solution, but when you scrolls your table down - wrong rows become selected (because UITableView caches it's cells). So, I've slightly modified Raphael's solution:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.accessoryType = UITableViewCellAccessoryNone;
}

/*Here is modified part*/

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    /*
    ...
    Your implementation stays here
    we're just adding few lines to make sure
    that only correct rows will be selected
    */

    if([[tableView indexPathsForSelectedRows] containsObject:indexPath]) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    } else {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
}

Comment: When scroll it hides the selected rows!
Answer: self.tableView.allowsMultipleSelection = YES;

Answer: Just a quick tip in addition to the great answer above: to mimic Apple's style from the clock app (making the row select color fade back out after checking / unchecking the row), add this to the didSelectRowAtIndexPath, after the conditionals:
[self.tableView deselectRowAtIndexPath:indexPath animated:YES];

From Apple's TableMultiSelect guide.
Answer: Here it is what you needed
http://developer.apple.com/library/ios/#samplecode/TableMultiSelect/Introduction/Intro.html#//apple_ref/doc/uid/DTS40011189-Intro-DontLinkElementID_2
Answer: I have seen this problem with so many developers. Due to table view's nature of re-using cell it removes or haphazard the checks. I have created a working solution for that. Clone/download code from DevelopmentSupportWorkspace and Execute UITableViewTest project from there.
Here is code summery for that:
@interface CheckBoxTestTableViewController ()

@property (nonatomic, strong) NSArray *dataArray;
@property (nonatomic, strong) NSMutableDictionary *selectedIndexDictionary;

@end

@implementation CheckBoxTestTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;

    //
    _dataArray = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"ImageList" ofType:@"plist"]];
    _selectedIndexDictionary = [NSMutableDictionary dictionary];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"checkMarkCell" forIndexPath:indexPath];
    cell.accessoryType = UITableViewCellAccessoryNone;

    // Configure the cell...
    cell.textLabel.text = _dataArray[indexPath.row][@"text"];
    if (_selectedIndexDictionary[indexPath] != nil) cell.accessoryType = UITableViewCellAccessoryCheckmark;

    return cell;
}

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    if (_selectedIndexDictionary[indexPath] == nil) {
        [_selectedIndexDictionary setObject:_dataArray[indexPath.row] forKey:indexPath];
        [[tableView cellForRowAtIndexPath:indexPath] setAccessoryType:UITableViewCellAccessoryCheckmark];
    }else{
        [_selectedIndexDictionary removeObjectForKey:indexPath];
        [[tableView cellForRowAtIndexPath:indexPath] setAccessoryType:UITableViewCellAccessoryNone];
    }
//    [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
@end

Answer: The clock alarms repeat table view is not multiple selection.  Think of it as a lit of checkboxes.
When a cell is selected, the font color and accessory type are changed and the selection fades out.  When a checked cell is selected, the font color and accessory type are changed back and the selection fades out.
In your didSelectRowAtIndexPath delegate method, you would set the text color and accessory type for the selected cell, then deselect the cell.  You would also record the new state in your data model.  That could be as simple as a bit mask representing the selected state, but depends on what data you are displaying.
In your cellForRowAtIndexPath: dataSource method, set the text color and accessory type based on your data model.
Actual multiple selection would be similar.  You have to keep track of which cells are selected, and set the selected cell of each state as it is created or shown.  When the table view reports that a cell is selected, toggle the selection state in your data model and set the selected state of the cell accordingly.
Answer: You can't key off indexPath because the cells that refers to changes as you scoll.  Put an NSLog in cellForRowAtIndexPath to see that.  You can do the check/uncheck in willSelectRowAtIndexPath or didSelectRowAtIndexPath.  That covers only the initial check or uncheck though, and will also have things appear as checked once you've scrolled because the underlying cell for a given indexPath changes.
So the solution I found is to have an array of selected things with something that is specific to that given cell, and do the initial check.
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];

  if (![selectedIndexes containsObject:cell.textLabel.text]){
    [selectedIndexes addObject:cell.textLabel.text];
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
  } else {
    [selectedIndexes removeObject:cell.textLabel.text];
    cell.accessoryType = UITableViewCellAccessoryNone;
  }

  return indexPath;
}

You also have to have logic in cellForRowAtIndexPath to make sure the right stuff is checked or not as the view scrolls:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

  ...

  cell.accessoryType = UITableViewCellAccessoryNone;
  if ([selectedIndexes containsObject:cell.textLabel.text]) {
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
    [cell setSelected:YES animated:YES];
  }

  return cell;
}

Comment: -1 The indexPath in tableView:didDeselectRowAtIndexPath: does NOT depend on scrolling, and there is no need to keep a separate array of selected items. See @Dmitry solution for a correct implementation
Answer: 1 - Allow multiple selection and toggle of selected state:
tableView.allowsMultipleSelection = true

2 - Collect or get an array of all selected indices when you are done:
let selected = tableView.indexPathsForSelectedRows

Note: This is independent of which cells are currently showing on screen.
3 - Change the appearance of the cell depending on selected state: Override this method in your UITableViewCell subclass. If you don't have a subclass, make one.
// In UITableViewCell subclass
override func setSelected(selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)
    accessoryType = selected ? .Checkmark : .None
}

Answer: I know that this is an old posting, but for future use, the following code will solve the problem of ensuring that a checkmark will only appear on selected rows during scrolling:
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    cell.accessoryType = (cell.isSelected) ? .checkmark : .none
}

UITableView Multiple Selection


How do I count elixir?

Question: In Clash Royale, one thing pros are able to do is count elixir.
I was wondering how would I be able to do such things.
Answer: In any competitive game there is something called "game sense", what this means is that as you play the game you start to understand the intricacies of the game and is able to do certain things that an inexperienced player wouldn't do.
As for Clash Royale, you need to understand what deck your opponent is playing and be able to understand how much elixir your opponent has based on the cards he has played. For example after your opponent goes all in with hog/goblins/prediction log, you need to be able to add the elixir of those cards, which happen to be 8, so after you defend this push and has units left over, you can get a huge counter push and your opponent will only have 3 elixir to defend.
Basically, there is no correct way to count elixir, pros can do this because they play a lot and are naturally good at keeping a clear mind. Just keep playing, and understand how to properly punish your opponent for making bad all in plays.
Answer: A quick method of counting elixir is using your own as a reference. Example of a game:

I put minions and miner(6 elixir) at 9.9 elixir and he puts a minion horde when I have 5 elixir=> he lost 1 elixir for the delay and I know he is still on par with me
He plays hog rider and Goblins(6) and I play barbarians, he will be -1.
Continue the count from -1 for each card he plays after you play the response, only adding the difference

You can divide a battle into multiple plays (where you and the opponent put down cards) and keep the score after each play.
Keeping score of the opponents elixir and his card rotations are just as important as a good and upgraded deck.
Answer: There's an app called Elixir Counter that could help you in counting elixir, you'll have to enable "Elixir counter mode" option in settings and click on each card your opponent plays.

How do I count elixir?


What's the self awareness of Paul re his office of "Apostle of Gentiles"?

Question: What's the nature of the self awareness of Paul regarding his office of "Apostle of Gentiles"? Can we say that in Paul's mind he is appointed the office singularly or exclusively as no one else can say the same in the same sense, or he think he is just one among many laborers? (Ephesians 3:1-2)
Comment: Welcome to BHSX.  Thanks for this excellent question.  Please remember to take the tour (link below left) to better understand how this site works.
Comment: @Dottard I wonder why you say the tour link is "below left." On my screen it's under the question mark at the top right bar.  Does this depend on the device? Here's the [link](https://hermeneutics.stackexchange.com/tour) in any case.
Comment: @DanFefferman Maybe on a smart phone it is different. (I wouldn't know, as I don't use one.) On a computer it is at the bottom of the page, bottom left, under 'Bibilical Hermeneutics' - 'Tour' and 'Help'.
Comment: Interesting factoid: The [Tour](https://hermeneutics.stackexchange.com/tour) link is both at the bottom left under "Biblical Hermeneutics" and at the top right under the question mark. In the mobile version of the web page, both are centered. So, Nigel and Dan are both right is right. Everyone was so excited to know; you're all welcome.
Answer: Relying on Acts 15:22, we are informed that both Paul and Barnabas were "sent" (the verb from which "apostle" is derived) to Antioch to minister to the Gentiles, and between the two, Barnabas was originally the senior, being a Levite and having joined the church much earlier (Acts 4:36).
Also, Acts 14:14 specifically refers to both men as "apostles:"

But when the apostles Barnabas and Paul heard of it, they tore their
garments and rushed out among the multitude

From the above we know that Acts considered at least one person besides Paul to be an apostle. But Paul never read Acts and the question is whether Paul, in his own mind, considered himself unique as the Apostle to the Gentiles. Although he does not specifically use this title in regard to Barnabas, he certainly knew that Barnabas, as his elder brother in the faith, had been sent back to Antioch with him by the elder apostles with the same mission as Paul. (Acts 15) Also, as the OP points out, Paul definitely acknowledges others beside himself to be legitimate ministers of the Gospel among the Gentile churches.
So we may conclude that Paul may have considered Barnabas in some sense to be his co-apostle in bringing the Gospel to the Gentiles. Beyond that, we have to speculate. Certainly Paul knew that others ministered to the Gentiles, presumably having been authorized by the elders in Jerusalem, as he himself was. However, in references to such ministers in his letters, Paul acknowledges no one other than himself as "apostle to the Gentiles." Indeed, the famous "men from James" (Gal. 2) sent to Antioch are specifically denigrated by Paul as false teachers who negatively influenced even Barnabas, his co-minister.  We are left with the OP question unresolved.
Comment: Excellent analysis thank you. It seems the word apostle is used more loosely in New Testament time then we probably use now. Maybe I should phrase  the question this way: can we say that Paul in his own mind think that he is given the burden, revelation, task and authority to the gentile church, uniquely, singularly, like no one else, has no equal?
Answer: The question seems to be answered later in the chapter, as we read on into it.
Yes, Paul is a prisoner "on behalf of" the Gentiles he's addressing (v1 RSV), and he has a stewardship of God's grace "for you" (v2), but neither of those is necessarily exclusive.
Then in vv4-6 he speaks of the "mystery of Christ". This is the secret of the fact that the Gentiles are "fellow-heirs" of the Jews, and "partakers of the promise in Christ Jesus". On the one hand, this mystery was "not made known to the sons of men in other generations". They were excluded from this knowledge by being born too soon. On the other hand, "it has now been revealed to his holy apostles and prophets by the Spirit". Not just revealed to himself.
Since there are many others who have been shown the secret, the implication is that many others may be involved in teaching it. Indeed, when Paul calls himself "minister" of the gospel to the Gentiles (v7),the noun comes without a definite article. He does not claim to be THE minister.
Now, in practice, as the leadership recognised (Galatians ch2 v9) God was steering Paul rather than the other leaders towards this task. At the same time, though, we learn from Acts and from greetings in the epistles that Paul was doing this work in company with men like Barnabas and Timothy and countless others. For that matter, Paul's ministry to the Gentiles did not entirely block out his witness towards the Jews. A large part of the epistle to the Romans is a direct address to the unconverted Jews.
In both ways, Paul's mission to the Gentiles is a matter of emphasis rather than an exclusive task.
Comment: Thank you for your excellent answer. I try to reconcile the two views. Maybe the degree of the revelation, the level of understanding given is different between Paul and the other people who are burdened in the labor and for the gentiles church. it seems to me Paul has a consciousness that he is THE apostle to the gentiles. For example, when he begins his episodes introducing himself, one reading it would not tend to think that he is one of 200 apostles to the Gentiles.
Comment: Then how do you explain the term 'apostle' being confined to 'twelve' in several places in holy writ ?
Comment: @Nigel J Paul calls himself an apostle in 1 Corinthians ch9 vv1-2 and 1 Corinthians ch15v9. In the second passage, he admits to being a late arrival on the list, so that could account for the discrepancy.
Comment: Yes, indeed. So Paul is number twelve. I agree . . . . .  and then there are no more.
Comment: @EastOfEden Certainly he was the prime mover in that campaign.
Answer: Paul claimed to be "the apostle to the Gentiles" a number of times:

Rom 11:13 - I am speaking to you Gentiles. Inasmuch as I am the apostle to the Gentiles, I magnify my ministry
Rom 15:16 - to be a minister of Christ Jesus to the Gentiles in the priestly service of the gospel of God, so that the Gentiles might become an offering acceptable to God, sanctified by the Holy Spirit.
Gal 2:8, 9 - For the One who was at work in Peter's apostleship to the circumcised was also at work in my apostleship to the Gentiles. And recognizing the grace that I had been given, James, Cephas, and John—those reputed to be pillars—gave me and Barnabas the right hand of fellowship, so that we should go to the Gentiles, and they to the circumcised.
Acts 13:47 - For this is what the Lord has commanded us: 'I have made you a light for the Gentiles, to bring salvation to the ends of the earth.' "

This also appears to allude to some OT passages as well:

Isa 49:6 - He says: "It is not enough for You to be My Servant, to raise up the tribes of Jacob, and to restore the protected ones of Israel. I will also make You a light for the Gentiles, to bring My salvation to the ends of the earth."
Ps 98:2 - The LORD has proclaimed His salvation and revealed His righteousness to the nations/Gentiles.

Eph 1:22, 23
Note that Paul is claiming a special, personal revelation from God concerning the mystery of Godliness and the mystery of Christ:

Eph 3:1-6 - 1 For this reason I, Paul, the prisoner of Christ
Jesus for the sake of you Gentiles... 2Surely you have heard about
the stewardship of God's grace that was given to me for you, 3that
is, the mystery made known to me by revelation, as I have already
written briefly. 4In reading this, then, you will be able to
understand my insight into the mystery of Christ, 5which was
not made known to men in other generations as it has now been revealed
by the Spirit to God's holy apostles and prophets. 6This
mystery is that through the gospel the Gentiles are fellow heirs, fellow members of the body, and fellow partakers of the promise in
Christ Jesus.

Thus, Paul is effectively claiming that his ministry to the Gentiles about the mystery of Christ:

in accord with that revealed in the OT (see above references)
given to him personally by the Holy Spirit
that, thus, Paul was also like the prophets of old who were "carried along by the Holy Spirit", 2 Peter 1:19-21.
Comment: Thank you for the excellent answer. I am studying it slowly. I feel Paul understood he is entrusted with the evangelization of gentiles like no one else, and accordingly, no one was given the revelation with that depth of understanding, but I don't have enough text proof and some texts suggest otherwise like other replies pointed out.
Comment: @EastOfEden - Paul was the apostle to the Gentiles but several others were also sent to the gentiles such as silas, Barnabas, timothy, Apollos, etc.

What’s the self awareness of Paul re his office of “Apostle of Gentiles”?


Norm of the product of two regular ideals of an order of an algebraic number field

Question: Let $K$ be an algebraic number field of degree $n$.
Let $\mathcal{O}_K$ be the ring of algebraic integers.
An order of $K$ is a subring $R$ of $K$ such that $R$ is a free $\mathbb{Z}$-module of rank $n$.
I am interested in the ideal theory on $R$ because when $n = 2$ it has a deep connection with the theory of binary quadratic forms as shown in this.
Let $I$ be a non-zero ideal of $R$.
It is easy to see that $R/I$ is a finite ring.
The number of elements of $R/I$ is called the norm of $I$ and is denoted by $N(I)$.
Let $\mathfrak{f} = \{x \in R | x\mathcal{O}_K \subset R\}$.
If $I + \mathfrak{f} = R$, we call $I$ regular.
Properties of regular ideals are stated in this question.
Let $I, J$ be regular ideals of $R$.
If $R = \mathcal{O}_K$, it is well-known that $N(IJ) = N(I)N(J)$.
I wondered if this holds when $R \ne \mathcal{O}_K$.
And I came up with the following proposition.
Proposition
Let $I, J$ be regular ideals of $R$.
Then $N(IJ) = N(I)N(J)$.
Outline of my proof
I used the result of this question and reduced the problem to the case $R = \mathcal{O}_K$.
My question
How do you prove the proposition?
I would like to know other proofs based on different ideas from mine.
I welcome you to provide as many different proofs as possible.
I wish the proofs would be detailed enough for people who have basic knowledge of introductory algebraic number theory to be able to understand.
Related question
A generalization of this question is asked here.
Comment: I think you're supposed to put the answer in the answer box, and save the meta for meta.
Comment: The spoiler shows how I tried to solve the problem. When you post a question, You need to show your effort to solve it.
Comment: I opened the following meta thread asking why this question was put on hold.
http://meta.math.stackexchange.com/questions/11617/why-was-this-question-norm-of-the-product-of-two-regular-ideals-of-an-order-of
Answer: By this question, $N(I) = N(I\mathcal{O}_K), N(J) = N(J\mathcal{O}_K), N(IJ) = N(IJ\mathcal{O}_K)$. Hence $N(IJ) = N(I\mathcal{O}_K)N(J\mathcal{O}_K) = N(I)N(J)$.


Is there anything akin to molecular chirality for crystalline?

Question: For example, in hexagonal closed-packed (HCP) structure, the atoms may be arranged in ABAB stacks or ACAC stacks. Can these two be considered enantiomers? Do they possess different solid state properties?
Answer: There are some crystal structures where the nature of the crystal structure creates chirality and therefore optical activity.
A trivial example (important because of its history: it was involved in the discovery of optical activity and molecular chirality) is tartaric acid. But the crystal is chiral because the molecule is chiral so that might not be what yyou were looking for.
But there are examples of crystals where the structure as a whole is chiral but the building blocks are not. Quartz, for example, is formed from a network of linked SiO4 tetrahedra (not molecules but a giant interlinked network where each oxygen is shared between two silicons). The overall crystal structure, though, is chiral due to small shifts in the rotation of the linked tetrahedra (see wikipedia for a detailed explanation).
I think this is a crystal analogy to molecular chirality.
Only a few crystal structures can do this and the ones you use as examples can't.
Answer: Typically, different ways of arranging atoms in a solid are referred to as phases. For a single composition, a material may have different phases depending on temperature or pressure. Different crystal structures are not referred to as enantiomers. For an HCP metal, there is no difference an ABAB stacking and ACAC stacking, other than the naming. If the stacking is ABCABC, then you have a face-centered cubic structure (FCC), not an HCP. The best way to alter solid-state properties such as resistivity, susceptibility, etc., is to change the temperature or introduce defects into the system.


How do I check file size in Python?

Question: How do I get the size of a file in Python?
Answer: Use os.path.getsize:
>>> import os
>>> os.path.getsize("/path/to/file.mp3")
2071611

The output is in bytes.
Comment: Note: the implementation of `os.path.getsize` is simply `return os.stat(filename).st_size`
Comment: @wordsforthewise measure it! ~150 ns in my computer.
Comment: @wordsforthewise this is more of an issue if you also want to get other things about the file (modification time, type of file, e.g.) -- then you might as well get it all from a single system call via `os.stat`. Then the difference could run into a substantial number of microseconds :-)
Comment: So is there a minute performance loss from using os.path.getsize as opposed to os.stat(file).st_size?
Comment: Another advantage of directly using `os.stat()` is, that it accepts filenames relative to a directory file descriptor `dir_fd` as in `os.stat(relname, dir_fd=mydirfd).st_size`, while `os.path.getsize()` does not. When parsing through directory trees, `dir_fd` can be a large advantage.
Answer: You need the st_size property of the object returned by os.stat. You can get it by either using pathlib (Python 3.4+):
>>> from pathlib import Path
>>> Path('somefile.txt').stat()
os.stat_result(st_mode=33188, st_ino=6419862, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=1564, st_atime=1584299303, st_mtime=1584299400, st_ctime=1584299400)
>>> Path('somefile.txt').stat().st_size
1564

or using os.stat:
>>> import os
>>> os.stat('somefile.txt')
os.stat_result(st_mode=33188, st_ino=6419862, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=1564, st_atime=1584299303, st_mtime=1584299400, st_ctime=1584299400)
>>> os.stat('somefile.txt').st_size
1564

Output is in bytes.
Comment: @josch - yes, this is nice, for the "size on disk" you can multiply `stat_result.st_blocks` by the block size, but I'm still searching how to get it programmatically and cross-platform (not via `tune2fs` etc.)
Comment: @TomaszGandor now `st_blocks` is defined as "Number of 512-byte blocks allocated for file", so you don't have to get the block size.
Answer: The other answers work for real files, but if you need something that works for "file-like objects", try this:
# f is a file-like object.
f.seek(0, os.SEEK_END)
size = f.tell()

It works for real files and StringIO's, in my limited testing. (Python 2.7.3.) The "file-like object" API isn't really a rigorous interface, of course, but the API documentation suggests that file-like objects should support seek() and tell().
Edit
Another difference between this and os.stat() is that you can stat() a file even if you don't have permission to read it. Obviously the seek/tell approach won't work unless you have read permission.
Edit 2
At Jonathon's suggestion, here's a paranoid version. (The version above leaves the file pointer at the end of the file, so if you were to try to read from the file, you'd get zero bytes back!)
# f is a file-like object.
old_file_position = f.tell()
f.seek(0, os.SEEK_END)
size = f.tell()
f.seek(old_file_position, os.SEEK_SET)

Comment: If you use integer literals instead of named variables, you are torturing anybody that has to maintain your code. There's no compelling reason not to import `os`.
Comment: Apparently this is at least a little risky, depending on how Python implements `#seek()`: https://wiki.sei.cmu.edu/confluence/display/c/FIO19-C.+Do+not+use+fseek%28%29+and+ftell%28%29+to+compute+the+size+of+a+regular+file
Comment: And for the last line, if ```os``` isn't used: ```f.seek(old_file_position, 0)```
Answer: import os

def convert_bytes(num):
    """
    this function will convert bytes to MB.... GB... etc
    """
    for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
        if num < 1024.0:
            return "%3.1f %s" % (num, x)
        num /= 1024.0

def file_size(file_path):
    """
    this function will return the file size
    """
    if os.path.isfile(file_path):
        file_info = os.stat(file_path)
        return convert_bytes(file_info.st_size)

# Lets check the file size of MS Paint exe
# or you can use any file path
file_path = r"C:\Windows\System32\mspaint.exe"
print file_size(file_path)

Result:
6.1 MB

Comment: Line 10 can be changed to `return f'{num:.1f} {x}'` in Python >= 3.5.
Comment: thank you Matt M., slight update, line 10 can be changed to `return f'{num}{unit}' if unit == 'bytes' else f'{num:.1f}{unit}' ` in Python >= 3.5
Comment: `file_info = os.stat(file_path).st_size`
Answer: Using pathlib (added in Python 3.4 or a backport available on PyPI):
from pathlib import Path
file = Path() / 'doc.txt'  # or Path('./doc.txt')
size = file.stat().st_size

This is really only an interface around os.stat, but using pathlib provides an easy way to access other file related operations.
Answer: There is a bitshift trick I use if I want to to convert from bytes to any other unit. If you do a right shift by 10 you basically shift it by an order (multiple).

Example:  5GB are 5368709120 bytes

print (5368709120 >> 10)  # 5242880 kilobytes (kB)
print (5368709120 >> 20 ) # 5120 megabytes (MB)
print (5368709120 >> 30 ) # 5 gigabytes (GB)

Comment: This doesn't answer the question.  The question is about finding the size of a file, not about formatting the result for human consumption.
Comment: Guys, he hasn't *confused* anything... he's just given an approximation, which is evident when he says "basically".  2^10 is approx. 10^3.  In fact, this approximation is so common that [it has a name](https://en.wikipedia.org/wiki/Mebibyte): *Mebi*, *Gibi*, and *Tebi* are Mega, Giga, and Tera, respectively. Regarding not answering the question, @WillManley , you have a fair point there!  ;-p
Comment: 1-bit=>2
...
2-bits=>4
...
3-bits=>8
...
4-bits=>16
...
5-bits=>32
...
6-bits=>64
...
7-bits=>128
...
8-bits=>256
...
9-bits=>512
...
10-bits=>1024
...
1024 bytes is 1kB
...
=> 20-bits => 1024 * 1024 = 1,048,576bytes, which is 1024kB, and 1MB...
=> 30-bits => 1024 * 1024 * 1024 = 1,073,741,824 bytes, which is 1,048,576 kB, and 1024MB, and 1GB
… You have confused scientific notation and decimal places with the binary/base-2 representation used in computing.
5x9 = 5 x 10^9 = 5,000,000,000
Comment: These numbers are wrong and thus confusing. 5GB is 5e9 bytes. Is this supposed to be some sort of human-readable approximation? Where would you even use something like this?
Answer: we have two options Both include importing os module
1)
import os
os.stat("/path/to/file").st_size

as os.stat() function returns an object which contains so many headers including file created time and last modified time etc.. among them st_size gives the exact size of the file.
File path can be either absolute or relative.
2)
In this, we have to provide the exact file path, File path can be either relative or absolute.
import os
os.path.getsize("path of file")

Comment: os.path.getsize works with a relative path
Answer: Strictly sticking to the question, the Python code (+ pseudo-code) would be:
import os
file_path = r"<path to your file>"
if os.stat(file_path).st_size > 0:
    <send an email to somebody>
else:
    <continue to other things>

Answer: You can use the stat() method from the os module. You can provide it with a path in the form of a string, bytes or even a PathLike object. It works with file descriptors as well.
import os

res = os.stat(filename)

res.st_size # this variable contains the size of the file in bytes

Answer: Here's another self-explanatory example. With this, bytes will be converted into MBs, GBs, or TBs automatically.
from pathlib import Path
from psutil._common import bytes2human

def get_readable_filesize(text_file: Path):
    return bytes2human(text_file.stat().st_size)

if __name__ == '__main__':
    current_file = Path(__file__).parent.resolve()
    print(get_readable_filesize(current_file / 'file.txt'))

Answer: #Get file size , print it , process it...
#Os.stat will provide the file size in (.st_size) property.
#The file size will be shown in bytes.

import os

fsize=os.stat('filepath')
print('size:' + fsize.st_size.__str__())

#check if the file size is less than 10 MB

if fsize.st_size < 10000000:
    process it ....

How do I check file size in Python?


C++ STL Map vs Vector speed

Question: In the interpreter for my experimental programming language I have a symbol table. Each symbol consists of a name and a value (the value can be e.g.: of type string, int, function, etc.).
At first I represented the table with a vector and iterated through the symbols checking if the given symbol name fitted.
Then I though using a map, in my case map<string,symbol>, would be better than iterating through the vector all the time but:
It's a bit hard to explain this part but I'll try.
If a variable is retrieved the first time in a program in my language, of course its position in the symbol table has to be found (using vector now). If I would iterate through the vector every time the line gets executed (think of a loop), it would be terribly slow (as it currently is, nearly as slow as microsoft's batch).
So I could use a map to retrieve the variable: SymbolTable[ myVar.Name ]
But think of the following: If the variable, still using vector, is found the first time, I can store its exact integer position in the vector with it. That means: The next time it is needed, my interpreter knows that it has been "cached" and doesn't search the symbol table for it but does something like SymbolTable.at( myVar.CachedPosition ).
Now my (rather hard?) question:

Should I use a vector for the symbol table together with caching the position of the variable in the vector?
Should I rather use a map? Why? How fast is the [] operator?
Should I use something completely different?
Comment: Just some food for thought, if you store the integer position your variable is at and some variable from before that gets garbage collected or deleted, what is your plan for that integer position cache?
Answer: A map is a good thing to use for a symbol table. but operator[] for maps is not. In general, unless you are writing some trivial code, you should use the map's member functions insert() and find() instead of operator[]. The semantics of operator[] are somewhat complicated, and almost certainly don't do what you want if the symbol you are looking for is not in the map.
As for the choice between map and unordered_map, the difference in performance is highly unlikely to be significant when implementing a simple interpretive language. If you use map, you are guaranteed it will be supported by all current Standard C++ implementations.
Comment: To 'cache' the symbol, just store the iterator returned by std::map::find() instead of the position of that symbol from std::vector.
Answer: You effectively have a number of alternatives.
Libraries exist:

Loki::AssocVector: the interface of a map implemented over a vector of pairs, faster than a map for small or frozen sets because of cache locality.
Boost.MultiIndex: provides both List with fast lookup and an example of implementing a MRU List (Most Recently Used) which caches the last accessed elements.

Critics

Map look up and retrieval take O(log N), but the items may be scattered throughout the memory, thus not playing well with caching strategies.
Vector are more cache friendly, however unless you sort it you'll have O(N) performance on find, is it acceptable ?
Why not using a unordered_map ? They provide O(1) lookup and retrieval (though the constant may be high) and are certainly suited to this task. If you have a look at Wikipedia's article on Hash Tables you'll realize that there are many strategies available and you can certainly pick one that will suit your particular usage pattern.
Comment: If you keep the vector sorted (penalty on insertion) then find will have `O(log N)` performance.
Comment: My vector is sorted, how to achieve `O(log N)` performance?
Comment: @John: You need to use a binary search algorithm. In C++ this can be achieved using the `std::lower_bound` and `std::upper_bound` algorithms (either one works).
Comment: @Matthieu M. It seems that `std::vector::lower_bound` is slower than `std::map::find` even when the data set is small(300 ~ 5000). It's really ***unexpected***. I did such tests  on Ubuntu two hours ago. How do you think about it?
Comment: @John: I think you'd need to make a proper question, and show your code, compiler and compiler settings, etc... It is, indeed, unexpected.
Answer: Normally you'd use a symbol table to look up the variable given its name as it appears in the source.  In this case, you only have the name to work with, so there's nowhere to store the cached position of the variable in the symbol table.  So I'd say a map is a good choice.  The [] operator takes time proportional to the log of the number of elements in the map - if it turns out to be slow, you could use a hash map like std::tr1::unordered_map.
Comment: You can certainly store the position in your parse tree or some other intermediate representation, but you can do the same thing if you're using a `map` as Tronic says in his/her answer.  The big difference is just the time to look up the variable name.  (Actually other issues pop up if you want to serialize your data structures but I'll stop speculating about your code here ;))
Comment: You don't know my code, I have a very good option to store the position, trust me
Comment: Then store a pointer (e.g. symbol*), and bypass the container lookup completely.
Answer: std::map's operator[] takes O(log(n)) time. This means that it is quite efficient, but you still should avoid doing the lookups over and over again. Instead of storing an index, perhaps you can store a reference to the value, or an iterator to the container? This avoids having to do lookup entirely.
Answer: When most interpreters interpret code, they compile it into an intermediate language first.  These intermediate languages often refer to variables by index or by pointer, instead of by name.
For example, Python (the C implementation) changes local variables into references by index, but global variables and class variables get referenced by name using a hash table.
I suggest looking at an introductory text on compilers.
Answer: a std::map (O(log(n))) or a hashtable ("amortized" O(1)) would be the first choice - use custom mechanisms if you determin it's a bottleneck. Generally, using a hash or tokenizing the input is the first optimization.
Before you have profiled it, it's most important that you isolate lookup, so you can easily replace and profile it.

std::map is likely a tad slower for a small number of elements (but then, it doesn't really matter).
Answer: Map is O(log N), so not as fast as positional lookup in an array. But the exact results will depend on a lot of factors, and so the best approach is to interface with the container in a way that allows you to swap between implementation later on. That is, write a "lookup" function that can be efficiently implemented by any suitable container, to allow yourself to switch and compare speeds of different implementation.
Answer: Map's operator [] is O(log(n)), see wikipedia : http://en.wikipedia.org/wiki/Map_(C%2B%2B)
I think as you're looking often for symbols, using a map is certainly right. Maybe a hash map (std::unordered_map) could make your performance better.
Answer: If you're going to use a vector and go to the trouble of caching the most recent symbol look up result, you could do the same (cache the most recent look-up result) if your symbol table were implemented as a map (but there probably wouldn't be a whole lot of benefit to the cache in the case of using a map). With a map you'd have the additional advantage that any non-cached symbol look ups would be much more performant than searching in a vector (assuming that the vector isn't sorted - and keeping a vector sorted can be expensive if you have to do the sort more than once).
Take Neil's advice; map is generally a good data structure for a symbol table, but you need to make sure you're using it correctly (and not adding symbols accidentally).
Answer: You say: "If the variable, still using vector, is found the first time, I can store its exact integer position in the vector with it.".
You can do the same with the map: search the variable using find and store the iterator pointing to it instead of the position.
Answer: For looking up values, by a string key, map data type is the appropriate one, as mentioned by other users.
STL map implementations usually are implemented with self-balancing trees, like the red black tree data structure, and their operations take O(logn) time.
My advice is to wrap the table manipulation code in functions,
like table_has(name), table_put(name) and table_get(name).
That way you can change the inner symbol table representation easily if you experience
slow run time performance, plus you can embed in those routines cache functionality later.
Answer: A map will scale much better, which will be an important feature. However, don't forget that when using a map, you can (unlike a vector) take pointers and references. In this case, you could easily "cache" variables with a map just as validly as a vector. A map is almost certainly the right choice here.

C++ STL Map vs Vector speed


Low Voltage between Neutral and Ground wires in Dishwasher Junction Box

Question: My Bosch 800 series Dishwasher will not function. I plan on swapping the control module. In the junction box, at the terminals, I'm reading 120V between Hot and Ground, and between Hot and Neutral. Between Neutral and Ground, I am reading almost zero to 1V. Is this a normal reading between these two terminals, or should I consider swapping the junction box, as well?
Comment: Hello, and welcome to Home Improvement. One of our pros will answer more authoritatively, but I'm pretty sure that's what you should expect. And, props for [taking our tour](//diy.stackexchange.com/tour) before posting; few newbies do.
Comment: Have you checked the door switches? There is also going to be a thermal fuse that may be bad. What has you contemplating it is a control unit? (it certainly can be). The voltage you are measuring sounds good. You shouldn't see voltage between GND and NEUTRAL, but its LESS than a volt its most likely noise. Is there anything else connected to this same circuit?
Comment: Hi, thanks for the response. When I open the door and press ON, there is a very faint beep. That's why I thought the operating module/controller would be the most likely fix. The garbage disposal is also on the circuit.
Answer: Yes, because of voltage drop
If you've ever done a voltage drop calculation, let's say you want to run a 12A well pump load.  You do the calculations and it says you'll have 6 volts of voltage drop, so 114V.  OK.
Well, how does that happen?  There are TWO wires - hot and neutral.  Is the voltage drop shared across both?  Yes.  Each one drops 3 volts.
Well, how does "dropping" voltage on a neutral work?  Certainly the hot sags to 117V, no question there.  Obviously if the neutral sags to -3 volts, there'd still be 120 across hot and neutral, so that can't be it.   Actually, the neutral "drops" the other direction - it rises to +3 volts. So with neutral at 3V, and hot at 117, you have the expected 114V.
Why doesn't ground move also?  Voltage drop is proportional to current; that's literally what Ohm's Law is saying. E=IR.  Since there is no current on ground, it doesn't drop.
So you measure 3V between neutral and ground in that case.
It's rather like the small rod on a beam-type torque wrench.  Your strength is bending the big rod, but the small rod is unaffected and indicates your torque on the scale.
Answer: The voltage measurements are normal any reading from ~112 to 125 vac hot to neutral is normal throughout the US. A small voltage neutral to ground is also very common.  if the voltage gets above 2.5 volts I have seen switching supplies have problems. But your measurements would point to the controller not the junction box. Having a motor load like a garbage disposal on the same circuit as the dishwasher can create failures as the disposal motor creates large voltage spikes starting and stoping. Adding a surge suppressor to your dishwasher may extend the life of the electronics.
Answer: Yes a small induced voltage difference is often present, particularly with a flat cord where the ground and neutral are different distance from the hot.


Time to recruit UX research participants

Question: I'm conducting user interviews and wondering how long it takes to recruit research participants?  I need to recruit 20 participants with the only distinguishing requirement being that they have used an industry-specific (can't reveal) site that is popular.  I'm being asked how long it will take for recruitment and then conducting the interviews.
Answer: It's going to depend on how large your recruiting budget, potential participant pool, and incentives are. You can use tools like respondent.io to screen millions of people extremely quickly, but there will be a cost.
I'd suggest creating a screener survey that buries the target site in a list of other sites. Example:
Which sites have you visited in the last 5 years?

Google
Amazon
Home Depot
Target
Lowe's

Potential participants won't know whether you're looking to disqualify those who have been to one of the sites, or have not. It's important to root out "professional participants" who will say anything for money.
You can start by using your company's email and social channels to distribute the screener survey. If it's taking too long to find participants, then you can escalate to services like Respondent.
Answer: We allow 1 week for B2C participants and 3 weeks for B2B. However, whether you can actually find the specific criteria you are looking for depends on the incident rate (how many there are per population) and how you are going about finding them.
We use specialist third party recruiters for B2B (i.e. like SIS International (not an endorsement, an example) and they have pretty large databases.


Is it possible to retrieve MAC address of a host using Tor?

Question: I know that Tor is used for anonymity while browsing in the Internet. I heard that by using Tor, it is possible to hide my IP. But is it possible to hide my MAC address also?
Comment: It would help if you understood the TCP/IP or the OSI networking model. You would answer your own question. The MAC address is only seen by the next hop in the path. Most probably the router.
Answer: The MAC address is only visible on your local network. You don't need to hide it.
With Tor or without Tor, as soon as the packet reaches your default gateway, that computer sitting between you and the next network segment, your MAC cannot be seen anymore.
But if someone tries very hard to trace you, a special crafted website can get your MAC by exploiting your browser, executing some commands on your computer and get all kinds of information from the computer.
But this does not have anything to do with Tor nor no-Tor nor MAC address.
If you want to add another layer of security, try using Whonix Linux. It's a two-server solution running on virtual machines: the gateway and the workstation. The gateway connects to Tor, and creates a local network routing everything over Tor. The workstation only have access to the gateway, so even if someone exploits the workstation, he will see a local IP address, a virtual MAC, a virtual HDD, and no information on your physical hardware.
Answer: TLDR; It's possible to mask your MAC address, but it's still broadcast in plain text to anyone local to your network
It's not really possible to "hide" a MAC address.  The MAC address is used to determine where to deliver the actual packets, if you remove it from the packet, the router has no way of knowing where to deliver the packet.
Think of it like a paper letter.  If you remove or "hide" the address, how does the postman know where to deliver the letter?
Similarly, it's not really possible to hide an IP address.  The way tor accomplishes this is to forward the request and reply through several layers of encrypted communications.  The gamble is that any attacker won't control enough tor relays to be able to decrypt the entire message.  If you, as an attacker, controlled the whole tor network, you would be able to read any message passed between relays.
The same concept will protect your MAC address from anyone on the Tor network, or the website administrator.  It will not protect you from anyone on your local network.
Actually even without tor, your MAC address will not be leaked beyond your local network.  Your local router will perform NAT on any requests which will have the effect of not leaking your MAC address to the greater internet.  In TCP/IP, the MAC continually changes as it is rewritten by every hop it goes through.
Comment: The final destination will never see the MAC address of the originating computer, even without Tor or any effort what-so-ever by the user to "hide" the MAC address.  None the less, it's not possible to hide the MAC address from a user on a local network (technically, before the first hop, wherever that is).
Comment: @paj28, I've edited my answer to be a bit clearer
Comment: But it depends how you define the "hide".
For example you can easly change your mac address. (Thats how you could for example bypass the mac filtering.)
And you can use proxy or the tor system to "change"/"hide" your IP with a fake one.

Yes you need these addresses in the packets, but you can modify them a bit.
Comment: @Gerifield, yes, I address this within my post.  Tor will mask the IP/MAC address from the final destination, but it'll still be broadcast in plaintext to the first relay.
Comment: @ChrisMurray - which is what most people mean by "hide". So it's a bit misleading to start off saying "it's not possible..."
Comment: Even without NAT,  MAC addresses do not leave the link. As soon as the packet changes subnet, the MAC address is not available anymore.
Answer: It is not impossible. Theoretically it should not, but in practice it can:
http://samy.pl/mapxss/
<code>3. The XSS obtains the MAC address of the router via AJAX.
4. The MAC address is then sent to the malicious person. In the test case below, it's sent to me (not that I'm malicious!)
</code>
this works with the Verizon FiOS routers, but it may be possible to find ways to do it with other routers.
Comment: -1 This person is asking whether or not it's possible when using Tor. Tor browser blocks local connections, so this attack would not work.


What about performance in core data?

Question: I would like to write an application based on core data, but I don't know if it's worth, there will be several tables of a few or several thousand data.
What is the situation at the front?
Comment: This previous answer of mine might provide some guidence: http://stackoverflow.com/questions/5237943/creating-a-json-store-for-iphone/5249674#5249674
Answer: A few thousand records isn't that many in the grand scheme of things, and so is likely to be fine. Though without knowing exactly what you want to do with the data or what platform you're running it on, it's difficult to be sure.
Answer: The important thing to remember about Core Data is that it isn't primarily a persistence API i.e. one primarily concerned with getting data onto and off disk like SQL. It is primarily an API for creating the entire model layer for a Model-View-Controller (MVC) design app. As such, it provides a complete data management solution from persistence to object-graph management to integration with the UI.
Core Data is such a comprehensive solution that in Cocoa using bindings, it is possible to create entire apps without writing any custom code.
Any performance you might hypothetically lose in persistence operations with Core Data is almost always overshadowed by the performance gains of the object-graph management and UI integration.

What about performance in core data?


Pydev/OpenCV: Installation Errors

Question: I've a Mac (OS X 10.7.3 64 bit) and am working with OpenCV and Python.
I was able to install OpenCV using MacPorts with support for Python.
I installed the 2.7 Python interpreter, exported the site-packages to PYTHONPATH(this is where the location of my cv2.so and cv.py are).
I am able to run my OpenCV Python programs via the command line.
I installed Eclipse + PyDev, chose the same interpreter.
Now, in the Project properties for any project I create, I add the site-packages dir in the system libraries. If I save and run, I get the following error:

File
  "/Users/harishvenkatesan/Documents/Eclipseworkspace/helloworldpython/src/org/eclipse/python/standard.py",
  line 10, in <module>

import cv

File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/cv.py",
  line 1, in <module>

from cv2.cv import *

ImportError: dynamic module does not define init function (PyInit_cv2)

It seems like PyDev found the location alright, since from cv2.cv import * is the statement in cv.py. But I am not able to fix this error. I did a few searches online, but couldn't find any solutions.
Does anyone have an idea about this? Much appreciated! My Eclipse and everything else is 64-bit, so I am not sure if this is a 32-64 bit mismatch.
Answer: Instead of
import cv

I use
import cv2.cv as cv

and it works.
Hope it will work for you too :)

Pydev/OpenCV: Installation Errors


Help witha second-order nonlinear ODE

Question: I'm stuck with the following second-order nonlinear differential equation:
$$
\frac{Af'(x)\left(1+f'(x)^2\right)+(B+Ax)f''(x)}{\left(1+f'(x)^2\right)^{3/2}}=A+C
$$
where $f(x)$ is the function that I want to find, while $A$,$B$, and $C$ are constant parameters. I've been searching for an exact solution but I'm having a hard time dealing with it. Do you think that there is an exact solution for it or should I go for a numerical method instead? Thank you in advance.
Answer: In such cases involving expressions $\sqrt{1+g(x)^2}$ you can try to set $g(x)=\sinh(u(x))$ or $g(x)=\frac12(v(x)-\frac1{v(x)})$. Using the first variant gives
$$
A\tanh(u(x))+(B+Ax)\frac{u'}{\cosh^2(u(x))}=A+C
$$
The left side is now recognizable as a product derivative, leading to
$$
(Ax+B)\tanh(u(x))=(A+C)x+D.
$$
Now solve this for $f'(x)=\sinh(u(x))$. It is unlikely that the resulting expression is symbolically integrable.

Help witha second-order nonlinear ODE


Constants in general solution of a differential equation.

Question: Wherever a general solution to a first degree, first order differential equation has been given in my book, I've found that they use either ln|C| or C or $e^C$ as the constant of integration obtained. What's the catch? When to use which?
Comment: It's a matter of convenience. Pick the one that make the solution easier to work with. (Of course, you can only use $e^C$ if the constant must be positive.)
Answer: So said, they haven't the same value. Because the examples you give,they seem to come from a equation of this type:
$y'-y/x=0$.
It's very easy, a separable one: $\mathrm dy/\mathrm dx-y/x=0$; $\mathrm dy/y=\mathrm dx/x$
We can integrate both sides, leading to $\ln\vert y\vert+c_1=\ln\vert x\vert +c_2$ as solution. Because the constants are unknown (before the initial conditions are set), we can manipulate them and/or redefine them:
Stipulating $k=c_2-c_1$ we can write: $\ln\vert y\vert=\ln\vert x\vert+k$ Taking the exponential in both sides:
$y=\pm xe^k$ Now, defining $k_1=\pm e^k$, $y=k_1x$ (but, be careful: $k_1\ne 0$). So said, the constant of integration have diferent values in each of the cases. If you set the initial conditions, e.g. $y(1)=2$ it can be seen: $k_1=2$, $k=\ln2$ and plus sign for the first one.
Comment: You mean $y=\pm xe^k$, $k_1=\pm e^k$ when resolving the logarithms. Also need to add in the case $k_1=0$ from the initially excluded constant solution.
Comment: You are right and I was aware of this. I thought of an example using the form for the constants, the OP chose and allowing some inaccuracies to make clear the point of the question. I see now it's not a big problem solve it well.


Why six Trigonometric Ratios

Question: Why should we use six trigonometric ratios when all the three sides of a right angled triangle (opposite, adjacent and hypotenuse) are connected with the three rations sine, cosine and tangent?
what is the significance of inverses of these ratios(cosec, sec and cot)?
Comment: The "co" functions correspond to the trig function related to the coangle (if $\theta$, $\theta^{\prime}$ are the two (non-right) angles of the right triangle, $\theta^{\prime}$ is the co-angle of $\theta$).
Comment: Even if you don't use the $\tan(x/2)$ trick in the answer below you can relate all three sides with just *two* ratios. The third ratio can just be expressed in terms of the other two, for example $\tan(\theta) = \sin(\theta)/\cos(\theta).$ But what makes any three (or two) of the six possible ratios better than all the other three (or four)?
Answer: Short answer: there are three sides (adjacent $A$, hypotenuse $H$ and opposite $O$) we can choose in three unordered pairs or six ordered pairs, giving ratios such as $\sec x=\frac{H}{A}$ etc.
Long answer: You could argue only one trigonometric function is needed, $t:=\tan\frac{x}{2}$ so$$\sin x=\frac{2t}{1+t^2},\,\cos x=\frac{1-t^2}{1+t^2},\,\tan x=\frac{2t}{1-t^2}.$$Or you could argue it's convenient to name not only the above functions and their reciprocals, but also other functions such as $\operatorname{versin}x$ etc. (That link shows geometric significances of all these functions, albeit from the perspective of a circle in which we embed a right-angled triangle of hypotenuse $1$.) History has settled on a compromise where a few functions are widely memorised while others aren't (e.g. a mathematician might not know off the top of their head that $\operatorname{exsec}x:=\sec x-1=\frac{2t^2}{1-t^2}$). But history turned out that way because of how often each function is useful.
Answer: It is not particularly helpful to have $6$ trigonometric functions when you only consider them in the context of right-angled triangles. If you simply want to compute the lengths of the sides of a triangle, and the angles in between them, then $\sin$, $\cos$, and $\tan$ are all you need. However, the reciprocal functions have nice geometric interpretations, one of which is given here:

The 'co-functions' have another interpretation. $\cos \theta$ is sine of the co-angle of $\theta$. So, for example, in a right-angled triangle with angles $\{60,30,90\}$, $\cos 30 = \sin 60$, since $60$ is the co-angle of $30$ (the two angles have to add up to 90).
(Incidentally, this is how the function tangent got its name. It is the length of the line segment that is tangent to a point $P$, with the end points of the line segment being the $x$-axis and $P$.)
That being said, we could do just fine without the reciprocal functions. 3Blue1Brown calls them tattoos on math.
Comment: Nice graphic, +1
Comment: @rogerl: Thank you!
Answer: Sine, cosine, and tangent are used most often. But sometimes the other three are more convenient or more appropriate. They also show up as solutions to differential equations, physics problems, statistics problems, astronomy problems, economics problems, etc.
Bye the way. There used to be more than 6 trig functions.
Comment: I would argue that there still are more than six trig functions. Some are just better known than others. People still refer to the haversine formula, for example.

Why six Trigonometric Ratios


Phaser Tiled map importing

Question: How can I be sure that the tileset used in making a Tiled map remains as a multiple of 2, since this is a requirement of phaser when loading JSON tiled maps? I have tileset images which I got for free and they are not exactly up to phaser specs to be used.
Answer: You're probably referring to this:
    // May be fractional values
    var rowCount = (imageHeight - this.tileMargin * 2 + this.tileSpacing) / (this.tileHeight + this.tileSpacing);
    var colCount = (imageWidth - this.tileMargin * 2 + this.tileSpacing) / (this.tileWidth + this.tileSpacing);

    if (rowCount % 1 !== 0 || colCount % 1 !== 0)
    {
        console.warn("Phaser.Tileset - " + this.name + " image tile area is not an even multiple of tile size");
    }

It's not a requirement, it's only a console warning
If you inspect the code carefully (rowCount % 1), what it's trying to do is actually check that the tileset dimensions is divisible by the tile size, and not about "even numbers", i.e. divisible by 2

So for example, if your tile size was 32x32 and your tileset image was 64x64, that's ok (32 divides into 64), but if the tileset image was 65x65, that's 1px left over and 65 doesn't divide evenly into 32.
Comment: Right, and thanks for your answer. However it does prevent the map from being loaded.
Comment: I believe the WebGL 1.0 specs do require that images be power-of-2, so it might be that way for compatibility.

Phaser Tiled map importing


Utility that will set an alarm off when too much memory has been consumed?

Question: Does anyone know of a utility that can send the user an alert when too much system memory has been consumed?   So that they know to close out a few programs, and close a few browser tabs?  I found one on Google but it only monitors individual programs and not memory as a whole.
Comment: Why do you care that memory is being used?  Idle memory serves no purpose.
Comment: I care about it because if I  absent-mindedly use too much RAM I have revert to using the swap file and it makes things run slow.  At least of I had an alert about it before this happens I could close out some programs before using the slow swap file.
Comment: What kind of person closed this question as off topic? I find it very much on topic! Even 10 years later.
Answer: You have to:

Set up a task-scheduler task that sends an email, or shows some warning etc.
Set up a an alert-type "data collector" in Windows "Performance monitor"
Set this alert to trigger the task you created in step #1

I wrote a blog post some time ago with more detailed instructions if you need them.
Answer: http://ss64.com/nt/logman.html
Create an alert which monitors memory usage.
Answer: Windows has a built-in warning when eviction pressure gets too high (i.e., it's extremely tight on memory). It's a little notification in the system tray that warns you're low on memory and demanding more, and suggests closing some applications.
There's a subtle difference between being low on memory (which is not necessarily bad) and high eviction pressure (applications causing a large number of page faults, which is bad).
Personally, if this is a regular enough issue that the time it takes to close programs or tabs is an issue, I'd put some more memory in the machine. Memory is usually pretty cheap these days, and is quite often the best dollar-per-perceived-speed improvement you can do to most computers.
Comment: I love the concept of "eviction pressure".  If Microsoft maintains a number somewhere, is it possible to use?  Is there something in performance monitor to attach to?
Comment: @leeand00 The issue is the programs always have any memory that isn't actively in use paged out; only recently used memory is kept paged in. It's very difficult to define a threshold at which "memory is tight". You can page out 30% of an app and not notice, or page out a different 30% and have it slow to a crawl. Is the 4GB limitation due to 32-bit OS, or due to hardware?
Comment: I would do that but my machine is maxed out at 4GB.  I do a little bit of Virtualization, and that's probably why I keep running out of RAM and reverting to the page file.  But I figured if I had some sort of an alert I would be able to close the programs before the programs get loaded to the page file. (mainly this is for speed and productivity)
Comment: Hardware, I'm using Windows 7 64-bit Ultimate on my laptop an ASUS G51VX (Best Buy) only supports two 2GB modules of RAM, and I have them both filled in.


translated inline does not work

Question: Can't use inline translation tool on my webpage. Its working fine in backed. I checked on the frontent if Translate Inline>"Enabled for Fronted"` is enabled, but it wasn't. when I translating something it does not change.
Answer: Make sure you are using Mozila, crome have some problem.
After edit it , please flush cache and check it.

translated inline does not work


Understanding reduced suspension of $S^1$

Question: I know this is just $S^2$. To see it, I use the CW structure of $S^1$ x $S^1$ , consisting of one 0-cell, two 1-cells and a 2-cell. Then since the reduced suspension is the cartesian product identifying the wedge (or smash product) , what just remains is the 0.cell and the 2-cell...This is very theoretical and I don't visualize what is going on.
I imagine a torus with two circular threads being pulled to a point and then?
If anyone has thought of this and is convinced by some visualization, I'll thank his idea....
Comment: For me, the most intuitive view of it is - the generic loop in a loop space. That is, something that starts as a trivial loop, sweeps some amount of loops and then returns to the trivial state again.
Answer: Here is a way to see this. After you collapse one circle, you end up with a sphere with two points attached. Then, the remaining circle (1-cell) is the image of the path connecting this two points. If you first glue the two points and then collapse the whole segmnent between them, is the same as collapsing the segment to a point from the very beginning. But collapsing an arc on a sphere does nothing, so you get a sphere. Alternatively, instead of attaching the two points, connect them with an external path. Then make the two points collide, and you get a bucket of a 2-sphere and a cirle. Then you have to collapse the circle to the point, since this is the second 1 cell, and you end up with a 2-sphere.
Answer: I like to think about it this way: Start with a circle and cross with an interval rather than another circle, to get a cylinder. You're next going to identify the two ends of the cylinder and a path connecting them. If you can't picture that immediately, start by pinching off each end of the cylinder, to get a sphere, with a line connecting the two poles you just created. (This is the unreduced suspension.) Now shrink that line to a single point, which still gives you a sphere.


Zigzags and Collinear Lattice Points

Question: A "zigzag" is an infinite planar path formed by starting at $(0,0)$ and then repeatedly moving $1$ unit up or $1$ unit right. A lattice point is a point with integral coordinates. Given a zigzag $Z$ and a positive integer $n$, must $Z$ contain (at least) $n$ collinear lattice points?
Comment: What do you mean by "integral coordinates"? I'm not super familiar with how lattices work, but I'd like to try to help!
Comment: Are you looking for a hint or an answer?  How far have you gotten on this question?
Comment: I will take whatever I am offered, with thanks. I have not gotten far, but I have experimented with small values of n, seeking to find, for a given n, the furthest one can walk without meeting the condition. That is, I am looking to see whether this  leads to a shape or convex hull of a possible maximal region that FAILS to have n collinear points. Of course, two sides of this are parts of the positive x and y axes.
Comment: For example, for the easiest case with n = 2, the region is just the point (0, 0), as a step either left or right from any point yields two collinear points.  For n = 3, the maximal region is the unit square.
Comment: Integer = "whole number" but positive, negative, or zero; integral is adjective form.
Answer: In two dimensions it is fairly cheap. First observe (as it has been done already) that the bad path (if it exists) can cross any line with rational slope only finitely many times, which implies that eventually it is contained in an arbitrarily small angle $A_\varepsilon$ around some direction $\theta$ (i.e., $|y-\theta x|\le\varepsilon x$; WLOG the escape slope $\theta\le 1$, otherwise just swap $x$ and $y$). Now pick up a big $P$ and choose some $p\in\{1,\dots,P\},q\ge 0$ such that $|q-\theta p|\le 1/P$ (Dirichlet approximation theorem). Then for large $N$, the path has $\ge N/2$ points in the sector $A_{1/(pP)}\cap B(0,N)$ but for any point $(x,y)$ in this sector, we have $$|py-qx|\le p|y-\theta x|+|q-\theta p|x\le pN/(pP)+N/P\le 2N/P,$$ so there are at least $P/8$ points with the same value of $py-qx$, which are on the same line.
Answer: This paper shows that the answer to your question is yes. Specifically, look to lemma $(1)$ and lemma $(2)$, which are:

Let $m>1, \{p_i\}$ be a sequence in $\mathbb{Z}^m$ and $S$ be a finite subset of $\mathbb{Z}^m$ such that $p_{i+1}-p_i \in S$ for all $i$. Then for each positive integer $N$, there are $N$ integers $j$ and a rational hyperplane $H$ such that $p_j \in H$.

Let $m>1$ and $S$ be a finite subset of $\mathbb{Z}^m$. Let $N \in \mathbb{Z}^+$ be given. Then there is an $N' \in \mathbb{Z}^+$ such that if $\{p_i\}$ is a finite sequence in $\mathbb{Z}^m$ of length $N'$ and $p_{i+1}-p_i \in S$ for all $i < N'$, then there are $N$ distinct integers $j$ and a hyperplane $H$ such that $p_j \in H$.

For your question, $m = 2$, $S = \{(0, 1), (1, 0) \}$, and the hyperplane $H$ is a line. Let the $i$th point in the zigzag be given by $p_i$. Assume that $\theta = (\theta_x, \theta_y)$ is a cluster point of $\frac{p_i}{||p_i||}$, which will be a point on the unit circle in the first quadrant for our specific case.
The author defines $H$ to be the line through the origin and $\theta$. Then $H'$ and $H''$ are lines going through the origin with rational slopes forming angles with $H$ that are less than a specified angle, on opposite sides of $H$. Since a subsequence of points have $\frac{p_i}{||p_i||}$ converging to $\theta$, there are infinitely many choices for $p_J$ between $H'$ and $H''$. For each such $p_J$, there is a $p_j$ on the opposite side of $H'$ or $H''$, which means that the path traced by $p_i$ crosses $H'$ and $H''$ infinitely often. Since $H'$ and $H''$ have rational slopes, a finite number of translates of them cover all the points in $\mathbb{Z}^2$ within a distance of $1$. Then, one of these translates contains $p_i$ for infinitely many $i$.
There are more details in the paper, but what they basically show first is that there are all but a finite number of points within a region bounded by two lines which are a small angle (explicitly defined in the paper) from $H$. Then there must be a line going through $n$ points in this region. In this picture, $H$ is the middle line, and all the points in the path but a finite number of lattice points will be within the green and purple lines. Then they show that there must also be at least $n$ collinear points within this region.
Comment: The claim about $H'$ and $H''$ is false. Just take a sequence where all the angles converge to $\theta$, not just a subsequence, (which is possible). Then the points are eventually all between $H'$ and $H''$ and so the path can only cross the lines finitely many times. (Nonetheless, it is true that a path with no n collinear points can only cross any line with rational slope finitely many times.) It is also easy to construct a path which does not have infinitely many points between any two parallel lines (just follow closely a curve with positive second derivative).
Comment: @DavidHartley Hmm, I see your points. To be honest, I glossed over a lot of the details in the paper because of the length and complexity. The paper obviously explains it better than I could, so I will take another look at the paper and try to improve my answer.
Comment: Also, I think if a curve with positive second derivatives is followed, it would look nearly like a line at some section of points, so it would be even easier to show that there are $n$ collinear points.
Comment: @VarunVejalla You do not need two parallel lines, just an arbitrarily small angle around the limiting direction. I posted the details as an answer (too long for a comment box), but the credit and bounty should really be yours (though I cannot control that) :-)
Comment: @fedja Yes, it seems I have misunderstood the paper. I have editted my answer to showcase that.
Comment: *there are an infinite number of points within a region bounded by two lines which are a small angle (explicitly defined in the paper) from H. Then there must be a line going through n points in this region.* This passage is still incorrect. as written. Just having "infinitely many points" is not enough to derive the conclusion. I'm using a stronger condition that *all but finitely many* points are there though a fixed portion independent of the angle or even going to $0$ much slower than the angle itself would suffice.

Zigzags and Collinear Lattice Points