Can I access a folder right after it's created - file

This maybe because I'm used to backend and async in js but if I type this in rust..
fs::create_dir("dir1")
Then use
fs::File::create("dir1/file1.txt")
To create a file in the new folder right after,
is it bound to go wrong, should the program sleep for a second to make sure the directory has already been created on the environment?

To answer this, No it is not bound to go wrong.
And also to add in general, sleeping to ensure that something is being done is not that of a good idea.
In the case you provided, fs::create_dir is sync and it returns a Result type. So before you create file inside dir1 make sure you check the result is ok. And also check the result for creating file is ok.
fn create_file(){
if fs::create_dir("dir1").is_ok() {
if fs::File::create("dir1/file1.txt").is_ok() {
println!("File created inside dir1");
}
}
}
Also, while inside rust you can take the gurantee that once directory is created it stays there but this won't always be case. For example, a system might have a background job that keeps deleting the directory inside some place. Hopefully, you don't always have to worry about all these extreme cases but just so you know ;)

Related

How do I find the context in which document.write operates. Can you solve the riddle

Basically i have these two lines of code written right after each other.:
console.log(typeof (noAdsCallback));
document.write('<sc' + 'ript type="text/javascript">console.log(typeof(noAdsCallback));</scr' + 'ipt>');
The first one logs function, the second logs undefined.
Of course it's a bit trickier than that. So here is the set-up in a nutshell:
I have a so called waterfall of ad-providers. That means, I try to load some Ads, by writing (using document.write) some special tags (given to me by my ad-provider).
If the provider doesn't find an ad for me, they send back a javascript-snippet which looks like this:
if (typeof(window.noAdsCallback) === "function") noAdsCallback();
This function essentially writes the tags of the next provider, which does the same as the first one until I reach the end of the list.
This system actually works fine, doing exactly what I want it to do. Both lines given in the beginning log function.
Except if I use Google as an ad-provider. There is one thing Google does differently, which seems to mess everything up.
In Google, I cannot define a fallback-JavaScript-snippet. All I can do is provide a fallback-url. So this fallback-url (since it's loaded inside an iframe inside an iframe inside...) sends a postMessage to the top, which then calls the same noAdsCallback() method. And this too, works just fine. The message is received and the right method executed. However, already the two lines already give different results, i.e. function and undefined respectively
The next provider then fails to find the noAdsCallback() Method, when it returns, because it uses document.write to try to execute it. Somehow, the context was lost.
First hint: It works fine (i.e. both lines log function) in Chrome, but it doesn't work in FF or IE.
Second hint: It works fine, as long as context never switches, but if communication runs at any point through messaging, it get's confused.
Third hint: Using the fantastic postscribe library as mentioned below, actually solves the problem, but introduces new ones somewhere else.
Fourth hint: Debugging the window.name, before using document.write, gives the correct name, so I'm not in a random iFrame.
Finishing thoughts. I know, i know: DON'T USE DOCUMENT WRITE!! I know that. But since Adproviders use it all the time, I am forced to use it to, otherwise I get this:
Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.
In Fact, right now I'm using postscribe (https://github.com/krux/postscribe) and it works like a charm, except for one lousey provider. And the workauround solution would be, to use document.write only for this lousy provider and postscribe for all the others. But i would really like to find out what the root of the problem is.
Any Ideas, much appreciated.
I think I understood it now. Long story short: DON'T USE DOCUMENT.WRITE :)
Try postscribe, if you have to.
So in hindsight it is quite obvious, because really, anywhere you read about document.write() it says, that write() clears the whole document. And I just didn't get it, because I never saw it happening and every ad is using it, like the whole time. Plus, it seemed to work fine on Chrome. So what's going on??
Well here is what happens. As long as the document is open, which basically means while it is being written, document.write() just appends to the stream, and doesn't clear the document. And as long as I used document.write(), to append foreign ad-scripts (which may and will contain document.write()), the page does not close, hence the document stays open.
This is the reason, why adding Google to my waterfall, posed a problem: Google puts everything in iframes. So the page containing the waterfall model just sees the iframe and says: "well as far as I'm concerned, I'm done" and closes the document, while in fact, Google is still at it.
Afterwards, Google didn't find an ad, sends a postMessage to the main page, causing the next provider to be used. Who then uses document.write() and clears everything.
Everything? Not everything. Remember, it still used to work when I used Chrome? The reason for that is, Chrome just clears the HTML but leaves the Javascript intact. So on Chrome, my Javascript-waterfall worked fine, because all the JS-objects where still in place. All other browsers cleared it.
So that's it. Probably noone's gonna read it, but if you do, USE POSTSCRIBE! Now that I finally really understood document.write() and document.open() and document.close() I'm a big fan.

Save to .settings file diffrence between 2 diffrent ways of saving

I was reading about the .settings file on msdn and I noticed they give 2 examples of how to set the value of a item in the settings. Now my question is what is the real diffrence between the 2 and when would you use one instead of the other, since to me they seem pretty mutch the same.
To Write and Persist User Settings at Run Time
Access the user setting and assign it a new value, as shown in the following example:
Properties.Settings.Default.myColor = Color.AliceBlue;
If you want to persist changes to user settings between application sessions, call the Save method, as shown in the following code:
Properties.Settings.Default.Save();
The first statement updates the value of the setting in memory. The second statement updates the persisted value in the user.config file on the disk. That second statement is required to get the value back when you restart the program.
It is very, very important to realize that these two statements must be separate and never be written close together in your code. Keeping them close is harakiri-code. Settings tend to implement unsubtle features in your code, making it operate differently. Which isn't always perfectly tested. What you strongly want to avoid is persisting a setting value that subsequently crashes your program.
That's the harakiri angle, if you saved that value then it is highly likely that the program will immediately crash again when the user restarts it. Or in other words, your program will never run correctly again.
The Save() call must be made when you have a reasonable guarantee that nothing bad happened when the new setting value was used. It belongs at the end of your Main() method. Only reached when the program terminated normally.

Mercurial pre-merge hook

Is there a way to do some checks before allowing a merge in Mercurial?
I have found the pre-update hook and have a script that runs before an update is allowed, by adding the following to ~/.hg/hgrc:
[hooks]
pre-update = ~/hg_pre_update.sh
But I'd like to run the check before allowing a merge as well, and currently it just allows the merge to go through without running my checks.
Background
In case there are alternative ways to solve the problem...
We have been having a number of problems with 'lost' edits under Mercurial. I've tracked down most of them now to the same underlying cause: someone has vim edit sessions open while either they or someone else does a hg update or merge. The editor warns the file has changed externally, the user ignores the warning and saves their changes.
When these changes are committed, for Mercurial there is nothing controversial. The user has simply reverted all the changes brought in with the last update and put in their own changes.
Some time later, we notice the code has gone walkabouts. Cue assorted insults flung the way of mercurial...
Set vim to autoreload changes if no local changes where done. (otherwise ask, or force a merge)
that's how I avoid such issues in any editor...
Sorry just worked out there is a pre-merge hook that works just the same as pre-update. I tried it before asking the question, but now just looking at my hgrc I realise I put the script being called for that hook to ~/hg_pre_merge.sh which doesn't exist.
I can't find the existence of pre-merge documented anywhere but still feeling like a bit of a muppet now.

How to reset an object's security descriptor to the default?

As part of a testing utility I am creating some registry keys and applying a specific security descriptor to them. Later on I want to reset it to the "default" security descriptor (i.e. inherited from the parent). What is the proper way to do this?
I can't save and restore the original security descriptor because this utility may be run multiple times before the tester will want to reset it. I guess I could save it to a temp file or registry value, but I would prefer a more elegant solution.
So, do I have to do something with the parent's security descriptor or what? I'm having a hard time figuring out what to do.
Almost forgot to mention I'm doing this in C.
UPDATE: I should have added that I'll also be doing this with files (and possibly other securable objects), so it would be nice if there were a generic way to work with security descriptors themselves instead of using object-specific things like RegSaveKey. I imagine it would require working with the security descriptor of the parent, so it would be great if I could do something like the following:
BOOL WINAPI GetDefaultChildSecurityDescriptorFromParent(LPSECURITY_DESCRIPTOR Parent, LPSECURITY_DESCRIPTOR* Child);
I'm just not sure how to do it programmatically. You can accomplish this in the security descriptor editor by using the check box to inherit entries from the parent, so obviously it is possible somehow.
I recommend saving keys to a file using RegSavekey. To restore the key use RegLoadKey.
The easiest way I can think to do this would be to read in the structure that needs to be defaulted... then delete it and recreate it - passing NULL to force the defaults.
I hate to answer my own question, but I found a snippet of documentation on the matter (the DACL is really the only thing I am concerned with). Looks like I have to get the DACL of the parent and create a new DACL that includes all the inheritable ACEs in it. I was hoping it would be simpler than that, but it's not too bad.

Aborting a change to a node from a module

I'm building a module for Drupal 6 (what it does isn't wildly important; I've spent a long time looking for other solutions to this problem and rolling my own is definitely the simplest), and I've run into something of a conceptual road-block.
Much like the uploadpath module, I'm creating a directory based on (via a replacement pattern) properties of a node. For instance, creating a node with the "assignmentindex" contenttype called "Foobar", my module will create a folder sites/default/files/assignmentindex/Foobar.
The problem comes (predictably) during update events, when the target directory already exists, or can't be created for some other strange reason (the only one I can dream up right now is running out of inodes, but I'm sure there are other failure conditions). Obviously, to avoid losing data, the original folder needs to be left alone, but that breaks the association between the directory and the node. Thus, I see 3 different possibilities:
Rolling back the whole node
Rolling back just the changed title
Not rolling anything back (but showing an error)
First question is which of these is best? Rolling back the whole node wipes away a potentially huge amount of work, rolling back just the title is confusing and rolling back nothing means that the names are out of sync. My current preference is for just rolling back the title, but I'd really appreciate thoughts on this.
The second question is: how? I've already switched the relevant $op to presave (from update) so that the original node is available via
$old_node = node_load($node->id);
and to roll back a single field, can potentially just do
$node->title = $old_node-title;
but this seems sub-optimal, and I'm curious as to whether there's a better way of achieving this.
Sorry for the long question, and many thanks in advance for your help.
As an alternative to those discussed above: if you do not care about imported/programmatically created nodes, you could add a validation handler on the node form submission. Validation has access to both the new and old nodes, and can reject the submission to the user in a more standard fashion.
function custom_form_alter(&$form, &$form_state, $form_id) {
if ($form['#id'] == 'node-form') {
$form['#validate'][] = '_custom_node_form_validate';
}
}
function _custom_node_form_validate(&$form, &$form_state) {
$old_node = $form['#node'];
$new_node = $form_state['values'];
}

Resources