setTimeout doesn't work JavaScript "style undefined"

Question: I want to fade in 4 div boxes, one by one.
In css they have the opacity = 0.
Here my JavaScript code:
function fadeIn() {
    var box = new Array(
        document.getElementById('skill1'),
        document.getElementById('skill2'),
        document.getElementById('skill3'),
        document.getElementById('skill4')
    );

    var pagePosition = window.pageYOffset;

    if (pagePosition >= 1000) {
        for (var i = 0; i < box.length; i++) {
            setTimeout(function(i) {
                box[i].style.opacity = "1";
            }, i * 500);
        }
    }
}

Well, the function has to start if you scroll the page to the position 1000px and called in the body-tag:
Without the setTimeout it works, but with this function the console says:
Uncaught TypeError: Cannot read property 'style' of undefined

I'm a beginner and want to understand JS, so please don't provide an answer using jQuery.
Comment: Welcome to [so]. It appears your question can be answered here: [**JavaScript closure inside loops – simple practical example**](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example). Please let me know if it solves your issue. Thanks!
Answer: By the time your your timeout runs, the loop has finished processing, so i will always be the last iteration. You need a closure:
for(var i = 0; i < box.length; i++) {
  (function(index) {
    setTimeout(function() {
        box[index].style.opacity = "1";
    }, index*500);
  })(i)
}

Comment: @JamesThorpe -- It'll work..but I'll change it for clarity. Edit: Oh - the `timeout` function, yeah, that was wrong :D
Comment: @JamesThorpe I think a different variable name would make the operation clearer, but there's actually two `i` variables in tyme's original version - when it enters the function scope, it discards the outside `i` naming to just use `i` as a local argument.
Comment: Also worth noting that `i` would actually be one more than the number of items in the `box` array, which is what was causing the `undefined` error.
Comment: @Katana314 exactly, which would again have been `undefined` as it wouldn't be passed by the timeout
Comment: Why would `i` be one more? I thought `undefined` was coming from the `i` in the function being passed to the `timeout`
Comment: @tymeJV Ah yes, that too.  Without the `i` in the timeout function, it would be using the `i` from the outer scope, which the for loop would have incremented to beyond the end of the array, so `box[i]` would be undefined.  There's too much wrong here :)
Comment: Actually, Thorpe appears correct; I hadn't noticed `i` was being passed as an argument again inside the setTimeout scope. I was referring to the first function. The example looks fine now.
Comment: `i` would not increment beyond the array! The array length is `4` - `i` starts at `0` - up by `1` until not less than `4`. `4 < 4 == false`
Comment: If the length is 4, the highest index is 3, ie `box[0]` to `box[3]` are fine, but after the loop is finished (and by the time the timeout ran), `i` would be 4, and `box[4]` is `undefined`
Answer: The problem is the scope. When anonymous function executes inside timeout i variable has the last value of the i in the iteration. There are two solutions:
1) Use an IIFE:
for (var i = 0; i < box.length; i++) {
  (function (i) {
    setTimeout(function (i) {
      box[i].style.opacity = "1";
    }, i * 500);
  })(i);
}

for (var i = 0; i < 5; i++) {
  (function(i) {
    setTimeout(function() {
      console.log(i);//prints out 0 1 2 3 4
    }, i * 500)
  })(i);
}

2) Using let:
 for (let i = 0; i < box.length; i++) {

    setTimeout(function (i) {
        box[i].style.opacity = "1";
    }, i * 500);
}

"use strict";
for (let i = 0; i < 5; i++) {
  setTimeout(function() {
    console.log(i)
  }, i * 500)
}

The let statement declares a block scope local variable, optionally
  initializing it to a value.

Keep in mind let is feature fo ecmaScript 6.
Comment: Even if `set i` is an ES6 feature I haven't read yet, I think you linked to the wrong MDN article; it's detailing a `Set` object


tensor cannot be accessed , present in another function or code block

Question: i am implementing post processing code for yolov3 in tensorflow using tf.keras. This code block is used to compute the mAP metrics during validation after each epoch. But while i am able to run the post processing code standalone with random data , i am getting an error while i am calling this function inside the mAP metrics code which is called via model.fit function.
the code look like this:
...
...
for i in tf.range(num_images):
        final_boxes , final_probs , final_class = filter_predictions(adjusted_bbox_delta[i] , det_probs[i] , det_class[i] , num_classes)
        keep_index = [index for index in range(len(final_probs)) if final_probs[index] > filter_threshold]
        final_boxes = tf.reshape([final_boxes[index] for index in keep_index] , (len(keep_index) , 4))
        final_probs = tf.reshape([final_probs[index] for index in keep_index] , (len(keep_index) , 1))
        final_class = tf.reshape([final_class[index] for index in keep_index] , (len(keep_index) , 1))
        # generate the eval bounding boxes (used to calculate metrics.)
        pred_box_objects.append(gen_box_objects(final_boxes, final_probs , final_class))

this is where i am calling the filter_predictions function ,
adjusted_box_delta.shape = [batch_size , 10647 , 4]
det_probs.shape = [batch_size , 1067 , 1]
det_class.shape = [batch_size , 1067 , 1]

below is the code where i am facing the problem :
def filter_predictions(localizations , det_probs_this_inst , det_class_this_inst , num_classes):
    # det_probs_this_inst.shape : 10647 , localizations.shape : (10647 , 4)
    max_prediction = 100
    if max_prediction < len(det_probs_this_inst):
        pred_order = tf.argsort(det_probs_this_inst)[ : -max_prediction-1:-1]
        locs = tf.gather(localizations , pred_order , axis = 0)
        probs = tf.gather(det_probs_this_inst , pred_order)
        cls_idx = tf.gather(det_class_this_inst , pred_order)

        final_boxes = []
        final_probs = []
        final_class = []
        for c in range(num_classes):
            index_per_class = tf.where(cls_idx == c)
            keep = nms(tf.squeeze(tf.gather(locs , index_per_class , axis = 0)) , tf.squeeze(tf.gather(probs , index_per_class)))
            for i in range(tf.shape(keep)[0]):
                if tf.cast(keep[i] , tf.bool):
                    final_boxes.append(locs[index_per_class[i]])
                    final_probs.append(probs[index_per_class[i]])
                    final_class.append(c)

        return [final_boxes , final_probs , final_class]

the error i am getting :
Traceback (most recent call last):
  File "train.py", line 142, in <module>
    main()
  File "train.py", line 120, in main
    train(input_size,
  File "train.py", line 81, in train
    face_detector.fit(train_data_generator ,
  File "/home/yogeesh/yogeesh/tf2/lib/python3.8/site-packages/keras/engine/training.py", line 1215, in fit
    val_logs = self.evaluate(
  File "/home/yogeesh/yogeesh/tf2/lib/python3.8/site-packages/keras/engine/training.py", line 1501, in evaluate
    tmp_logs = self.test_function(iterator)
  File "/home/yogeesh/yogeesh/tf2/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py", line 885, in __call__
    result = self._call(*args, **kwds)
  File "/home/yogeesh/yogeesh/tf2/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py", line 933, in _call
    self._initialize(args, kwds, add_initializers_to=initializers)
  File "/home/yogeesh/yogeesh/tf2/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py", line 759, in _initialize
    self._stateful_fn._get_concrete_function_internal_garbage_collected(  # pylint: disable=protected-access
  File "/home/yogeesh/yogeesh/tf2/lib/python3.8/site-packages/tensorflow/python/eager/function.py", line 3066, in _get_concrete_function_internal_garbage_collected
    graph_function, _ = self._maybe_define_function(args, kwargs)
  File "/home/yogeesh/yogeesh/tf2/lib/python3.8/site-packages/tensorflow/python/eager/function.py", line 3463, in _maybe_define_function
    graph_function = self._create_graph_function(args, kwargs)
  File "/home/yogeesh/yogeesh/tf2/lib/python3.8/site-packages/tensorflow/python/eager/function.py", line 3298, in _create_graph_function
    func_graph_module.func_graph_from_py_func(
  File "/home/yogeesh/yogeesh/tf2/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py", line 1007, in func_graph_from_py_func
    func_outputs = python_func(*func_args, **func_kwargs)
  File "/home/yogeesh/yogeesh/tf2/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py", line 668, in wrapped_fn
    out = weak_wrapped_fn().__wrapped__(*args, **kwds)
  File "/home/yogeesh/yogeesh/tf2/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py", line 994, in wrapper
    raise e.ag_error_metadata.to_exception(e)
tensorflow.python.framework.errors_impl.InaccessibleTensorError: in user code:

    /home/yogeesh/yogeesh/tf2/lib/python3.8/site-packages/keras/engine/training.py:1330 test_function  *
        return step_function(self, iterator)
    /home/yogeesh/yogeesh/object_detection/Yolov3_tf2/metrics/mAP.py:102 update_state  *
        box_objects = tf_postprocessing.post_process(predictions ,
    /home/yogeesh/yogeesh/object_detection/Yolov3_tf2/postprocessing/tf_postprocessing.py:148 post_process  *
        final_boxes , final_probs , final_class = filter_predictions(adjusted_bbox_delta[i] , det_probs[i] , det_class[i] , num_classes)
    /home/yogeesh/yogeesh/object_detection/Yolov3_tf2/postprocessing/tf_postprocessing.py:57 filter_predictions  *
        if max_prediction < len(det_probs_this_inst):
    /home/yogeesh/yogeesh/tf2/lib/python3.8/site-packages/tensorflow/python/autograph/operators/control_flow.py:1172 if_stmt
        _tf_if_stmt(cond, body, orelse, get_state, set_state, symbol_names, nouts)
    /home/yogeesh/yogeesh/tf2/lib/python3.8/site-packages/tensorflow/python/autograph/operators/control_flow.py:1218 _tf_if_stmt
        final_cond_vars = control_flow_ops.cond(
    /home/yogeesh/yogeesh/tf2/lib/python3.8/site-packages/tensorflow/python/util/dispatch.py:206 wrapper
        return target(*args, **kwargs)
    /home/yogeesh/yogeesh/tf2/lib/python3.8/site-packages/tensorflow/python/util/deprecation.py:549 new_func
        return func(*args, **kwargs)
    /home/yogeesh/yogeesh/tf2/lib/python3.8/site-packages/tensorflow/python/ops/control_flow_ops.py:1254 cond
        return cond_v2.cond_v2(pred, true_fn, false_fn, name)
    /home/yogeesh/yogeesh/tf2/lib/python3.8/site-packages/tensorflow/python/ops/cond_v2.py:82 cond_v2
        true_graph = func_graph_module.func_graph_from_py_func(
    /home/yogeesh/yogeesh/tf2/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py:1011 func_graph_from_py_func
        func_outputs = nest.map_structure(convert, func_outputs,
    /home/yogeesh/yogeesh/tf2/lib/python3.8/site-packages/tensorflow/python/util/nest.py:869 map_structure
        structure[0], [func(*x) for x in entries],
    /home/yogeesh/yogeesh/tf2/lib/python3.8/site-packages/tensorflow/python/util/nest.py:869 <listcomp>
        structure[0], [func(*x) for x in entries],
    /home/yogeesh/yogeesh/tf2/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py:971 convert
        x = deps_ctx.mark_as_return(x)
    /home/yogeesh/yogeesh/tf2/lib/python3.8/site-packages/tensorflow/python/framework/auto_control_deps.py:231 mark_as_return
        tensor = array_ops.identity(tensor)
    /home/yogeesh/yogeesh/tf2/lib/python3.8/site-packages/tensorflow/python/util/dispatch.py:206 wrapper
        return target(*args, **kwargs)
    /home/yogeesh/yogeesh/tf2/lib/python3.8/site-packages/tensorflow/python/ops/array_ops.py:289 identity
        ret = gen_array_ops.identity(input, name=name)
    /home/yogeesh/yogeesh/tf2/lib/python3.8/site-packages/tensorflow/python/ops/gen_array_ops.py:3945 identity
        _, _, _op, _outputs = _op_def_library._apply_op_helper(
    /home/yogeesh/yogeesh/tf2/lib/python3.8/site-packages/tensorflow/python/framework/op_def_library.py:748 _apply_op_helper
        op = g._create_op_internal(op_type_name, inputs, dtypes=None,
    /home/yogeesh/yogeesh/tf2/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py:597 _create_op_internal
        inp = self.capture(inp)
    /home/yogeesh/yogeesh/tf2/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py:642 capture
        raise errors.InaccessibleTensorError(

    InaccessibleTensorError: The tensor 'Tensor("while/cond/while_1/cond/strided_slice_1/GatherV2_1:0", shape=(1, 4), dtype=float32)' cannot be accessed here: it is defined in another function or code block. Use return values, explicit Python locals or TensorFlow collections to access it. Defined in: FuncGraph(name=while_cond_while_1_cond_true_12011, id=140480887970688); accessed from: FuncGraph(name=while_cond_true_11525, id=140480887162192).

2021-10-22 04:37:19.739693: W tensorflow/core/kernels/data/generator_dataset_op.cc:107] Error occurred when finalizing GeneratorDataset iterator: Failed precondition: Python interpreter state is not initialized. The process may be terminated.
     [[{{node PyFunc}}]]

i wonder if the problem is somehow caused due to for loop that i am using for num_images.
please share some insight.
Answer: i am posting my solution here incase if someone is also stuck under same situation.
So basically the problem is that, tensorflow under graph mode is not very compatible with python list, so for each input signature a new graph fucntion is created, hence it is not recommended to have mutable python objects like lists which might have different shape for each fucntion call to be used in the fucntion signature (parameters and their shape).
The error explains it all, as the list is getting expanded or might have a different shape the signatue is also changed and hence a new graph func is created.
Solution :
its better to use tensor objects , and one must use list like structure then recommended use is to use tf.TensorArray object.
For more details , refer to this github issue : https://github.com/tensorflow/tensorflow/issues/52617


What happens to RAII objects after a process forks?

Question: Under Unix / Linux, what happens to my active RAII objects upon forking? Will there be double deletions?
What is with copy construction and -assignment? How to make sure nothing bad happens?
Comment: `fork(2)` is a fundamental Unix system call. You would use it ... every time you need a new process.
Comment: @OliverStutz: E.g. to create daemons or to run processes and capture their input-, output- and error-channel
Comment: Why would you use fork, C++ is much better with Threads.
Comment: @OliverStutz, to avoid all the problems (and thus many crashes) that threads come with. It's way more difficult to make sure your program works with threads than with a "simple" `fork()`, except maybe if you have RAII objects which manage external resources...
Comment: @AlexisWilke How do you can know that a complex program will work well with fork?
Comment: @curiousguy, by testing it? :-) Frankly, in comparison with threads, it's very easy to make a software work with `fork()`. You do not have all the memory problems and other shared resource issues you get with threads. The one thing not to do is have threads running when you `fork()`.
Comment: @AlexisWilke Library code might use threads to do some operations in the background. If there is no user callback called from another thread, the library might not expose any thread to the user. The library only needs to protect its own shared resources.
Answer: fork(2) creates a full copy of the process, including all of its memory. Yes, destructors of automatic objects will run twice - in the parent process and in the child process, in separate virtual memory spaces. Nothing "bad" happens (unless of course, you deduct money from an account in a destructor), you just need to be aware of the fact.
Comment: For memory only objects, or even objects holding a simple file descriptor, yes. Things are simple. Memory is duplicated with a copy-on-write and descriptors with a `dup()`. However, a destructor may do way more destructive things like do a `shutdown()` on a socket. That is NOT safe even across parent/child.
Comment: @Sahsahae I was talking about the destructor calling `shutdown()` on your socket. You can always write a test: Open a socket in the parent, create a child (`fork()`), then do a shutdown in either one, the other's socket is dead. An unfortunate _feature_. Also, there is the `CLOEXE` flag which can be used to automatically close a descriptor on an `execve()`, for security reasons. However, if you just `fork()`, that won't matter.
Comment: @AlexisWilke indeed, you're correct. `shutdown` unlike `close` operates on the actual `socket` and not `sockfd`, something I overlooked, having never used this function before, as `close` already does "everything" you usually want. I can see how `shutdown` can be useful for multiprocess servers though, where a primary process is in control of most sensitive resources, like `sockets`, not `sockfd`s. Where it isn't necessary, a `close` is better choice for this exact reason. In hindsight, quite ironic how theory can catch up to reality like this.
Comment: @AlexisWilke sockets are no different from any other file descriptor in *nix systems and it makes no sense to say that it is destructive when all non-special file descriptors are simply copied. Closest to what you claim that I can think of is child inheriting stdin/stdout/stderr, which is true, you have to redirect these if you don't want them interfering with parent, but even this is not even close to anything destructive, they simply take same input and provide same output through the same file descriptors.
Answer: Principally, it is no problem to use these functions in C++, but you have to be aware of what data is shared and how.
Consider that upon fork(), the new process gets a complete copy of the parent's memory (using copy-on-write). Memory is state, therefore
you have two independent processes that must leave a clean state behind.
Now, as long as you stay within the bounds of the memory given to you, you should not have any problem at all:
#include <iostream>
#include <unistd.h>

class Foo {
public:
    Foo ()  { std::cout << "Foo():" << this << std::endl; }
    ~Foo()  { std::cout << "~Foo():" << this << std::endl; }

    Foo (Foo const &) {
        std::cout << "Foo::Foo():" << this << std::endl;
    }

    Foo& operator= (Foo const &) {
        std::cout << "Foo::operator=():" << this<< std::endl;
        return *this;
    }
};

int main () {
    Foo foo;
    int pid = fork();
    if (pid > 0) {
        // We are parent.
        int childExitStatus;
        waitpid(pid, &childExitStatus, 0); // wait until child exits
    } else if (pid == 0) {
        // We are the new process.
    } else {
        // fork() failed.
    }
}

Above program will print roughly:
Foo():0xbfb8b26f
~Foo():0xbfb8b26f
~Foo():0xbfb8b26f

No copy-construction or copy-assignment happens, the OS will make bitwise copies.
The addresses are the same because they are not physical addresses, but pointers into each process' virtual memory space.
It becomes more difficult when the two instances share information, e.g. an opened file that must be flushed and closed before exiting:
#include <iostream>
#include <fstream>

int main () {
    std::ofstream of ("meh");
    srand(clock());
    int pid = fork();
    if (pid > 0) {
        // We are parent.
        sleep(rand()%3);
        of << "parent" << std::endl;
        int childExitStatus;
        waitpid(pid, &childExitStatus, 0); // wait until child exits
    } else if (pid == 0) {
        // We are the new process.
        sleep(rand()%3);
        of << "child" << std::endl;
    } else {
        // fork() failed.
    }
}

This may print
parent

or
child
parent

or something else.
Problem being that the two instances do not enough to coordinate their access to the same file, and you don't know the implementation details of std::ofstream.
(Possible) solutions can be found under the terms "Interprocess Communication" or "IPC", the most nearby one would be waitpid():
#include <unistd.h>
#include <sys/wait.h>

int main () {
    pid_t pid = fork();
    if (pid > 0) {
        int childExitStatus;
        waitpid(pid, &childExitStatus, 0); // wait until child exits
    } else if (pid == 0) {
        ...
    } else {
        // fork() failed.
    }
}

The most simple solution would be to ensure that each process only uses its own virtual memory, and nothing else.
The other solution is a Linux specific one: Ensure that the sub-process does no clean up. The operating system will make a raw, non-RAII cleanup of all acquired memory and close all open files without flushing them.
This can be useful if you are using fork() with exec() to run another process:
#include <unistd.h>
#include <sys/wait.h>

int main () {
    pid_t pid = fork();
    if (pid > 0) {
        // We are parent.
        int childExitStatus;
        waitpid(pid, &childExitStatus, 0);
    } else if (pid == 0) {
        // We are the new process.
        execlp("echo", "echo", "hello, exec", (char*)0);
        // only here if exec failed
    } else {
        // fork() failed.
    }
}

Another way to just exit without triggering any more destructors is the exit() function. I generally advice to not use in C++, but when forking, it has its place.

References:

http://www.yolinux.com/TUTORIALS/ForkExecProcesses.html
man pages
Comment: I think your waitpid example would be better if it still showed the file being written to, but now in a predictable order. I'm not sure what the exec code is showing; was there supposed to be some other object that does or doesn't get cleaned up?
Comment: All you are showing here is a very simple synchronization problem. This can very easily be resolved with a lock (a mutex in a thread, because you would get similar problems in a thread... and probably a semaphore between the parent and in a forked child.) Either way has nothing to do with RAII per say. That is, **the point of RAII is the destructor of the class** and not using various things such as a file while the parent and the child are running.
Comment: @AlexisWilke: Are you suggesting to keep a lock _around_ a resoure-full object, never mind how long the resource-full object is alive? Or, are you suggesting to make all resource-full classes threading-aware, just in case _someone_ may _somewhen_ use an instance in a threading context? I don't understand how this, as a general solution, is not premature pessimization.
Comment: If you want to write to a file in an orderly manner you need synchronization if more than one process has access to the file. In that specific case you can lock the file. That's what good log libraries do. You can have any number of processes sending logs simultaneously, and to get proper looking logs you (1) lock the file, (2) write your line of log, (3) unlock the file, and this is not specific to RAII.
Comment: @AlexisWilke: No, this is not specific to RAII. But ordering problems and doubled _effects_ (like accessing or modifying something a second time when this is not allowed) can follow from RAII, which is the point of the question ... Not sure what you are up to.
Answer: The currently accepted answer shows a synchronization problem which frankly has nothing to do with what problems RAII can really cause. That is, whether you use RAII or not, you will have synchronization problems between parent and child. Heck, if you run the same process in two different consoles, you have the exact same synchronization problem! (i.e. no fork() involved in your program, just your program running twice in parallel.)
To resolve synchronization problems, you may use a semaphore. See sema_open(3) and related functions. Note that a thread would generate the exact same synchronization problems. Only you can use a mutex to synchronize multiple threads and in most cases a mutex is much faster than a semaphore..
So where you do get a problem with RAII is when you use it to hold on what I call an external resource, although all external resources are not affected the same way. I have had the problem in two circumstances and I will show both here.
Do not shutdown() a socket
Say you have your own socket class. In the destructor, you do a shutdown. After all, once you are done, you can as well send a message to the other end of the socket saying you are done with the connection:
class my_socket
{
public:
    my_socket(char * addr)
    {
        socket_ = socket(s)
        ...bind, connect...
    }

    ~my_socket()
    {
        if(_socket != -1)
        {
            shutdown(socket_, SHUT_RDWR);
            close(socket_);
        }
    }

private:
    int socket_ = -1;
};

When you use this RAII class, the shutdown() function affects the socket in the parent AND the child. That means both, the parent and the child cannot read nor write to that socket anymore. Here I suppose that the child does not use the socket at all (and thus I have absolutely no synchronization problems,) but when the child dies, the RAII class wakes up and the destructor gets called. At that point it shutdowns the socket which becomes unusable.
{
    my_socket soc("127.0.0.1:1234");

    // do something with soc in parent
    ...

    pid_t const pid(fork());
    if(pid == 0)
    {
        int status(0);
        waitpid(pid, &status, 0);
    }
    else if(pid > 0)
    {
        // the fork() "duplicated" all memory (with copy-on-write for most)
        // and duplicated all descriptors (see dup(2)) which is why
        // calling 'close(s)' is perfectly safe in the child process.

        // child does some work
        ...

        // here 'soc' calls my_socket::~my_socket()
        return;
    }
    else
    {
        // fork did not work
        ...
    }

    // here my_socket::~my_socket() was called in child and
    // the socket was shutdown -- therefore it cannot be used
    // anymore!

    // do more work in parent, but cannot use 'soc'
    // (which is probably not the wanted behavior!)
    ...
}

Avoid using socket in parent and child
Another possibility, still with a socket (although you could have the same effect with a pipe or some other mechanism used to communicate externally,) is to end up sending a "BYE" command twice. This is actually very close to being a synchronization problem, though, but in this case, that synchronization happens in the RAII object when it gets destroyed.
Say for example that you create a socket and manage it in an object. Whenever the object gets destroyed, you want to tell the other side by sending a "BYE" command:
class communicator
{
public:
    communicator()
    {
        socket_ = socket();
        ...bind, connect...
    }

    ~communicator()
    {
        write(socket_, "BYE\n", 4);
        // shutdown(socket_); -- now we know not to do that!
        close(socket_);
    }

private
    int socket_ = -1;
};

In this case, the other end receives the "BYE" command and closes the connection. Now the parent cannot communicate using that socket since it got closed by the other end!
This is very similar to what phresnel talks about with his ofstream example. Only, it is not an easy to fix synchronization. The order in which you write the "BYE\n" or another command to the socket won't change the fact that in the end the socket gets closed from the other side (i.e. synchronization can be achieved using an inter-process lock, whereas, that "BYE" command is similar to the shutdown() command, it stops the communication in its track!)
A Solution
For the shutdown() it was easy enough, we just do not call the function. That being said, maybe you still wanted to have the shutdown() happen in the parent, just not in the child.
There are several ways to fix the problem, one of them is to memorize the pid and use it to know whether these destructive function calls should be called or not. There is a possible fix:
class communicator
{
    communicator()
        : pid_(getpid())
    {
        socket_ = socket();
        ...bind, connect...
    }

    ~communicator()
    {
        if(socket_ != -1)
        {
            if(pid_ == getpid())
            {
                write(socket_, "BYE\n", 4);
                shutdown(socket_, SHUT_RDWR);
            }
            close(socket_);
        }
    }

 private:
     pid_t pid_;
     int   socket_;
 };

Here we do the write() and shutdown() only if we are in the parent.
Notice that the child can (and is expected to) do the close() on the socket descriptor since the fork() called dup() on all the descriptors so the child has a different file descriptor to each file it holds.
Another Security Guard
Now there may be way more complicated cases where an RAII object is created way up in a parent and the child will call the destructor of that RAII object anyway. As mentioned by roemcke, calling _exit() is probably the safest thing to do (exit() works in most cases, but it can have unwanted side effects in the parent, at the same time, exit() may be required for the child to end cleanly--i.e. delete tmpfile() it created!). In other words, instead of using return, call _exit().
pid_t r(fork());
if(r == 0)
{
    try
    {
        ...child do work here...
    }
    catch(...)
    {
        // you probably want to log a message here...
    }
    _exit(0); // prevent stack unfolding and calls to atexit() functions
    /* NOT REACHED */
}

This is anyway much safer just because you probably do not want the child to return in the "parent's code" where many other things could happen. Not just stack unfolding. (i.e. continuing a for() loop that the child is not supposed to continue...)
The _exit() function does not return, so destructors of objects defined on the stack do not get called. The try/catch is very important here because the _exit() is not going to be called if the child raises an exception, although it should call the terminate() function which also won't destroy all the heap allocated objects, it calls the terminate() function after it unfolded the stack and thus probably called all your RAII destructors... and again not what you would expect.
The difference between exit() and _exit() is that the former calls you atexit() functions. You relatively rarely need to do that in the child or the parent. At least, I never had any strange side effect. However, some libraries do make use of the atexit() without consideration of the possibility a fork() gets called. One way to protect yourself in an atexit() function is to record the PID of the process which requires the atexit() function. If when the function gets called the PID doesn't match, then you just return and do nothing else.
pid_t cleanup_pid = -1;
void cleanup()
{
    if(cleanup_pid != getpid())
    {
        return;
    }

    ... do your clean up here ...
}

void some_function_requiring_cleanup()
{
    if(cleanup_pid != getpid())
    {
        cleanup_pid = getpid();
        atexit(cleanup);
    }
    ... do work requiring cleanup ...
}

Obviously, the number of libraries that use atexit() and do it right is probably very close to 0. So... you should avoid such libraries.
Remember that if you call execve() or _exit(), the cleanup will not occur. So in case of a tmpfile() call in the child + _exit(), that temporary file will not get deleted automatically...
Comment: I do answer the RAII question: "Will there be double deletions?" Which is also the title of the post. I mention the fact that all memory and descriptors get duplicated (second code sample,) which should be enough to know that everything will look the same in the child, at least at the start... As for objects allocated on the heap, they should make use of an `std::shared_ptr<>()`. That means they are guaranteed to be freed at some point. So the problem is to avoid the stack unfolding and `exit()` does that...
Comment: Calling `exit` in the child is incorrect and has caused bugs with severe security consequences. In general, you have no way to know what `atexit` handlers libraries might have registered and what they might do if invoked by the child and then again by the parent.
Comment: @AlexisWilke The recommended way to terminate a child process is `_exit` if you're not going to call an `exec` function (or that function fails).
Comment: @AlexisWilke Unfortunately, there are always going to be restrictions on what the child can do because you are inheriting an unknown context from libraries and the like. The child can't rely on exit handlers because it has no way to know what they're going to do. There are lots of ways around this, depending on what you're trying to do.
Comment: The synchronization problem lies therein where destructors are guaranteed by C++ to execute, and there is no way around it, except wrapping instances as dynamically allocated objects. I don't really like to overengineer all my resource-full objects towards using non-standard functions, when the problem lies outside in application code that does not want to get their threading right. There are not only sockets that impose problems. It could also be a fancy HTML printing library, or a smart handle for a DirectPhysics wrapper on Windows.
Comment: In essence, your answer is not really all too different from mine. Both of us just gave examples. And _both_ of us mention the use of exit() to cancel clean up. And, just as a side note: Not all heap objects belong into a `shared_ptr`. Copyable PIMPL classes for example should use a `unique_ptr` for their impl-pointer, in order to force its implementor to write proper copy-assignment and -construction.
Comment: @phresnel Ah! You do mention `exit()`! I missed it because it does not appear in your sample code... Yeah, allocated object should use some kind of smart pointer, some people prefer `unique_ptr<>()` for stack allocated objects too. Another thing I did not mention, [threads and `fork()` do not mix well](http://www.linuxprogrammingblog.com/threads-and-fork-think-twice-before-using-them) but that was not part of the question...
Comment: @DavidSchwartz, then maybe those libraries should not be used? One aspect of highly secure programming (say rockets for people or bombs) is to rewrite everything yourself so you have full control over each piece of code and you avoid problems such as the `atexit()`. However, most of the Unix software I know of will call `exit()` in the child process.
Comment: @AlexisWilke I think you're suggesting learning the wrong lesson. Sure, I agree, libraries like that shouldn't be used. But we only found that out by going through some very painful bugs with very serious security consequences. The lesson to learn is not to do things whose effects you can't know at the time you choose to do them, and calling `exit` in the child falls in that category. It's trivially avoidable. So why risk a repeat of past disasters?
Comment: @DavidSchwartz, the only safe way I can think of would be to do an `execve()`. But I don't yet see what you would propose...
Comment: @DavidSchwartz What about the cleanup the child needs? With `_exit()` you are not going to get the `tmpfile()` deleted when the child exits... Maybe a less problematic bug than a big security issue that `atexit()` can create. But overall, it's not really that much more of a solution.
Comment: "`exit()` may be required for the child to end cleanly" Maybe. But many uses of `fork()` are for the end goal of calling an `execX` function anyway, so you may as well consider these system resources created under the hood by libraries will be lost most of the time because `atexit` "destructors" will not run.
Answer: Unless you know what you are doing, the child process should always call _exit() after it has done its stuff:
pid_t pid = fork()
if (pid == 0)
{
   do_some_stuff(); // Make sure this doesn't throw anything
   _exit(0);
}

The underscore is important. Do not call exit() in child process, it flushes stream buffers to disk (or wherever the filedescriptor is pointing), and you will end up with things written twice.
Comment: tho `man 2 _exit`: `[...] Whether it flushes standard I/O buffers and removes temporary files created with  tmp‐
       file(3)  is  implementation-dependent.[...]`
Comment: @phresnel, it's not just files. Actually closing file descriptors in the child is not a problem at all. Certain other problems, though, such as shutting down a socket have generally unwanted consequences.
Comment: Note that `Make sure it does not throw` could be changed with `try { do_some_stuff(); } catch(...) {} _exit(0);`. You may or may not catch things like SEGV, but it should still be pretty safe, generally speaking.
Comment: @AlexisWilke: SEGV is not an exception you can `catch` in C++. There are libraries that can produce that, though.


Checar se o valor de um objeto de um certa classe foi mudado

Question: Quero que quando um valor for mudado dentro de um objeto de certa classe, outro mude também.
Exemplo:

class minhaClasse{
  constructor(valor1, valor2){
    this.valor1 = valor1
    this.valor2 = valor2
    this.valores = {
      valor1: this.valor1,
      valor2: this.valor2
    }
  }
}

var meuObjeto = new minhaClasse(2,4)
console.log(meuObjeto.valor1, meuObjeto.valores)

meuObjeto.valor1++ // ou meuObjeto.valor1 = 3
//log esperado => 3 {"valor1": 3, "valor2": 4}
console.log(meuObjeto.valor1, meuObjeto.valores)
Answer: Podes usar getters para fazer isso. Esses valores de this.valores podem ser um ponteiro protegidos de escrita (read-only) dos valores this.valor1 e this.valor2.
Podes fazer isso assim:

class minhaClasse {
  constructor(valor1, valor2) {
    this.valor1 = valor1
    this.valor2 = valor2
    const self = this;

    this.valores = {
      get valor1() {
        return self.valor1;
      },
      get valor2() {
        return self.valor2;
      }
    }
  }
}

var meuObjeto = new minhaClasse(2, 4)
console.log(meuObjeto.valor1, meuObjeto.valores)

meuObjeto.valor1++; // ou meuObjeto.valor1 = 3
// log esperado 3 {"valor1": 3, "valor2": 4}
console.log(meuObjeto.valor1, meuObjeto.valores)
meuObjeto.valores.valor1 = 200;
console.log(meuObjeto.valores); // dá  {"valor1": 3, "valor2": 4}
Comment: @LuísHNrique [ambas ao mesmo tempo!](https://stackoverflow.com/a/63148485/2256325). Pois, getters é a maneira mais simples e como escrevi na resposta esses valores não podem ser mudados se configurados da maneira correta.
Comment: Acabaram de me responder no StackOverflow gringo, responderam a mesma coisa que você. De qualquer jeito, muito obrigado!
Comment: eu tinha tentado usar `get valor1(){ return this.valor1 }`, não tinha pensado em criar uma variável pro `this`


Windows Server Backup - managing multiple targets

Question: I have Windows Server Backup connected to 2x NAS devices (via iSCSI), each one is situated in a different building for resilience.
I'd like to backup from WSB to both targets. WSB supports multiple targets, however the MS recommendation is to rotate the backup targets by taking one physical disk offsite, then subsequently switching them around periodically. Presumably suitable for USB disks rather than fixed network attached targets.
Instead, I'd obviously like to back up to both at the same time, but the above article suggests this isn't supported. An acceptable compromise might be to back up to each target alternately.
The above article states;

To force a backup to be saved to a particular disk, you can detach or disable all other disks in the backup series.

Perhaps to achieve my goal, I could create a scheduled task that runs a script which takes one target offline (in disk management) and brings the other one back online.
Although possibly an acceptable solution, the above is somewhat clunky.
Is there a better way?
Please do not suggest alternative products. My question is specific to Windows Server Backup and I would like to find the most robust possible solution within this limitation.
Answer: I found a solution using the wbadmin command line tool.
You can schedule multiple instances of execution at different times or create a batch file to execute them in sequence.
e.g.:
wbadmin start backup -backupTarget:<driveLetter>: -include:<filea and folders to include> -allCritical -systemState -vssFull < C:\Users\Administrator\Documents\Setup\Backup\do_backup2.ans > C:\Users\Administrator\Documents\Setup\Backup\do_backup2.log 2>nul

See also wbadmin start backup -?
Erman
Comment: you can find the backups in the windows server backup gui and restore them from gui too
Comment: Thank you this is excellent. I'm going to test this and report back here.
Comment: Please remember to mark as answer if this can help to answer your question.


CSS not work after applying ajax

Question: I have a problem with css after applying ajax.
I have an exposed form that I stylized.
Before applying ajax it is:
id="edit-field-price-value-min"
After applying it changed to
id="edit-field-price-value-min--8EHokPV5K8s"
Also similar codes with --RandomSymbols are added to others elements.
How can I use ajax whithout adding --8EHokPV5K8s  ?
Comment: You can't, you should use classes to style the items, not ID's. The ID's on dynamic AJAX'd content can change, this is because Drupal tries to ensure ID's are unique on the page to create valid HTML.
Comment: Use classes to target the element instead
Comment: The additional values in the id is Drupal's attempt to ensure unique ids.  Styling should be done with css classed instead of ids.
Comment: But which class can I use?
How to assign a class to a field?

I have several fields that need to be styled, but by default they have the same classes.
ID is unique.

Price
Comment: I find it difficult to understand how `js-form-item-field-price-value-min` isn't a unique enough class. Are you saying that there are multiple field wrappers with that same class, even though you only have that field once in the form? If so there's probably a bug in your theme
Comment: Many thanks! Indeed, for this field I can and will use js-form-item-field-price-value-min.

But what about the fieldset? I use several fieldset. They do not have a unique class.
Answer: Use a class to target the element.
If this is in a view, you can add a class on the fields you need to target. You could also add a class to the view and use existing classes inside that view.
Comment: Thanks! This really works for normal views fields. But I need to add classes to the exposed form fields. I did not find how to add a class there
Comment: You could always add a class with jQuery.
Comment: Thanks! I will do so. I will add classes with jQuery.
Comment: Instead of jQuery, you can also edit the templates to add static classes, or even preprocess the template and add dynamic classes without touching the template. Using javascript to add classes seems like the least elegant solution.

CSS not work after applying ajax


Is the iii chord in second inversion ever used?

Question: In A major if I want to harmonize a descending step bassline that goes A>G#>F#>E>A I could be looking at:
I iii6/4 vi V I
I am not sure about that iii6/4 chord though. Is this ever used? Could anyone share any beginner to intermediate examples of this chord to analyze how they are used in voice leading and if and why it may be avoided?
Comment: If you play it, does it sound good? If so then use it. If not, maybe not. Whether it's been done before is less of a valuable guide to whether to do it now
Comment: Don't know, I am studying voice leading so I would like to see how it is written and voice led. How it sounds now is less important
Answer: I'll let a music theorist speak to it, but it seems to me that there are some benefits to it. My first impulse would probably to harmonize that G# with V6:
X:1
L:1/2
K:A
[Ace] [GBe] | [FAc] [EAc]

... but your iii6/4 keeps the other two chord members in common from the I chord (C# and E). This could be a good thing, making the motion from I to iii smoother. On the other hand, the B in the 1st-inversion V above smooths the motion in parallel thirds all the way from I to V6 to vi. On the other other hand, the second measure below echoes the motion of the first measure, keeping two members in common between vi and V. And all of this could probably be improved by using four-part chords and giving some thought to the voicing.
X:1
L:1/2
K:A
[Ace] [Gce] | [FAc] [EAc]

Answer: For a bass of ^1 ^7 ^6 ^5 I think a common way to harmonize it is I V6 V43/V V.
In relation to your recent question about passing 6/4 chords you get the passing 6/4 motion over the V chord.
Another progression for that bass is a "falling thirds" type sequence [I V6][vi iii6].
Neither are examples of iii6/4, but your question really seems to be more about how to harmonize a descending bass.
Answer: I suppose iii6/4 could be used as a pedal 6/4, surrounded by vi chords.  That's about the only place where it's actually likely to occur idiomatically in "classical" style.  (If you believe in arpeggiated 6/4 chords, then I also suppose one could see a iii6/4 there.)
(EDIT: Oops -- I just realized I was thinking about the wrong context for pedal 6/4.  A iii6/4 would have to occur between minor vii chords, which are not diatonic to any key.  So no, iii6/4 doesn't really exist there.)
As a passing 6/4, you might perhaps see a 6/4 interpolated between vi and vi6.  But in classical style, that's more likely to turn into a V6/4 of vi rather than iii6/4.
As Michael Curtis notes, there are much better and more idiomatic ways of harmonizing a descending scalar bass line.  Using iii6/4, though technically following the "rules" of voice-leading, wouldn't be idiomatic.


User accounts for customers

Question: How would I go about having a feature for customers to create their own accounts on my Drupal? Will I need PHPMyAdmin and some SQL?
Answer: This is a setting that's built into the core of Drupal. On D7/D8 the Who can register accounts? (Public registrations in D6) setting adjusts who can create accounts on your Drupal installation.

Administrators only
Visitors
Visitors, but administrator approval is required

The settings form can be found under /admin/config/people/accounts (/admin/user/settings in D6).
Answer: For D7
You can look Profile 2 module and Profile2 Registration Path module.

The module is aimed to provide a simple, but extensible solution
  providing a similar end user interface like the core profile module by
  default.
Multiple profile types may be created via the UI (e.g. a general
  profile + a customer profile), whereas the module provides separated
  permissions for those.
Optionally, profile forms are shown during user account registration.
  Similar to the deprecated core profile module, fields may be
  configured to be private - thus visible only to the profile owner and
  administrators.
By default the UI behaves similar to the deprecated core profile
  module, thus showing each profile type in each own tab below
  user//edit. Via the included "Profile pages" module profiles can
  be viewed and edited at their own page and get their own menu link,
  e.g. "My profile".

For D8
You can look Profile module.

Multiple profile types may be created via the UI (e.g. a general
  profile + a customer profile), whereas the module provides separated
  permissions for those.
Optionally, profile forms are shown during user account registration.
  Fields may be configured to be private - thus visible only to the
  profile owner and administrators.
Profile types are displayed on the user view page, and can be
  configured through "Manage Display" on account settings.

User accounts for customers


Show that exists a polynomial $p$ such that $\text{sup}_{x\in[1,\infty]}\{|f(x)-p\left(\frac{1}{x}\right)|\}<\epsilon$.

Question: Let $f:[1,\infty]\longrightarrow \mathbb{R}$ a continous function such that $\text{lim}_{x\rightarrow \infty}f(x)$ exists and let $\epsilon >0 $. Show that exists a polynomial $p$ such that $\text{sup}_{x\in[1,\infty]}\{|f(x)-p\left(\frac{1}{x}\right)|\}<\epsilon$.
By the Weierstrass aproximation theorem exists $p$ polynomial such that  $\text{sup}_{x\in[1,\infty]}\{|f(x)-p(x))|\}<\epsilon$. But I don't know how to use the exitence of $\text{lim}_{x\rightarrow \infty}f(x)$ to conclude that $\text{sup}_{x\in[1,\infty]}\{|f(x)-p\left(\frac{1}{x}\right)|\}<\epsilon$. Any suggestions
Comment: Shouldn't it be $[0,\infty)?$
Answer: Hint: Start by showing that the function $g : [0,1] \to \mathbb{R}$ defined by $$g(y) = \begin{cases}f(\tfrac{1}{y}) & y \in (0,1] \\ \lim\limits_{x \to \infty}f(x) & y = 0\end{cases}$$ is continuous on $[0,1]$. Then use the Weierstrass aproximation theorem on $g(y)$ to find a polynomial $p$ such that ....
Can you finish the proof from here?
Comment: Thanks! I'm showing the cotinuity of $g$ useing sequences. It's the right way?


Find ideals of $R[X,Y]/(X^2,XY,Y^2)$ where $R$ is a commutative ring with unity

Question: By the correspondence theorem, we know that ideals of $R[X,Y]/(X^2,XY,Y^2)$ is of the form $I/(X^2,XY,Y^2)$ where $I$ is an ideal of $R[X,Y]$ containing $(X^2,XY,Y^2)$.
So I have to find ideals containing $(X^2,XY,Y^2)$. By division algorithm, any $f(X,Y)\in R[X,Y]$ can be written as $f(X,Y)=(aX+bY+c)+g(X,Y)$ where $g(X,Y)\in (X^2,XY,Y^2)$.
Now if $I$ be an ideal containing $(X^2,XY,Y^2)$ and $I\ne (X^2,XY,Y^2)$. Then there is $a,b,c\in R$ (not all $0$) such that $aX+bY+c\in I$.
So $I$ could be of the form $(X^2,Y^2,XY, aX+bY+c)$. My question is - is there any other ideal of $R[X,Y]$ containing $(X^2,XY,Y^2)$ other than this form?
Comment: No, just any commutative ring with unity.
Comment: One thing I want to mention is that the form could be like $(X,Y,XY,c_1,c_2)$, for example if $R=\mathbb Z[t]$, we can take $c_1=2,c_2=t$. And the ideal you constructed could be infinitely generated, so youhave write all those forms out
Answer: Surely there are other ideals than just the ones you described (the principal ideals).
For one thing, if I call your quotient to ring $S$, $R\cong S/(x,y)$, and so the top of $S$ has all sorts of ideals that $R$ has.  For that reason I do not think it is tractable to ask for a complete set of ideals for your ring when $R$ is just some commutative ring.
Even when $R$ is a field, the maximal ideal $(x,y)/(x,y)^2$ is not principal.


Show there exists a sequence of positive real numbers s.t. ...

Question: Let $f_n$  be a sequence of measurable functions on $[0,1]$ with $|f_n(x)|\lt\infty$  a.e. Show there exists a sequence $c_n$  of positive real numbers s.t. $f_n(x)/c_n\to0$  for almost every $x$ in $[0,1]$. Hint: use the borel-cantelli lemma- pick the sequence $c_n$  so that $$m[x{\rm\ in\ }[0,1]:|f_n(x)|/c_n\gt1/n]\lt2^{-n}$$ where $m$ is the measure.
Comment: Presumably you mean to ask how to solve the (homework?) problem you posted and not order us to solve it.  Please tell us what you have tried so far: e.g., you understand the relevance of the hint?
Comment: Unless there is a very good reason, we prefer not to arbitrarily delete good content: it could well help other users in the future.
Comment: @RealAnal I fail to understand "so that it is just infinity for each element in the sequence". You might want to explain.
Comment: I don't understand how to use the hint. My first idea is to just have a sequence c sub n so that it is just infinity for each element in the sequence. Then surely the fn/cn will go to zero. I think of the hint as just a more difficult way of doing it.
Comment: Perhaps the question should be reopened, as OP appears willing to engage in dialogue.
Comment: Possible duplicate:http://math.stackexchange.com/questions/371467/convergence-of-random-variables-durrett-probability-theory-and-examples
Answer: Fact 1: If $f:[0,1]\to\mathbb R$ is  measurable and $|f(x)|$ is finite for almost every $x$, then for any $\epsilon>0$ there is a number $M$ such that the set $\{x:|f(x)|>M\}$ has measure at most $\epsilon$.
Reason: Since the intersection $\bigcap_{k=1}^\infty \{x:|f(x)|>k\}$ has measure $0$ and the sets in this intersection are nested, it follows that $m[\{x:|f(x)|>k\}]\to 0$ as $k\to\infty$.
Choose   $c_n$ on the basis of Fact 1, so that   $m[\{x:|f(x)|/c_n>1/n\}]<2^{-n}$.
The rest is an application of Borel-Cantelli: the set of number $x$ such that $|f(x)|/c_n>1/n$ infinitely often has measure zero. Rephrase this as: for almost every $x$ we have $|f(x)|/c_n\le 1/n$ for all sufficiently large $n$.
Comment: Why do we need to state the "fact 1"? What if we omit this fact in the proof?


Generic property in a non-generic class?

Question: I'm not sure how to go about this...
I have a class that performs various functions:
public abstract class EntityBase { ... }

public interface ISomeInterface<T> where T : EntityBase, new() { ... }

public class SomeClass<T> : ISomeInterface<T> { ... }

I'm trying to have a cache of these in a non-generic class:
public class MyClass
{
    //Not sure how to do this
    private ConcurrentDictionary<?, ISomeInterface<?>> Cache { get; set; }
}

The problem is that EntityBase is abstract and can not do new(), The ISomeInterface expects a class that is based off EntityBase and does new(). Is there any way to do what I'm wanting to do?

Update: I realized that for the TKey I can use Type, but I still am not sure what to put for the ISomeInterface.
Answer: Firstly, I think you meant to use ConcurrentDictionary since you have a key/value pair.
Secondly, you can do it similar to ICloneable. ICloneable has a method that returns an Object instead of a T.
private ConcurrentDictionary<Type, Object> Cache { get; set; }

Since it's private you can manage it internally and cast it as needed. Obviously you'll have to make sure any function calls have a typeparam definition, for example:
//I omitted error checking on all the examples.
public class Foo : EntityBase { ... }

void DoSomething<Foo>()
{
    var someClass = Cache[typeof(Foo)] as ISomeInterface<Foo>
    someClass.Bar();
}

Also, even if the property had another modifier (public, internal, protected) you could add comments to callers that the Object is a generic type of ISomeInterface where T is a EntityBase, new(). Then, they simply have to cast however they need to.

You can also have generic methods on the non-generic class to get the cached item as a generic type:
ISomeInterface<T> GetInstance<T>()
    where T : EntityBase, new()
{
    return Cache[typeof(T)] as ISomeInterface<T>;
}

void AddInstance<T>(ISomeInterface<T> instance)
    where T : EntityBase, new()
{
    Cache[typeof(T)] = instance;
}

void DoSomething<T>()
{
    var someClass = GetInstance<T>();
    someClass.Bar();
}

Answer: See this related question: Making a generic property
If you don't want MyClass to be generic, you can use two generic methods instead:
    private ConcurrentCollection<T, ISomeInterface<T>> GetCache<T>()
    {
        ...
    }

    private void SetCache<T>(ConcurrentCollection<T, ISomeInterface<T>> cache)
    {
        ...
    }

Comment: And how would you implement the methods?
Comment: I guess I didn't address the backing storage issue in my answer. :)
Answer: I'm not sure what exactly do you want to use that collection for, but one way of doing something similar would be to create a nested generic static class that holds the values:
class SomeInterfaceCollection
{
    private static class Item<T>
    {
        public static ISomeInterface<T> Value;
    }

    public static ISomeInterface<T> Get<T>()
    {
        return Item<T>.Value;
    }

    public static void Set<T>(ISomeInterface<T> value)
    {
        Item<T>.Value = value;
    }
}

Comment: This only makes sense for a static property.


How to remove date chunk from bigger string without regex?

Question: NOTE - This question might seem similar to this or this or this, but none of them exactly solved my problem.
I want to remove the probable date strings from a string of bigger length containing this date string in between. Like if the input string is "13th June 2020 is the day to remember" the output will be "is the day to remember". Now I've already tried these three modules:

parseddatetime
date-extractor
datefinder

Like this:
import parsedatetime as pdt
from date_extractor import extract_dates as ed
from datetime import datetime as dt
from datefinder import find_dates as fd
cal = pdt.Calendar()

def check_date_parseddatetime(date_string):
    date_parsed, parse_status = cal.parse(date_string)
    #print(f"check_date_parseddatetime :: date_parsed : {date_parsed}")

def check_date_extractor(date_string, prec_=False):
    try:
        dt_parsed = ed(date_string)
        #print(f"check_date_extractor :: dt_parsed : {dt_parsed}")
    except Exception as e:
        #print(f"check_date_extractor :: error")
        pass

def check_datefinder(date_string, date_extract_result=(False, )):
    datefinder_list = [str(m) for m in fd(date_string)]
    #print(f"check_datefinder :: datefinder_list : {datefinder_list}")

Here is a sample output for the string " 13 jun 19 : Once upon a time"
given by parseddatetime:
time.struct_time(tm_year=2020, tm_mon=6, tm_mday=13, tm_hour=16, tm_min=23, tm_sec=48, tm_wday=5, tm_yday=4, tm_isdst=0)

given by date_extractor:
[datetime.datetime(2019, 6, 13, 0, 0, tzinfo=<UTC>)]

given by datefinder:
[datetime.datetime(2019, 6, 13, 0, 0)]

The problem of using them is they work perfectly fine to parse the exact date from the string, but still they don't return the exact word chunk for which this date is found.
Here are all the test data I'm trying on. The date parsing is working great, but none of them returns any matched string for which this parsed date is extracted:
l = ['13 jun 19 : Once upon a time', '13-jun-19', '13JUN19', '13 dec 19', '13-dec-19', '13th june 2019', '13th december 2019', '13-06-19', '13.06.19', '13.6.19', '13.12.19', '13/06/19', '13/12/19', '12 jan 2009', '12 jan, 2009', 'jan 12 2009', 'jan 12, 2009', '12 january 2009', '12 january, 2009', 'january 12 2009', 'january 12, 2009', '01 12 2009', '12-01-2009', '12 - 01 - 2009', '12/01/2009', '12 / 01 / 2009', '12 /01 /2009', '12/ 01/ 2009', '12/ 01 /2009', '12 /01/ 2009', '12 01 2009', '12 1 2009', '13 01 2009', '12 21 2009', '15 1 2009', '2 15 2009', '01-12-2009', '01/12/2009', '12.01.2009', '01.12.2009', '13-Jun-18', '13 Jun 19', '13 Jun, 19', '13, Jun 19', 'bla13 bla 14, Jun 19 sdfhkjn jd 12', '18-Feb-2008', '18 - Feb - 2008', '18 -Feb -2008', '18- Feb- 2008', '18 -Feb- 2008', '18- Feb -2008', '13-Jun-18 , 18-Feb-08', 'june 20', 'Jul 01, 2019', 'Jul 01 2019', 'Aug 5 2019', '21 Jun 2019, 18:00', '6/12/19', '6/18', '29 DEC 19', '29-DEC-19', '29/12/19', '14J1-N19', '12/Jul/2019 12/Aug/2019 MEISHAN BRIDGE 06:00']

The desired output will be vacant string for all cases, except these three cases where there are extra words except the date:
['13 jun 19 : Once upon a time', 'bla13 bla 14, Jun 19 sdfhkjn jd 12', '21 Jun 2019, 18:00', '12/Jul/2019 12/Aug/2019 MEISHAN BRIDGE 06:00']

The output for the above three cases should be:
[': Once upon a time', 'bla13 bla  sdfhkjn jd 12', ', 18:00', ' MEISHAN BRIDGE 06:00']

I've thought of writing regex for each cases, but there are more date test cases to be introduced later (which might be handled using these modules) and thus writing regex for all these many cases to match with the bigger string will be painstakingly hard. How to achieve this without regex? Is there any other module (or any of these three modules) which return the exact match for which we are getting the parsed date and thus can help to remove that part from the bigger string?
Answer: I found out a new package named python-sutime [a python wrapper for Stanford NLP's sutime java libraries]. It helps me remove the particular date chunks from strings. It works even if there are multiple dates in single string.
The disadvantage of using this package is additional installation of the java jdk dependencies required. But nevertheless this is kinda perfect for getting the thing done.
Here is the usage example I used :
from sutime import SUTime
test_string = "13 jun 19 : Once upon a time"
jar_files = os.path.join(os.path.dirname(__file__), 'jars')
sutime = SUTime(jars=jar_files, mark_time_ranges=True)
sutime_parsed_vals = sutime.parse(test_case)
sutime_parsed_vals = [i for i in sutime_parsed_vals if i['type']=='DATE']
temp_string = deepcopy(test_string)
for parsed_val in sutime_parsed_vals:
    start, end = [parsed_val["start"], parsed_val["end"]]
    temp_string = temp_string[:start] + (end - start)*' ' + temp_string[end:]
output = ' '.join(temp_string.split())


Distinction between same notes played on different strings

Question: While playing a particular piece (not chords, fingerpicking/single note playing) on my ukulele (or as far as the question is concerned, any similar instrument), I use the standard notation and then play the different notes by engendering the required notes by appropriately fretting different strings.
My question is, is there any difference between the same note played on different strings? Or choosing where to play the note is purely a matter of convenience?
Logically, since the sizes and tensions of the strings vary, there might be some difference even with the same fundamental frequency, maybe in the harmonic spread. If it is so, on what basis do we choose the strings while doing the aforementioned exercise?
I am not certain of the tags to be used. Please add if necessary. Thanks :)
Comment: On the violin notes of the same pitch sound different if played on different strings, partlly because the violin sounds different higher up the fingerboard. Sometimes when I'm playing in orchestra the composer (especially Elgar) will write "Sul G" meaning that the entire phrase should be played on the low G string. Hard, but sounds wonderfully eerie if you can pull it off. Also as the violin is not fretted an open string sounds very different from the equivalent note on a stopped string. Folk fiddlers often use this to play both 'versions' of the same note together as it sounds rich.
Answer: There can be a difference in tone quality due to the difference in thickness and tension of strings. This is true on guitars, lutes, violins, etc. There can be a subtle difference in tuning also; the nominal pitch may be slightly different. In early times before equal temperament became popular, notes like Ab and G# would have differed a bit and which fingering would depend on which note was wanted in a particular place in the music. It's worth looking up the effects of temperament on lute (or other stringed instruments) tunings.
Some references:
http://www.theaterofmusic.com/temperaments.html (a guide to tunings with references)
https://scholarsphere.psu.edu/downloads/sf268k62m (a dissertation on the subject)
http://www.michaelkudirka.com/papers/files/the-rule-of-31.pdf (an historical discussion)
In practice for contemporary music, the easiest fingering should be sufficient.
Comment: There's one more difference: String angle. Using guitar as an example, fingerings that are higher up the neck deflect the string farther downward towards the body in the area where most picking is done. If one plays with a plectrum and is using minimal picking for tone or speed purposes, choosing different places to play the same note can make a difference for precise picking depth. I would say the tonal difference is a definite factor, as opposed to possible, and is the most obvious consequence of playing the same note on a different string and fret combination.
Answer: Interesting question.  I have a ukulele and play it on occasion but my main instrument is acoustic guitar.  With either instrument my choice of where to play a note is predicated by the overall musical phrase and where the other notes lie in relation to each other.
In other words, I have to take into consideration what the preceding note is and the following note and which direction I am moving on the scale which could inform which direction I might want to move on the fretboard.
Also, if I want a note to sustain while I play other notes, then I might choose to play the next note on a different string. If playing guitar where it is common to bend strings to produce different notes and effects, I might choose the placement of the note based on where it will be easier to bend if that is my intention.  Of course it is not so common to bend notes on a uke.
In the absence of a compelling reason to do otherwise (see above), my choice of where to play the note will in fact be a matter of convenience.  I choose the easiest to reach note position to play a particular note.
While it is true that there may be a slightly perceptible difference in tone playing the same note on a different string, I would not worry about differences in the harmonic spread or which overtones are emphasized or anything like that.  With most music played on a ukulele, the listener is not going to notice any practical difference.
Don't over think it and have fun!
Answer: Convenience is certainly a factor, but it's not the only one. Others have mentioned selecting strings to allow previous notes to ring out etc. I think this is one other thing to consider when playing uke.
All fretted instruments have imperfect intonation. Ukuleles tend to suffer from bad intonation more than guitars. Much of this is down to just how many ultra-cheap poor quality ukes there are, but I think the short scale also emphasises it (I'm prepared to be corrected). With this in mind, the lower the number of fret you're playing the more in tune it will sound.
Answer: Of course there is a difference: you cannot let a previous note ring on when you are playing the next note on the same string rather than a different one.
Bach's Partita III for Solo Violin (BWV 1006 I think) is also available for lute.  At any rate, even the violin version transfers well to guitar in the first movement and you should likely be able to figure out a version for ukulele if you try.
There are characteristic, uh, licks?, which very idiomatically go across two or three strings where sometimes the notes on two of the strings are even the same.  Even though the first movement is formally monotonic (just one note at a given time), without distributing these phrases in the intended manner across three strings they become pointless.
Comment: While you're correct I think the OP was asking purely about how the sound of the same note differs when played on different strings, not the practicality of doing so.
Comment: I don't understand the phrase "without distributing these phrases in the intended manner across three strings they become pointless"


How to deal with exposure or outcome at time 0 in a time-varying Cox model

Question: Let's say I have a dataset with a list of cars, some of which have self-driving function which is the time-varying exposure. Some of the cars had this function from the beginning (time 0) and some acquired it after. The outcome of interest is crash. Some cars had car crash day 0. How do you deal with these exposures and outcomes that occur at time 0 in a time-varying Cox-model?
Answer: Cox regression doesn't model times-to-events directly; it only works with the ordering of events in time. Thus you can choose any positive value less than the smallest event time after day 0 for event times on day 0. The baseline hazard function estimated at that chosen "event time" from the Cox model will then represent the cumulative hazard for events during day 0.


closed embedded submanifold and proper map

Question: In Lee's Introduction to Topological Manifolds. I came across this statement:

A submanifold of $M$ is closed in $M$ if and only if the inclusion map is proper.

However, isn't the inclusion map from $i: B^k \to R^k$ a counter example to this, since the map is an embedding and proper but $B^k$ is open in $R^k$.
Comment: Your inclusion is not proper. The inverse image of $\overline{B^k}$ is $B^k$ which is not compact.
Comment: I see, completely overlook that, tks
Answer: The inclusion map is not proper, because preimage of $\bar{B(1,0.5)}$is not closed, therefore not compact


VBA copy a column from an excel's file to another in the first empty column

Question: Private Sub CommandButton1_Click()
Dim selection As Variant
selection = UserForm1.ComboBox1.Text
Sheets("Sheet1").Select
Cells(1, 2) = selection
Sheets("Sheet1").Select
selection = Cells(1, 2)
namefile = "C:\Users\xxx\" & Left(selection, 1) & "\" & selection & ".xls"
Workbooks.Open Filename:=namefile

Dim wk1 As Workbook
Dim wk2 As Workbook
Dim sh1 As Worksheet
Dim sh2 As Worksheet

Set wk1 = Workbooks("file1.xlsm")
Set wk2 = Workbooks(selection & ".xls")

Set sh1 = wk1.Worksheets("Sheet2")
Set sh2 = wk2.Worksheets("Sheet1")

sh2.Activate
Dim firstempty As Variant
Dim x As Integer
Dim y As Integer
Dim A1 As Variant
Dim R1 As Variant
Dim C1 As Variant
x = 0
y = 0
While x = 0
If Range(Cells(1, y), Cells(1, y)) <> "" Then
y = y + 1
Else: Range(Cells(1, y), Cells(1, y)).Select
A1 = Target.Address
R1 = Target.Row
C1 = Replace(A1, R1, "")
firstempty = (C1 & ":" & C1)
x = 1
End If
Wend

With sh1

    .Columns("D:D").Copy Destination:=sh2.Range(firstempty)
End With

End
End Sub

I need to copy column D of Sheet2 file1.xls on the first blank column of sheet1 of a second file whose name is selected by a combobox.
I am having trouble defining the letter of the empty column of the second file.
I am getting runtime error 424 and my debugger brings me to the point in the code:
  A1 = Target.Address
What am I doing wrong?
Comment: Where is `Target` defined?
Comment: Is this code in `UserForm1' module?
Comment: I've defined target: Dim target As Variant . But i've the same error
Comment: Yes, the code is in UserForm1' module
Answer: Shouldn't y=0 be y=1 ?
Now you're referring to column 0.
And then this should work:
If Cells(1, y) <> "" Then
y = y + 1
Else
firstempty = y
x = 1
End If

And then:
.Columns("D:D").Copy Destination:=sh2.Columns(firstempty)

Answer: Here is a much faster way to get the last column:
Private Sub CommandButton1_Click()
Dim selection As Variant
selection = UserForm1.ComboBox1.Text
Sheets("Sheet1").Select
Cells(1, 2) = selection
Sheets("Sheet1").Select
selection = Cells(1, 2)
namefile = "C:\Users\xxx\" & Left(selection, 1) & "\" & selection & ".xls"
Workbooks.Open Filename:=namefile

Dim wk1 As Workbook
Dim wk2 As Workbook
Dim sh1 As Worksheet
Dim sh2 As Worksheet

Set wk1 = Workbooks("file1.xlsm")
Set wk2 = Workbooks(selection & ".xls")

Set sh1 = wk1.Worksheets("Sheet2")
Set sh2 = wk2.Worksheets("Sheet1")

Dim LastColumn As Long

LastColumn = sh2.Cells(1, Columns.Count).End(xlToLeft).Column + 1

sh1.Columns("D:D").Copy sh2.Cells(, LastColumn)

End Sub

As a side note could you explain this part of code:
Sheets("Sheet1").Select
Cells(1, 2) = selection
Sheets("Sheet1").Select
selection = Cells(1, 2)

It looks like you are getting a value then assigning the value to a cell then the cells value (that you just assigned already) back to the variable that assigned the original value.
at the most you should only need one line:
Sheets("Sheet1").Cells(1, 2) = selection

dno't get the need for the rest.
Comment: I don't need exactly the last empty column, I need the last column with an empty first row
Comment: @user3023582 Thats exactly what this does, it goes to the last column in Row 1, then jumps left to the last value in Row 1 with a value, then moves over 1 to the empty cell next to it. The end command is the same as if you are on the worksheet press Ctrl + Arrow Keys.


laravel eloquent nested comment and replies

Question: Few days ago, I saw a website where users can comment on a post. Other users can reply on that. and a replay can have replies like the example screenshot below..
So I thought to give it a try but somehow couldnt figure it out.
here is my database set up
Schema::create('comments', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('user_id');
            $table->unsignedInteger('post_id');
            $table->unsignedInteger('reply_id')->default(0);
            $table->text('body');
            $table->timestamps();
        });

relationships in model
class Comment extends Model
{
    protected $fillable = [
        'user_id',
        'post_id',
        'reply_id',
        'body'
    ];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function post()
    {
        return $this->belongsTo(Post::class);
    }

    public function replies()
    {
        return $this->hasMany(Comment::class,'reply_id','id');
    }

in controller
$comments = Comment::with('replies')->where('reply_id','=',0)->get(['id','reply_id','body']);
   return response($comments);

this perfectly returns the comment and replies. But if there is a reply of  reply, it doesnt show up. How can I do that? Need suggestion.
Answer: Swap reply_id with a nullable() parent_id. So basically you want to know if a comment has a parent.
Then in Comment model, add a self relationship to take all comments whose parent_id match.
public function replies() {
    return $this->hasMany('App\Comment', 'parent_id');
}

In your view you can have nested loops for each comments and its replies
@foreach($comments as $comment)
   {{ $comment->content }}

   @if ( $comment->replies )
       @foreach($comment->replies as $rep1)
           {{ $rep1->content }}
           ...
       @endforeach
   @endif
@endforeach

Comment: can you please provide a complate example
Comment: Couple of questions though: what how would action attribute look like and why this /posts/{{$post->id}}/comments/{{parent_id}} isn't viable i.e. show error that parent_id can't be called twice? And how to get parent comments id in a first place?
Answer: In your controller, the ->where('reply_id','=',0) clause will definitely return no reply. Remove the condition and eloquent will assume to return all replies related to the comment.


Doubt with this serie of function defined by parts.

Question: i need find the point limit of this function, of course, if the limit exists.
Determine the point limit of $\left\{ f_{n}\right\}$ in $\mathbb{R}$
$f_{n}(x)=\begin{cases}
0 & x\leq n\\
x-n & x\geq n
\end{cases}$
Then...
$lim_{n\rightarrow\infty}f_{n}(x)=\begin{cases}
0 & x\leq\infty\\
\infty & x\geq\infty
\end{cases}$
Is right this?
I have a problem with $x\leq\infty$ and $x\geq\infty$ i think that is bad, can someone help?
Comment: Which real numbers $x$ satisfy $x\geq\infty$?
Comment: I don't know @MatthewLeingang For that im question this problem...
Answer: A pointless limit means that you take a fixed $x$ and see what happens with $f_n(x)$ as $n$ grows to infinity.
Now, whatever $x$ we take, at some point $n$ will become greater than it, so $f_n(x)$ would irreversibly become $0$. Can you finish?
Answer: If $x\in\mathbb{R}$ we consider the usual order relation
\begin{align*}
-\infty<x<\infty
\end{align*}
So, the expression $x\geq \infty$ is not correct.

We instead fix an arbitrary real number $x$. We recall the limit of a sequence does not change, when changing $finitely$ many elements of the sequence and we obtain
\begin{align*}
\lim_{n\to \infty}f_n(x)=\lim_{{n\to\infty}\atop{n>x}}f_n(x)=0
\end{align*}
We conclude
  \begin{align*}
\lim_{n\to\infty}f_n(x)=0\qquad\qquad \text{for all }x\in\mathbb{R}
\end{align*}


Theory- grouping notes

Question: In a 4/4 time signature, can I write a half note on the 2nd and 3rd beat Or should I split the half note into quarter notes with a tie to show the middle of the bar?
Also, in 7/8 with (4,3)as main beats, can I write 8 beamed 16th notes and the the rest of the beat?
Answer: In relatively strict notational convention, you'd want to split that half note into two quarter notes. But honestly, I've seen that particular rhythm countless times; it won't trip up any performer. (What could trip up a performer, though, is cutting over smaller divisions of the bar like a quarter note or eighth note.)
And your 7/8 sounds fine, but you may also experiment with two groups of four beamed sixteenth notes. This is only because we're used to seeing groups of four and can recognize them pretty much immediately. A group of eight, though, is less common, and it may cause a performer to second guess themselves.

Theory- grouping notes


Passagem de parâmetros para Modal

Question: Estou com problemas ao passar parâmetros para meu Modal, gostaria de apresentar os dados da tupla selecionada, consegui isolar o valor devidamente (atestei pelo console.log), porém, este mesmo não está sendo passado para meu modal, parece que precisaria de algo como uma chamada assíncrona, mesmo que toda operação ocorra dentro de meu front (não faz uma nova chamada do banco).
A intenção é fazer um formulário, porém, apenas para verificar que os dados estão sendo passados devidamente, vou usar a simples passagem do meu JSON, resolvendo isso já estaria ótimo para dar continuidade.
Código do filtro:
 filtrardetalhes(value){

     this.planilhaDetalhes = this.planilha.filter(x =>
        x.PID == value
     );
     console.log(this.planilhaDetalhes)

 }

Modal:
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" (click)="filtrardetalhes(planilha.PID)">
    Details
</button>

  Detalhes

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    ×
                </button>

                {{planilhaDetalhes}}

                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" (click) = "AtualizaBtn()">Save changes</button>

Coloquei um "Input" na minha variável "PlanilhaDetalhes" porém apenas para fins de teste:
  @Input('planilhaDetalhes') public planilhaDetalhes

Como o parâmetro está sendo passado:

Vale ressaltar que o filtro está funcional, apenas deixei meu JSON fechado pois contém informações confidenciais de negócio, porém este JSON de 1 posição é o filtro de um de 74 (e acompanha aonde eu clicar em DETAILS)
EDIT:
Resolvido, passei o JSON na íntegra, porém, estou na dúvida se consigo passar algum parâmetro específico, por exemplo, {{planilhaDetalhes.CAMPO | JSON}}
Segue como ficou a passagem para meu form:

Formulário funcional (sem conseguir passar parâmetros ainda) dentro do BODY do MODAL:
   <form class="meuFormulario" [formGroup]="cadastroForm" (ngSubmit)="onSubmit()">

                                      Cliente
                                      <input type="text" class="form-control" formControlName="CLIENTE" value="{{planilhaDetalhes.PID}}">

                                      CODIGO DMD
                                      <input type="text" class="form-control" formControlName="CODIGODMD" value="{{planilhaDetalhes.CODIGODMD}}">

                                      Sigla RM
                                      <input type="text" class="form-control" formControlName="SIGLARM" value="{{planilhaDetalhes.SIGLARM}}">

                                      Sigla Portal
                                      <input type="text" class="form-control" formControlName="SIGLAPORTAL" value="{{planilhaDetalhes.SIGLAPORTAL}}">

                                      Comercial
                                      <input type="text" class="form-control" formControlName="COMERCIAL" value="{{planilhaDetalhes.COMERCIAL}}">

                                        Atendimento
                                        <input type="text" class="form-control" formControlName="ATENDIMENTO" value="{{planilhaDetalhes.ATENDIMENTO}}">

                                        Auditoria
                                        <input type="text" class="form-control" formControlName="AUDITORIA" value="{{planilhaDetalhes.AUDITORIA}}">

                                        Periodicidade
                                        <input type="text" class="form-control" formControlName="PERIODICIDADE" value="{{planilhaDetalhes.PERIODICIDADE}}">

                                      Entrega
                                      <input type="text" class="form-control" formControlName="ENTREGA" value="{{planilhaDetalhes.ENTREGA}}">

                                        Responsável
                                        <input type="text" class="form-control" formControlName="RESPONSAVEL" value="{{planilhaDetalhes.RESPONSAVEL}}">

                                        Layout
                                        <input type="text" class="form-control" formControlName="LAYOUT" value="{{planilhaDetalhes.LAYOUT}}">

                                        DM
                                        <input type="text" class="form-control" formControlName="DM" value="{{planilhaDetalhes.DM}}">

                                        ODSDM
                                        <input type="text" class="form-control" formControlName="ODSDM" value="{{planilhaDetalhes.ODSDM}}">

                                        EFV
                                        <input type="text" class="form-control" formControlName="EFV" value="{{planilhaDetalhes.EFV}}">

                                        Caminho
                                        <input type="text" class="form-control" formControlName="CAMINHO" value="{{planilhaDetalhes.CAMINHO}}">

                                        Origem
                                        <input type="text" class="form-control" formControlName="ORIGEM" value="{{planilhaDetalhes.ORIGEM}}">

                                        Comercial
                                        <input type="text" class="form-control" formControlName="COMERCIAL" value="{{planilhaDetalhes.COMERCIAL}}">

                                        Portal
                                        <input type="text" class="form-control" formControlName="PORTAL" value="{{planilhaDetalhes.PORTAL}}">

                                        FTP
                                        <input type="text" class="form-control" formControlName="FTP" value="{{planilhaDetalhes.FTP}}">

                                        Observação
                                        <input type="text" class="form-control" formControlName="OBSERVACAO" value="{{planilhaDetalhes.OBSERVACAO}}">

                                      Mailing
                                      <input type="text" class="form-control" formControlName="MAILING" value="{{planilhaDetalhes.MAILING}}">

                                      Example select
                                      <select class="form-control" id="exampleFormControlSelect1">
                                        <option>Produção</option>
                                        <option>Other</option>
                                      </select>

                                    </form>

Comment: troque `{{planilhaDetalhes}}` para `{{planilhaDetalhes | json}}`
Comment: Então ficou bem confusa sua questão, você tem a função **filtrardetalhes()** que não está sendo executada em lugar nenhum.
Comment: Desculpe, esqueci de incluir a parte da chamada, editado com ela incluída agora!
Comment: E o que seria **planilha.PID**?
Comment: O ID, este é proveniente do meu INPUT para o NgFor que constrói a tabela inicial (onde o button de detalhes, que abre o modal fica), o filtro está funcional, o problema que estou enfrentando seria na passagem de parâmetros para o meu modal.
Comment: Ao que parece ele filtra depois de abrir o modal, desta forma, o modal só recebe "Object object" da minha variável.
Comment: Resolvido! Boa Gaspar! Muito obrigado!
Comment: Outra dúvida apenas, consegui passar o | JSON, mas não estou conseguindo passar planilhaDetalhes.CAMPOEXEMPLO | JSON, teria alguma forma de fazer isso?
Comment: Poderia me explicar o funcionamento deste pipe resumidamente "|"?
Comment: O pipe json (| json) é usado para transformar os valores nos campos. Se deseja construir um formulário nessa modal, basta informar `planilhaDetalhes.CAMPOEXEMPLO`no `ngModel` do input deste campo...
Comment: Pipe basicamente é para transformar visualmente um objeto que você não quer alterar ele por completo apenas para mostrar ao usuário na view. A documentação oficial do pipe está [aqui](https://angular.io/guide/pipes)
Comment: Obrigado pelas informações a respeito do pipe, será muito útil! Agora a questão do campo, ao colocar {{planilhaDetalhes.PID}} no meu form, o mesmo não retorna nenhum valor. O único jeito que retornou algo foi {{planilhaDetalhes | json}}.
Comment: Incluí o formulário para melhor compreensão
Comment: vou editar minha resposta com as informações necessárias
Comment: Ok! Coloque ela como resposta abaixo e eu terei prazer em votar nela!
Comment: Está editado na resposta! Qualquer duvida me avise
Comment: Existe outra forma sem ser com ngModel? Ao que aparenta alguns recursos do ngModel serão removidos/alterados nas próximas versões do angular, assim, podendo comprometer minha aplicação em caso de atualização.
Comment: Fiz uma gambiarra horrenda com o ngFor chumbado em um json exemplo e funcionou
Comment: O ngModel nunca vai ser removido do angular 2+, pode usar tranquilo. Se tu quiser aplicar um formulário e controlar se está validado ou não, utiliza-se de outro jeito de controlar o estado, porém é o mesmo conceito e não muito recomendado pra quem ta iniciando. Comece usando objetos separados e valide o essencial, quando tudo estiver funcionando, migre os formulários com uma validação mais robusta...
Answer: Não entendi se é o caso, mas acredito que você deseja abrir uma modal em outro componente e não está recebendo os parametros corretamente.
No componente que chama você utiliza esses dados:
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { ComponenteModal } from '...';

constructor(private modal: NgbModal) {}

abrirModal(objetoPraPassar: any) {
  const modalRef = this.modal.open(ComponenteModal);
  modalRef.componentInstance.planilhaDetalhes = objetoPraPassar;
}

No "ComponenteModal" você faria assim
export class ComponenteModal {

  @Input()
  planilhaDetalhes: any;
}

EDIT:
Agora que você possui o objeto com os valores construa um formulário no body da modal como por exemplo:

  Descrição
  <input name="descricao" class="form-control" [(ngModel)]="entity.descricao" required>

Onde o [ngModel] vai receber os valores digitados e mostrar para o usuário no objeto entity.descricao,
o (ngModel) vai atualizar a variável setando entity.descricao com os valores digitados,
por isso, utilizado o [(ngModel)] para atualizar e receber os valores.
Em casos que você quer mostrar alguma informação ao usuário que nao seja dentro do ngModel é utilizado duas chaves, como por exemplo {{ entity.descricao }}

Passagem de parâmetros para Modal


Using moment.js to indicate when mongoDB/mongoose was last updated?

Question: I have a table populated with data from my mongoDB and I want to use moment.js to indicate the last date/time any entry in the table was edited and updated.
My issue is that moment.js seems to be showing the date/time in real time, rather than only when a database entry was edited.
How do I get it to show the correct date and time?
Mongoose Schema, where I use timestamps for the updatedAt feature:
var environmentSchema = new mongoose.Schema({
    ePIMS: String,
    codeVersion: String,
    region: String
  }, {
    timestamps: true
  });

HTML where I'm trying to use moment.js

   <%= moment(environments.updatedAt) %>

   <% environments.forEach(function(environment){ %>

         <%= environment.ePIMS %>
         <%= environment.codeVersion %>
         <%= environment.region %>

   <% }); %>

By the way, it works when I put the moment.js code in my forEach loop where my mongo collection (environments) is being called, but then it shows a date and time for every single entry of my database, and updates those dates/times individually. Is there a way to do it this way but only have one date/time for all entries?
Answer:
Environments is an array of environment objects and you are trying to get updatedAt of that.
You need to get one environment object and get UpdatedAt of that single object.
So you can put [index] mostly [0] environments[0].updatedAt to get the updatedAt of the first environment.
To get the lastest one go with sort({"updatedAt": -1}) and then environments[0].updatedAt
Comment: Is there a way to have 1 date/time shown for all the environments? Instead of an individual date/time for each environment every time it's updated? This method works for just displaying the date/time when the first environment is updated, but I'm trying to have 1 date/time for all environments..
Comment: One solution I can think of right now is use `sort({"updatedAt": -1})` with your query so the first environment will have latest datetime.


About resource limitation (MaxSubmitJob) in Slurm

Question: I used the following command to set the maximum number of jobs a user can run.
However, the above setting did not work.
If anyone has any knowledge about this, could you please help me.
sacctmgr modify user account=<ldap-groupname> <ldap-username> set MaxSubmitJobs=2

I checked setting following command
sacctmgr show associations

outputs
Cluster    Account       User  Partition     Share   Priority GrpJobs       GrpTRES GrpSubmit     GrpWall   GrpTRESMins MaxJobs       MaxTRES MaxTRESPerNode MaxSubmit     MaxWall   MaxTRESMins                  QOS   Def QOS GrpTRESRunMin
---------- ---------- ---------- ---------- --------- ---------- ------- ------------- --------- ----------- ------------- ------- ------------- -------------- --------- ----------- ------------- -------------------- --------- -------------
  clustername       root                               1                                                                                normal
  clustername        root       root                    1                                                                                normal
  clustername ldap-groupname                               1                                                                                normal
  clustername  ldap-groupname  ldap-username                    1                                                                                2                                         normal
`

Answer: Make sure AccountingStorageEnforce is set to limits in slurm.conf.
Comment: Thank you for your help!  I was able to solve the problem by adding the following setting to slurm.conf.

```
AccountingStorageEnforce=associations
```


If $a,b,c\neq0$, prove that $ac\mid bc \iff a\mid b$

Question: How can I prove this question?

If $a,b,c\neq0$, prove that $ac\mid bc \iff a\mid b$

Please help me
Comment: I have a feeling this question has been asked before. It would make much more sense to close it for being a duplicate than to close it for being off-topic.
Comment: Remember that $a \mid b$ means *a divides b*, that is, by definition, there exists some $r$ such that $b = a \cdot r$. Does this help you understanding what Modded Bear did?
Comment: @Ale oh, thank you so much.I noticed :)
Comment: possible duplicate of [$a\mid b$ if and only if $ac \mid bc$ where $c\neq 0$](http://math.stackexchange.com/questions/671660/a-mid-b-if-and-only-if-ac-mid-bc-where-c-neq-0)
Answer: $bc=(ac)k\iff b=ak$. Of course you can only cancel $c$ if $c$ is different to zero.${}{}{}{}{}{}{}{}{}{}{}$
Comment: what is your definition for $a|b$?
Comment: thank you, sorry I am a beginner. Please explain more. so sorry.
Comment: what is $k$ in your answer?
Comment: One definition for $a|b$ is there exists an integer $k$  so that $b=ak$. This is the same as saying $\frac{b}{a}=k$ is an integer.
Comment: You really should state explicitly in the *answer* the key role played by one of the hypotheses.
Comment: $c\neq 0$?, so $c$ is invertible?
Comment: Yes, because it fails otherwise. The answer should at least give some hint that the hypothesis is needed.
Answer: The expression $ac \mid bc$ means that there exists an integer $n \in \mathbb Z$ such that
$$bc = n(ac).$$
Since $c \neq 0$
$$b = na \iff a \mid b.$$


GCP - Assigning Static External IPs on Marketplace Solutions

Question: I'm having trouble assigning a static IP to a Google Cloud Platform Marketplace Deployment and thought someone here might have some insight.
I have an unassigned static IP ready to go in the same zone as the virtual machine, yet it doesn't allow me to assign that IP to my new Compute Engine VM.
Image of Deployment Screen
Does anyone have any ideas, or know what might be going wrong? I've refreshed the page and have had the IP reserved for a bit, but still nothing. Thank you!
Answer: I think you should release the IP address after wordpress instance has been created.
https://cloud.google.com/compute/docs/ip-addresses/reserve-static-external-ip-address
After you attach the IP address, you should access to the instance using ssh and get the admin password.
--- This is the message that you can see in the ssh console.
<code>WordPress One-Click Quickstart guide:
* https://docs.litespeedtech.com/cloud/wordpress
In a web browser, you can view:
* The new WordPress site: http://34.67.88.XXX
* The phpMyAdmin: http://34.67.88.XXX/phpmyadmin
On the server:
* The default web root is located at /var/www/html
* You can get the MySQL root password and MySQL WordPress user password with com
mand:
   sudo cat /home/ubuntu/.db_password
* You can get the Web Admin admin password with the following command:
   sudo cat /home/ubuntu/.litespeed_password
* The WordPress Cache plugin, LSCache, is located at
   /var/www/html/wp-content/plugins/litespeed-cache
* The phpMyAdmin is located at /var/www/phpmyadmin
* A script will run that will allow you to add a domain to the web server and im
plement SSL.
</code>
Comment: Do you mean reserve? I've tried, but run into issues with network tiers. I'll try to make sense with this, but I don't know if it will.

If I try to promote that ephemeral IP to static using that guide, I get an error saying that the network tiers of the address and project don't match. I first did it with my default network tier set as standard, but I figured that message might mean that the instance wants to use premium tier. I started with a fresh instance and set my network tier to premium, same thing.
Answer: I'm editing my answer now. I was doing some tests and I reproduced your scenario. After some failed attempts I finally was able to attach the static external ip to the openlitespeed-wordpress instance.
The trick was create the instance without external IP and then reserve the ip attaching it to the instance on the reservation process. I mean, when you are reserving the external static IP you need to put the openlitespeed-wordpress instance name on the "Attached to" section (probably your instance will not be listed in the drop down menu) and then proceed to reserve the IP. Remember that the regions of both, the instance and the IP address should match.
Comment: I'm dying of laughter over here... that bug report was created by me as well! That's the account of the actual instance, so I used that. Funny that you were able to find it.
Comment: Well, it is funny but this is telling you that the bug report has some visibility ;-). I edited my answer....


How to determine the number of divisors of an integer through combinatorics

Question: How would you formally derive the fact that integer $100$ has 9 divisors $(1,2,4,5,10,20,25,50,100)$, knowing in advance that, apart from 1, its prime divisors are 2 and 5, each recurring 2 times $(2 \cdot 2 \cdot\ 5 \cdot 5 = 100)$?
This should be achievable using counting rules in combinatorics.
Answer: Yes, it is possible. Suppose we have $n = p_1^{k_1}...p_m^{k_m}$ where $p_1,...,p_m$ are distinct primes and $k_1,...,k_m \ge 1$. Then, for each prime factor $p_i$, we have the options $\{0,1,...,k_i\}$ for its power $k_i$ since $p_i^a|p_i^{k_i}, \forall a \text{ such that } 0 \le a \le k_i$. So we have $k_i+1$ options for each. Considering the fact that the prime factors are independent from other prime factors (as they are prime numbers), can you get a general result from here?
Comment: Independence of variables implies multiplications, so multiply all $k_i + 1$ to get all permutations. I had overlooked to consider the $1$.
Comment: Yes, exactly. If we pick $p_i^0$, we basically picking $1$ as a factor as you said. That's also possible.
Answer: The divisor counting function is usually noted with $\tau(n)$ (tau). In other words, $n$ has $\tau(n)$ divisors.

$$n=\prod_{i=1}^{m}p_m^{a_m}\Rightarrow\tau(n)=\prod_{i=1}^{m}(a_i+1)$$

The proof for this? Well observe that $p^k$ with prime $p$ has indeed $k+1$ divisors ($1,p,...,p^k$). Finally, observe that $$\tau\bigg(\prod_{i=1}^{m}p_m^{a_m}\bigg)=\prod_{i=1}^{m}\tau(p_i^{a_i})$$ and you are done.
Comment: I see, quite straightforward, my question is standard theory then.