Check if field is modified in mongoose's post hook for function findOneAndUpdate - express

In the controller I'm incrementing a field with findOneAndUpdate. The increment is not necessarily always executed, which depends on whether the condition for a update query has been met.
If the field has been incremented tho, an another model should updated as well. So, I was thinking to use:
schema.post('findOneAndUpdate', function(err) {
pseudo-code:
if (field is incremented)
anotherModel.update()
});
The problem is that I don't seem to be able to determine if the field has been modified.
Self reference (this) points to a funny object of considerable size, (unlike in e.g. middleware functions for 'save'), so I don't see much other options to determine if field is modified.
Any ideas?

The argument passed to the callback for findOneAndUpdate's post middleware is the matched document to be updated and not an error as common in the node callback pattern. Within the callback, this is the query object returned from the findOneAndUpdate.
schema.post('findOneAndUpdate', function(doc) {...});
Also note that if you want the updated document rather than original document that matches the query you must specify the new option in the query:
findOneAndUpdate(QUERY, UPDATE, {new: true});

Related

Assigning vs setting params in React Navigation

Is it a proper way to change React-Navigation's params' value by assignment:
navigation.state.params.number = 123;
instead of setting it:
navigation.setParams({ number: 123 });
I noticed that the first way is synchronous, meaning that I can console.log(number) the next line and get the assigned new value, whereas the second way is asynchronous meaning that if I console.log(number) on the next line, I will get the old value.
The reason why I need the value to be accessible on the next line is that state.params holds the search input in my app and I call action creator to perform a search on the next line, therefore it must be updated before the call.
So, the question, again. Is it a proper way to change the value this way?
If you need the param value that you assigned on the next line then you can just used the variable that you assigned to param directly rather than reading it from the params.
let someValue = 'Foo';
navigation.setParams({ Bar: someValue });
console.log(someValue);
setParams is used for setting the param for the screen and it updates the navigationState with the parameter you set. If you set it directly it will not work as it should be. If you need the parameter you set right after you set it I think you might have a not so ideal logic going on.

What is the difference between an Idempotent and a Deterministic function?

Are idempotent and deterministic functions both just functions that return the same result given the same inputs?
Or is there a distinction that I'm missing?
(And if there is a distinction, could you please help me understand what it is)
In more simple terms:
Pure deterministic function: The output is based entirely, and only, on the input values and nothing else: there is no other (hidden) input or state that it relies on to generate its output. There are no side-effects or other output.
Impure deterministic function: As with a deterministic function that is a pure function: the output is based entirely, and only, on the input values and nothing else: there is no other (hidden) input or state that it relies on to generate its output - however there is other output (side-effects).
Idempotency: The practical definition is that you can safely call the same function multiple times without fear of negative side-effects. More formally: there are no changes of state between subsequent identical calls.
Idempotency does not imply determinacy (as a function can alter state on the first call while being idempotent on subsequent calls), but all pure deterministic functions are inherently idempotent (as there is no internal state to persist between calls). Impure deterministic functions are not necessarily idempotent.
Pure deterministic
Impure deterministic
Pure Nondeterministic
Impure Nondeterministic
Idempotent
Input
Only parameter arguments (incl. this)
Only parameter arguments (incl. this)
Parameter arguments and hidden state
Parameter arguments and hidden state
Any
Output
Only return value
Return value or side-effects
Only return value
Return value or side-effects
Any
Side-effects
None
Yes
None
Yes
After 1st call: Maybe.After 2nd call: None
SQL Example
UCASE
CREATE TABLE
GETDATE
DROP TABLE
C# Example
String.IndexOf
DateTime.Now
Directory.Create(String)Footnote1
Footnote1 - Directory.Create(String) is idempotent because if the directory already exists it doesn't raise an error, instead it returns a new DirectoryInfo instance pointing to the specified extant filesystem directory (instead of creating the filesystem directory first and then returning a new DirectoryInfo instance pointing to it) - this is just like how Win32's CreateFile can be used to open an existing file.
A temporary note on non-scalar parameters, this, and mutating input arguments:
(I'm currently unsure how instance methods in OOP languages (with their hidden this parameter) can be categorized as pure/impure or deterministic or not - especially when it comes to mutating the the target of this - so I've asked the experts in CS.SE to help me come to an answer - once I've got a satisfactory answer there I'll update this answer).
A note on Exceptions
Many (most?) programming languages today treat thrown exceptions as either a separate "kind" of return (i.e. "return to nearest catch") or as an explicit side-effect (often due to how that language's runtime works). However, as far as this answer is concerned, a given function's ability to throw an exception does not alter its pure/impure/deterministic/non-deterministic label - ditto idempotency (in fact: throwing is often how idempotency is implemented in the first place e.g. a function can avoid causing any side-effects simply by throwing right-before it makes those state changes - but alternatively it could simply return too.).
So, for our CS-theoretical purposes, if a given function can throw an exception then you can consider the exception as simply part of that function's output. What does matter is if the exception is thrown deterministically or not, and if (e.g. List<T>.get(int index) deterministically throws if index < 0).
Note that things are very different for functions that catch exceptions, however.
Determinacy of Pure Functions
For example, in SQL UCASE(val), or in C#/.NET String.IndexOf are both deterministic because the output depends only on the input. Note that in instance methods (such as IndexOf) the instance object (i.e. the hidden this parameter) counts as input, even though it's "hidden":
"foo".IndexOf("o") == 1 // first cal
"foo".IndexOf("o") == 1 // second call
// the third call will also be == 1
Whereas in SQL NOW() or in C#/.NET DateTime.UtcNow is not deterministic because the output changes even though the input remains the same (note that property getters in .NET are equivalent to a method that accepts no parameters besides the implicit this parameter):
DateTime.UtcNow == 2016-10-27 18:10:01 // first call
DateTime.UtcNow == 2016-10-27 18:10:02 // second call
Idempotency
A good example in .NET is the Dispose() method: See Should IDisposable.Dispose() implementations be idempotent?
a Dispose method should be callable multiple times without throwing an exception.
So if a parent component X makes an initial call to foo.Dispose() then it will invoke the disposal operation and X can now consider foo to be disposed. Execution/control then passes to another component Y which also then tries to dispose of foo, after Y calls foo.Dispose() it too can expect foo to be disposed (which it is), even though X already disposed it. This means Y does not need to check to see if foo is already disposed, saving the developer time - and also eliminating bugs where calling Dispose a second time might throw an exception, for example.
Another (general) example is in REST: the RFC for HTTP1.1 states that GET, HEAD, PUT, and DELETE are idempotent, but POST is not ( https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html )
Methods can also have the property of "idempotence" in that (aside from error or expiration issues) the side-effects of N > 0 identical requests is the same as for a single request. The methods GET, HEAD, PUT and DELETE share this property. Also, the methods OPTIONS and TRACE SHOULD NOT have side effects, and so are inherently idempotent.
So if you use DELETE then:
Client->Server: DELETE /foo/bar
// `foo/bar` is now deleted
Server->Client: 200 OK
Client->Server DELETE /foo/bar
// foo/bar` is already deleted, so there's nothing to do, but inform the client that foo/bar doesn't exist
Server->Client: 404 Not Found
// the client asks again:
Client->Server: DELETE /foo/bar
// foo/bar` is already deleted, so there's nothing to do, but inform the client that foo/bar doesn't exist
Server->Client: 404 Not Found
So you see in the above example that DELETE is idempotent in that the state of the server did not change between the last two DELETE requests, but it is not deterministic because the server returned 200 for the first request but 404 for the second request.
A deterministic function is just a function in the mathematical sense. Given the same input, you always get the same output. On the other hand, an idempotent function is a function which satisfies the identity
f(f(x)) = f(x)
As a simple example. If UCase() is a function that converts a string to an upper case string, then clearly UCase(Ucase(s)) = UCase(s).
Idempotent functions are a subset of all functions.
A deterministic function will return the same result for the same inputs, regardless of how many times you call it.
An idempotent function may NOT return the same result (it will return the result in the same form but the value could be different, see http example below). It only guarantees that it will have no side effects. In other words it will not change anything.
For example, the GET verb is meant to be idempotent in HTTP protocol. If you call "~/employees/1" it will return the info for employee with ID of 1 in a specific format. It should never change anything but simply return the employee information. If you call it 10, 100 or so times, the returned format will always be the same. However, by no means can it be deterministic. Maybe if you call it the second time, the employee info has changed or perhaps the employee no longer even exists. But never should it have side effects or return the result in a different format.
My Opinion
Idempotent is a weird word but knowing the origin can be very helpful, idem meaning same and potent meaning power. In other words it means having the same power which clearly doesn't mean no side effects so not sure where that comes from. A classic example of There are only two hard things in computer science, cache invalidation and naming things. Why couldn't they just use read-only? Oh wait, they wanted to sound extra smart, perhaps? Perhaps like cyclomatic complexity?

ORMLite's iterator forgets all the data after hasNext() == false

code sample:
//...
CloseableIterator<Order> iterator = dao.iterator();
iterator.first(); // Object
iterator.current(); // Object
iterator.hasNext(); // false (only 1 record in table "Order")
iterator.current(); // null (?!)
iterator.first(); // null (?!!)
Also, iterator.previous() returns null too (if more than 1 record, ofc).
How to forbid ORMLite's SelectIterator to forget my data after calling hasNext() on the last record?..
According to the source code of ORMLite, it is a normal undocumented unchangeable behavior.
Just ran into this myself. We're using ORMLite on Android and were able to use methods available on the DatabaseResults member, available by calling:
iterator.getRawResults()
You'll have to cast it to the appropriate type before being able to do things like safely check count etc. (depending on whether or not they are available in your particular implementation)

Custom parameters in Pentaho dashboards

Custom parameters in a CDE/CTools dashboard are great for defaulting initial values of parameters, e.g. setting a date parameter to today. i.e. the parameter looks like:
function() {
// some code
return val
}
However there is an issue with them. The first time you access a "custom parameter" in code, it is a function not a string. So you have to use:
paramName()
To get its value.
Once the end user selects a value then you have to use
paramName
This is really awkward in complicated dashboards with lots of prompts. Is there a better way this can be done? (Perhaps there is something in javascript I'm missing to help here?)
OK, there is a solution, but I dont like it!
First; Move all the init code into named procedures e.g.
function monthInit() {
return "june";
}
Then in the custom parameter for month, just say:
monthInit();
That way the custom parameter is always a string, and never starts off as a function.
Not ideal though because then all your init code is in a separate bit of js.

Check field errors in word references with VSTO

How can I check if some fields in my word have errors? I have a large document that contains many references to other chapters or images. When those chapters or images are missing in the document, the fields containing those references will display Error! Reference Source Not Found instead of the reference.
The problem is, that I need to create an algorithm that will check for those reference errors, no matter what the locale and language of the file is. The problem is, that this field error is localized in the language of the system of the user who uses the word.
How can I do this? Is there any property on Field that can be used to check if the source is available?
Currently, I check for errors in the fields by using the result text of the field:
Int32 fieldErrors = 0;
foreach (Word.Field field in doc.Fields)
{
field.Update();
if (field.Result.Text.StartsWith("Error!"))
++fieldErrors;
}
Unfortunately, this will only work in english word instances.
In the documentation for Field types it is seen that a Field instance has an Update() method that returns a bool. The documentation does not state what the semantic meaning of the return value is, however, by doing a short empirical study I found that the method returns true if the Update() succeeded and false if the update did not succeed. This means that in order to find fields with errors you can do something like:
var fieldsWithErrors = new List<Field>();
foreach (Field field in document.Fields)
{
if(!field.Update())
fieldsWithErrors.Add(field);
}
... or shorter with LINQ:
var fieldsWithErrors = document.Fields.Cast<Field>().Where(field => !field.Update()).ToList();
Another (and faster) approach would be to use the Update() method exposed by the Fields collection.
var indexOfFirstError = document.Fields.Update();
... the method returns the index of the first field with an error. If no errors are found, the method returns 0.
For complete documentation please see the MSDN references:
Field.Update()
Fields.Update()
Field members
Fields members