Issue Using tensorflow hub Universal Sentence Encoder with local runtime and GPU in Google Colab

Question: I am working through a machine learning course to learn tensorflow. In one of the project I was performing text classification using a tensorflow_hub pre trained embedding, the Universal sentence encoder v4. The embeddings worked fine using the google Colab GPU, and also worked in my local runtime without my GPU. However, after I set up colab to be able to use my local GPU (RTX 3060), I started getting the error seen below. For reference, my python environment is through Anaconda, and I used conda install to install tensorflow_gpu and cudatoolkit and cudnn. I am not sure what this error means or how to even begin debugging it, any help would be greatly appreciated, thanks!
Code and error:
import tensorflow_hub as hub
tf_hub_embedding = hub.KerasLayer('https://tfhub.dev/google/universal-sentence-encoder/4',trainable=False,name='USE')

rand_sent = random.choice(train_sents)
print(f'Random sent: {rand_sent}\n')
print(f'Embedded sent: {tf_hub_embedding([rand_sent])[0][:30]}\n')
print(f'Embed length: {len(tf_hub_embedding([rand_sent])[0])}')

Random sent: Data of a Japanese study of patients with unresectable sacral chordoma showed comparable high control rates after hypofractionated carbon ion therapy only .

---------------------------------------------------------------------------
UnknownError                              Traceback (most recent call last)
Input In [55], in <cell line: 3>()
      1 rand_sent = random.choice(train_sents)
      2 print(f'Random sent: {rand_sent}\n')
----> 3 print(f'Embedded sent: {tf_hub_embedding([rand_sent])[0][:30]}\n')
      4 print(f'Embed length: {len(tf_hub_embedding([rand_sent])[0])}')

File ~\anaconda3\lib\site-packages\keras\utils\traceback_utils.py:67, in filter_traceback.<locals>.error_handler(*args, **kwargs)
     65 except Exception as e:  # pylint: disable=broad-except
     66   filtered_tb = _process_traceback_frames(e.__traceback__)
---> 67   raise e.with_traceback(filtered_tb) from None
     68 finally:
     69   del filtered_tb

File ~\anaconda3\lib\site-packages\tensorflow_hub\keras_layer.py:229, in KerasLayer.call(self, inputs, training)
    223 # ...but we may also have to pass a Python boolean for `training`, which
    224 # is the logical "and" of this layer's trainability and what the surrounding
    225 # model is doing (analogous to tf.keras.layers.BatchNormalization in TF2).
    226 # For the latter, we have to look in two places: the `training` argument,
    227 # or else Keras' global `learning_phase`, which might actually be a tensor.
    228 if not self._has_training_argument:
--> 229   result = f()
    230 else:
    231   if self.trainable:

UnknownError: Exception encountered when calling layer "USE" (type KerasLayer).

Graph execution error:

JIT compilation failed.
     [[{{node EncoderDNN/EmbeddingLookup/EmbeddingLookupUnique/embedding_lookup/mod}}]] [Op:__inference_restored_function_body_36706]

Call arguments received by layer "USE" (type KerasLayer):
  • inputs=["'Data of a Japanese study of patients with unresectable sacral chordoma showed comparable high control rates after hypofractionated carbon ion therapy only .'"]
  • training=None

Answer: I had this issue, and I solve it by downgrading my TensorFlow version to 2.8.0.
Using this command
pip install tensorflow==2.8.0


Microsoft Storage Space Direct reserve space

Question: I`m using this S2D calculator, which takes reserve space into account.
If I understood correctly, reserve space is only being used for in-place recovery in case a disk fails.
Is it correct that one is able to use this reserve space as storage at the price of missing in-place recovery?
I will use a 2-node cluster, so I think this should not be a problem, right?
Also, I currently have 6x1TB SSD and 2x2TB SSD. What is the best way to devide them between both nodes (for S2D only, no OS drive(s))
Answer:
Is it correct that one is able to use this reserve space as storage at
  the price of missing in-place recovery?

Yes. You will be able to keep up and running while S2D rebalances itself using reserve space. Theoretically, this can save you from data loss in case you wasn't able to replace failed drive in time, and the second drive failure occurred after S2D finished rebalancing. Unfortunately, I didn't manage to find any detailed description of this feature and it's impact on the number of drive failures S2D can tolerate. The chances of loosing your data after the second drive failure are still pretty high.
Your disk layout will be as follows:
3x 1TB SSD per node: contribute into usable capacity.
1x 2TB SSD per node: will be used as reserve space.
You are looking at nearly 3TB usable capacity in such case.
P.S: I can't disagree with @BaronSamedi1958: 2-node Storage Spaces Direct is a weak setup. I don't recommend using it in any serious production.
There are alternative solutions that work better in 2-node configurations:

StarWind VSAN Free - works like a charm in 2-node environments, can be deployed on a bare-metal Windows.
HPE VSA Free - a good piece of software as well, but runs only inside a virtual machine, which leads to performance compromises. 1TB limitation in free version.
Answer:
I will use a 2-node cluster, so I think this should not be a problem, right?

I think you'll have an issue. During one node being down say for maintenance (patch Tuesday?) you don't have anybody to sync your data with, so disk failure will represent catastrophic results. Same thing is going to happen in case of a double disk failure: one disk died and S2D rebalances it using free space, and now second disk dies and you have a data loss.
I'd strongly recommend to bring in at least third or better third and fourth nodes (yes, expensive!) for a fully fault-tolerant S2D cluster. Remember: Microsoft started with 4-node requirement, and brought 3-node & 2-node much later after numerous requests.


Best way to migrate from MySQL to PostgreSQL

Question: I have to migrate a MySQL database to PostgreSQL. I have tried the mysqldump with --compatible = postresql. I have seen that some poeple use ETL like Talend to make the migration but you must describe the migration for all tables... (I have 39 tables...)
Any other idea ?
Thanks in advance
Comment: My team is using Talend.  I know it's a good option but I don't think its free.
Answer: Create the tables by hand, and then script the data inserts with Perl/PHP/Python/etc, and just run through the data, preferably using PDO (to get around Pg's issues with BLOB data).
Comment: Probably the easiest way if `mysqldump` wasn't able to produce anything usable.  Leave out all indexes and constraints until AFTER you load your data to make life easier: You won't have to unwind the dependencies & you'll save lots of time if you're not updating indexes on every insert.
Comment: Nothing automatic ???
Answer: You can do this with Talend.
This Video describes at first how to do use a dynamic scheme for one table, then how to expand to doing a whole database dynamically.
Below is a screen capture of such a job. It connects to the database, grabs the list of tables from a database, and then iterates through those tables.

The trick is selecting a dynamic schema for the tables, as seen below.

Ps: I work for Talend.
Comment: Welcome to SO! We typically ask that answers be self-contained in case their links go dead or are otherwise unavailable. Can you bring in some of the key points from the video here?
Comment: @ceejayoz added some screen captures based on your reply.  Thanks for the suggestion!
Answer: Migration from MySQL to PostgreSQL can be automated with tools like Ispirer Toolkit.


How do I convert from an OpenSSH key to PuTTY format in C#?

Question: I have a key generated by SharpSSH in OpenSSH format.  How do I convert it to PuTTY format in C#?
Answer: See here for how to use puttygen on linux.
You should be able to take the source code for this or the windows version and  and create a windows DLL if one is not available. Then you can pinvoke to access it.
I downloaded the sources from here.


Tensor product of fields

Question:
Suppose $D$ is a finite dimensional skew field over the field $K$. Futher, take $x \in D\setminus K$ and let $L=K(x)$. My question: is $D\otimes_K L$ a field?

I think not. However I can't seem to give a logical reasoning behind this.
Also, would it help knowing that $L \otimes_K L$ is not a field?
Comment: How is the multiplication defined? Do you mean, 'are these *skew* fields'?
Comment: If you know $L \otimes_K L$ is not a field then don't you get a counterexample just taking D=L?
Comment: @Berci - Indeed I meant to ask whether $D\otimes_K L$ is a skew field.
Comment: @NoahSnyder - I thought that you can't just assume $D = L$, right? =)
Comment: Dear @Eric, Taking $D=L$ will give you a counterexample, but as my answer shows, the answer is "$D\otimes_KL$ is never a field," no matter what $D$ is. Of course I proved this by reducing to the case $D=L$.
Comment: You should phrase the question more precisely.  If you're asking "is the claim $D \otimes_K L$ a skew field true or false" then exhibiting a single counterexample is enough (so you can take D=L).  If you're asking "is $D \otimes_K L$ ever a skew field then you have to treat all cases.
Answer: The ring $L$ is a field (i.e. not a skew field) since $K$ is a field and you're only adjoining one (algebraic) element. Write $L=K[T]/(f(T))$ where $f$ is the minimal polynomial of $x$ over $K$. Note that $f$ has degree $\geq 2$ since $x\notin K$. Then $L\otimes_KL=L[T]/(f(T))$, and since $f(T)$ can be factored as $(T-x)^kg(T)$ in $L[T]$ with $x$ not a root of $g$, i.e., $T-x$ and $g(T)$ relatively prime in $L[x]$, the ring $L[T]/(f(T))$ is isomorphic to $L[T]/(T-x)^k\times L[T]/(g(T))$, which is not a domain, because either $k\geq 2$, in which case you have nilpotents, or $k=1$ and $g(T)\neq 1$, in which case you at least have zero divisors.
In general, if $L/K$ is non-trivial, then $L\otimes_KL$ is not a field. If $L$ is algebraic, pass to a finite subextension and use the argument above. If $L$ is not algebraic, then a theorem of Grothendieck says that the dimension of $L\otimes_KL$ has Krull dimension equal to the transcendence degree of $L$, so not zero (there is almost certainly a much easier way to see this, i.e., reducing to the case $K(T)\otimes_KK(T)$, but I'm not seeing it at the moment).
EDIT: Here's an argument that works in general for the assertion that $L\otimes_KL$ is not a field when $L/K$ is non-trivial. The argument was suggested in the comments by YACP. If $L\neq K$, then there exist distinct elements $\alpha\neq\beta\in L$ which are $K$-linearly independent. We may assume they are contained in a $K$-basis for $L$, in which case $1\otimes\alpha$ and $1\otimes\beta$ are $L$-linearly independent elements of $L\otimes_KL$. In particular, $\beta\otimes\alpha-\alpha\otimes\beta\neq 0$ in $L\otimes_KL$. Now, the $L$-linear multiplication map $x\otimes y\mapsto xy:L\otimes_KL\rightarrow L$ is non-zero ring map (since the target is non-zero). Since $\beta\otimes\alpha-\alpha\otimes\beta$ clearly lies in the kernel, we see that $L\otimes_KL$ has a non-trivial, proper ideal (namely the kernel). Therefore it is not a field.
It follows that $D\otimes_KL$ is not a skew field. If it were, then $L\otimes_KL$, being a commutative subring, would be a domain. But it isn't.
Comment: I don't understand if you have troubles with the reduction to the case $K(T)\otimes_KK(T)$ when the extension $K\subset L$ is not algebraic or with the proof that this ring is not a field. In the second case, if $p:K(T)\otimes_KK(T)\to K(T)$ is defined by $p(a\otimes b)=ab$, then $p$ is a surjective ring homomorphism. If $p:K(T)\otimes_KK(T)$ is a field, then $\ker p=0$. But $1\otimes T-T\otimes 1\in\ker p$ and $1\otimes T-T\otimes 1\neq 0$.
Comment: Yeah, sure, that works. Thanks. I wasn't talking about the reduction, I was talking about the proof that it's not a field. But it was tangential to my answer. I just added it because it was vaguely related. In fact that same argument works with $K(T)$ replaced by any extension $L\neq K$, the point being that you can choose two $K$-linearly independent elements $\alpha_1,\alpha_2$. Then you can put $\{1\otimes\alpha_1,1\otimes\alpha_2\}$ inside an $L$-basis for $L\otimes_KL$, and you win by the same argument.
Comment: @KeenanKidwell - Thank you Sir!
Comment: Hmm, just curious, in general, given a skew field $D$, and an extension $L$ of $K$, when is $D\otimes_K L$ a skew field? Can this even occur?

Thanks a lot. I appreciate the responses!
Answer: In the following $D$ is a field. Then $D\otimes_KL\cong D[X]/fD[X]$, where $f$ is the minimal polynomial of $x$ over $K$. I see no reason for $f$ to stay irreducible in $D$. So my answer is NO.

Tensor product of fields


Memoryless property with any random wait time

Question: We see here a proof of the random-time memoryless property $P(X>T+s|X>T)=P(X>s)$ where $E\sim Exp(\lambda)$ and $T\ge 0$ is a continuous random variable independent of $E$.
The proof, however, relies upon the existence of a pdf $f_T$ for $T$ (and hence the continuity of $T$); this places restrictions on the random variable $T$ that I'd like to avoid. Can we prove this result independent of such a pdf for $T$? I imagine conditioning on $E$ instead should be possible in deriving a proof, but can't seem to find anything on this.
Answer: You do not require $T$ to be continuously distributed.   It is only required to be almost surely non-negative and independent from $X$.
For instance: Let $T$ be a discrete non-negative integer-valued random variable ($T\in\Bbb N$).
$$\begin{align}\mathsf P(X\gt T+s\mid X\gt T) &=\dfrac{\mathsf P(X\gt T+s)}{\mathsf P(X\gt T)}\\[1ex]&=\dfrac{\displaystyle\sum_{t\in\Bbb N}\mathsf P(X\gt t+s\mid X\gt t)\,\mathsf P(T=t)}{\displaystyle\sum_{t\in\Bbb N}\mathsf P(X\gt t\mid X\gt t)\,\mathsf P(T=t)}\\[1ex]&~~\vdots\\[1ex]&=\mathsf P(X\geqslant s)\end{align}$$
So more generally.
$$\begin{align}\mathsf P(X\gt T+s\mid X\gt T) &=\dfrac{\mathsf P(X\gt T+s)}{\mathsf P(X\gt T)}\\[1ex]&=\dfrac{\mathsf E(\mathsf E(\mathbf 1_{X\gt T+s}\mid T))}{\mathsf E(\mathsf E(\mathbf 1_{X\gt T}\mid T))}\\[1ex]&=\dfrac{\mathsf E(\mathrm e^{-\lambda(T+s)})}{\mathsf E(\mathrm e^{-\lambda(T)})}\\[1ex] &= \mathsf e^{-\lambda s}\\[1ex]&=\mathsf P(X\gt s)\end{align}$$


How to avoid "An illegal choice has been detected" when updating select list values via ajax?

Question: I have four entity reference fields to user entity in a form. Host form is node edit form.
Three of them are select lists, last is Inline Entity Form.
After adding a user entity via IEF I'm trying to update select lists values:
function ebep_users_feature_users_list_ajax($form, $form_state) {

  $ief = array_shift($form_state['inline_entity_form']);
  $options = array('_node' => t('- None -'));
  $commands = array();

  foreach($ief['entities'] as $data) {
    $options[$data['entity']->uid] = $data['entity']->name;
  }

  foreach(_ebep_users_feature_getUserListFieldNames() as $fieldName) {
    $form[$fieldName]['und']['#options'] = $options;
    $commands[] = ajax_command_replace('#'.$fieldName.'_wrapper', drupal_render($form[$fieldName]));
  }

  return array('#type' => 'ajax', '#commands' => $commands);
}

It works, but when I try to add another user via IEF I am getting:

An illegal choice has been detected. Please contact the site
  administrator.
Comment: have any of the `Related` questions on here listed to the right resolved this?
Comment: @Jimajamma it seems that on ajax callback form rebuild is not work. How can I enable it? $form_state['rebuild'] = TRUE do nothing...
Comment: @Jimajamma so related solutions doesn't work
Comment: I've answered your question here since it's a duplicate question https://drupal.stackexchange.com/questions/15989/resolve-the-error-an-illegal-choice-has-been-detected/125233#125233
Comment: Possible duplicate of [Dynamic select list in the form (dependent dropdown)](https://drupal.stackexchange.com/questions/10112/dynamic-select-list-in-the-form-dependent-dropdown)
Answer: --- Original answer. Is wrong, check update below.
Just set
$bla['#validated'] = TRUE

On the select that will be updated with AJAX.
Checkout "Illegal Choice has been detected"
--- Update 17 Dec 2019 ---
Actually that was not good advice, that was a long time ago, now I know better.
Ajax callback function is supposed to only return the piece of form that has changed or some ajax commands.
In this case form modification must be made on the form function or a form alter hook. Form building and validation functions are run each time an ajax callback is called. Just check $form_state on your form build or alter function and adjust values accordingly.
See Resolve the error "An illegal choice has been detected..."
Comment: If I remember well I tried this, without a success in my case, thanks
Comment: I'm afraid this doesn't work for me either.
Comment: Does this not make the form less secure?
Comment: Yes, all previous comments are right. Answer has been updated.
Answer: I have faced this problem number of times in Drupal 6, changing the values of Select list via Ajax.
Here is what you can do is

If possible, try to insert all the possible values in the in the Field API, you need to edit that field, and then when you change the values, you will have to make sure that only the listed values are in the list.
Solution that I implemented was, you can change the field type from Select list to textfield, from Field API, and ask Drupal to save the value as is. Now, on form runtime, you will have to alter the form, change the type to select list, and push in options, which you want to. While submission as well, you will have to assign the correct value required by the field, that will be saved in DB as is. Make sure your submit handler is called before the default form submit handler, for that you may use array_merge

If first solution works for you, you will save a lot of time coding and testing things. BUT if the list in the drop down is dynamic and you have no control over it, you might have to go with second solution.
Do post if you face any issues, I have done quite lot of work on this problem, for my project, and I did for ~50 forms, PHEW !!!  :)
Answer: I have found the best way round this is to set the #value on the select list.
If we have the value in formstate and it is in our options then we will not get an error. If our value is not in the options then select the first option in our options and use that.
$form['example'] = array(
    '#type' => 'select',
    '#title' => t('Example'),
    '#options' => $options,
    '#value' => isset($form_state['values']['example']) && in_array($form_state['values']['example'],$options)?$form_state['values']['example']:key($options),
  );

Answer: My solution:
/**
 * Implements hook_form_FORM_ID_alter()
 */
function ebep_users_feature_form_ebep_exhibitor_profile_node_form_alter(&$form, &$form_state, $form_id) {

  foreach(_ebep_users_feature_getUserListFieldNames() as $fieldName) {
    $form[$fieldName]['und']['#prefix'] = '
';
    $form[$fieldName]['und']['#suffix'] = '
';
    $form[$fieldName]['und']['#options'] = _ebep_users_feature_getOptionsValuesFromIEFList($form_state);
  }

  $form['#attached']['css'] = array(
    drupal_get_path('module', 'ebep_users_feature') . '/assets/styles.css',
  );

  $form['#attached']['js'] = array(
    drupal_get_path('module', 'ebep_users_feature') . '/assets/scripts.js',
  );

  $form['users_refresh'] = array(
    '#type' => 'submit',
    '#value' => t('Refresh users list'),
    '#ajax' => array(
      'callback' => 'ebep_users_feature_users_list_ajax',
    ),
  );
}

function ebep_users_feature_users_list_ajax($form, $form_state) {

  $commands = array();

  foreach(_ebep_users_feature_getUserListFieldNames() as $fieldName) {
    $form[$fieldName]['und']['#options'] = _ebep_users_feature_getOptionsValuesFromIEFList($form_state);
    $commands[] = ajax_command_replace('#'.$fieldName.'_wrapper', drupal_render($form[$fieldName]));
  }

  return array('#type' => 'ajax', '#commands' => $commands);
}

function _ebep_users_feature_getOptionsValuesFromIEFList($form_state) {
  static $options = array();

  if (empty($options)) {
    $ief = array_shift($form_state['inline_entity_form']);
    $options['_node'] = t('- None -');

    foreach($ief['entities'] as $data) {
      $options[$data['entity']->uid] = $data['entity']->name;
    }
  }

  return $options;
}

Answer: In your ajax callback, add:
...

drupal_get_messages();
form_get_errors();

return array('#type' => 'ajax', '#commands' => $commands);

As a security precaution, the core _form_validate() function checks if an element's #options key has changed from what what was set in the original build (which they have). By calling drupal_get_messages() and form_get_errors() we basically tell Drupal to ignore any errors/messages while running our ajax request. :)
Comment: Error message is gone but the select element still contains the error class.How to remove or prevent that?
Comment: This is the Drupal equivalent of putting tape over a warning light on your vehicle's dash board.


how to show a message after a node form is submitted

Question: How do I show a message (notice or alert) after the node form is submitted and saved?
I'm writing a module that synchronizes the node content with a remote endpoint. All working good. But, if for any reason the sync fails, I want to show a message on the page the user is redirected to.
My problem is that I don't find the hook or function which is invoked after the form is saved to databases but before the redirect happens, where I hopefully can set the message I want.
Comment: Hello. Have you tried anything? Is there any code we can see? And have you seen the api docs for [`drupal_set_message`](https://api.drupal.org/api/drupal/includes!bootstrap.inc/function/drupal_set_message/7)?
Comment: My problem is that I don't know where to put a call to `drupal_set_message`. I'd like to know if there's a hook I can call **after** the form has been saved to database but **before** the redirect.
Comment: So you want some kind of a confirmation step? Please see if my answer is sufficient or not yet.
Comment: @FabrizioRegini See [`hook_node_insert()`](https://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook_node_insert/7) and [`hook_node_update()`](https://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook_node_update/7) for node API methods, or [`hook_form_alter()`](https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_form_alter/7) if you'd rather alter the submission of the node add/edit form itself
Comment: I did already @Clive but what I understood is that they are triggered either **during** a transaction or **before** the query is saved to db.
Comment: Might be an idea to add your code to the question, it'll help to understand what you're trying to do. Why does your message need to be set outside of the transaction in particular? You understand that you can't stop a transaction right in the middle, then show a message, then resume the transaction again afterwards? Or am I misunderstanding what you're asking?
Answer: You can create an additional submission callback.  Not sure if it will run late enough for you.  May be worth a shot.
Create a form alter hook using hook_form_alter();
Within there add an additional submit function to the #submit array
Example:
hook_form_alter(&$form, &$form_state, $form_id) {
  $form['#submit'][] = 'custom_submit_function';
}

function custom_submit_function($form, &$form_state) {
  drupal_set_message('your message');
}

You could try going 1 step further and adding the submit hook to #submit in the #after_build.  This will ensure it is the very last submit callback (unless other higher weighted modules also use the afterbuild)
Example:
hook_form_alter(&$form, &$form_state, $form_id) {
  $form['#after_build'][] = 'custom_afterbuild_function';
}

function custom_afterbuild_function($form, &$form_state) {
  $form['#submit'][] = 'custom_submit_function';
}

function custom_submit_function($form, &$form_state) {
  drupal_set_message('your message');
}

I hope this helps
[update] added drupal_set_messages to code examples.


jquery plugin does not work on multiple elements - options overwritten

Question: I've tried to make my first jquery plugin (a lightbox). It works on a single element just the way I want but if I use multiple elements it overwrites my options.
here is my current code. it doesn't seem to work on jsFiddle because of the layout.
http://jsfiddle.net/BjwCm/
you can download the code with a working (failing) sample here:
http://frumbert.org/files/frumbox.zip
I can see that I'm somehow overwrite the options in the default object when I bind to a second object but don't know what i've done wrong. I've tried moving where click is bound but can't make it work.
Answer: $this, declared in the outermost closure and used throughout, represents the last element on which FrumBox is instantiated.
Personally, I wouldn't try to fix the code as it stands. Instead adopt jQuery's "Best Practices" pattern. Here's my template based on the example given:
(function($){
    // **********************************
    // ***** Start: Private Members *****
    var pluginName = 'xxxxx';
    // ***** Fin: Private Members *****
    // ********************************

    // *********************************
    // ***** Start: Public Methods *****
    var methods = {
        init : function(options) {
            //"this" is a jquery object on which this plugin has been invoked.
            return this.each(function(index){
                var $this = $(this);
                var data = $this.data(pluginName);
                // If the plugin hasn't been initialized yet
                if (!data){
                    var settings = {
                    };
                    if(options) { $.extend(true, settings, options); }

                    $this.data(pluginName, {
                        target : $this,
                        settings: settings
                    });
                }
            });
        },
        myMethod_1 : function(){.....},
        myMethod_2 : function(){.....}
    };
    // ***** Fin: Public Methods *****
    // *******************************

    // *****************************
    // ***** Start: Supervisor *****
    $.fn[pluginName] = function( method ) {
        if ( methods[method] ) {
            return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof method === 'object' || !method ) {
            return methods.init.apply( this, arguments );
        } else {
            $.error( 'Method ' + method + ' does not exist in jQuery.' + pluginName );
        }
    };
    // ***** Fin: Supervisor *****
    // ***************************
})( jQuery );

Notes:

Add further private members and methods as required.
Public members (methods) are privileged (they have access to private members).
To maintain chainability, be sure to adopt the return this.each(function(index){...}) pattern in every method, except any that return a specific value.
Arguably the hardest aspect of developing with this pattern (and others) is being aware of what this refers to in every context. Keep your wits about you.
Be prepared to use javascript Function.call() and Function.apply methods. Make sure you understand them.
The supervisor is difficult to understand at first glance but doesn't need to be
modified. It is a cool chunk of code.
Instantiate the plugin on DOM element(s) with $(selector).pluginNmae() or $(selector).pluginNmae(options), where options is an object literal "map".
Invoke methods on initialised DOM element(s) with $(selector).pluginNmae('methodName', ...)
An example of this pattern can be found in the selected answer here (including a link to a fiddle).
Comment: Yeah I see that you're correct. I was just coming to the same conclusion. I knew that $this must be being scoped "too high" and as such it would be overwriting the previous setting, therefore screwing it up. Your supervisor also answers what would have been my next question about calling different methods properly.

I really wasn't sure what "the best practice" method was (often debated it seems) - I had looked at a few : https://github.com/zenorocha/jquery-plugin-patterns and took one I recognised reasonably well as a starting point. I think this is what messed me up.
Comment: @frumbert There's certainly no definitive plugin pattern but some are better than others. Thanks for the github link, I hadn't found it before. When I get time I will look through and see what I can learn. I like the pattern I posted above because I trust it but also because I have got used to it. Being a conservative sort, I will probably stick with it for the foreseeable future.
Comment: hmm, my updated code - http://jsfiddle.net/BjwCm/1/ - has problems. My selector is $(".external-links a"); calling open will fire on the last "a" matched not the specific instance.
Comment: Sorry to keep pestering about this, but if you take a look at this new version - http://jsfiddle.net/BjwCm/2/ - I have found that it was executing "each" of the options when using a selector with multiple matches. So I have to perform the each/bind in the caller function (see test case code, bottom of fiddle). This works, but seems "messy", and appears to negate the need for the each inside the plugin. What was the intended use of the inner each in your plugin template?
Comment: In methods, `return $(this).each(function(){...})` iterates through the jQuery selection made with `$(selector).pluginName('methodName')`. Selections are not remembered because the selector may well be different every time `$(selector).pluginName('methodName')` is called.


To prove convexity for a linear fractional function under some conditions

Question: I know that generally, a linear-fractional function is quasiconvex, however, I wonder if it is possible to prove this linear-fractional function to be convex, under the following additional conditions?
The function f(x) is formulated as
f(x) = $\frac{a_1x_1+...a_mx_m}{a_1x_1+...a_mx_m+a_{
m+1}x_{m+1}...+a_nx_n}$
the additional conditions are

$a_1,...a_n$ are constant positive numbers
m < n
$0 < x_i <1$, for i = 1...n
all the variables and constants are in R

If not, under what conditions can the linear-fractional function f(x) be convex?
Thank you
Comment: Are you sure about the minus sign in the definition of your function $f$? For a function to be convex, it needs to be convex at any point in any direction. If you take $n=m+1$, you can have something of the form $-1/(1+x)$ which is concave.
Comment: Thank you, and you are right, I have modified the function $f(x)$, in this way, is this possible to prove it could be convex?
Answer: Lets take for simplicity function $f(x,y)=\frac{ax}{ax+by}$.
The second derivatives: $\frac{\partial^2}{\partial x^2}f(x,y) = -\frac{2a^2by}{(ax+by)^3}, \quad\frac{\partial^2}{\partial y^2}f(x,y) = \frac{2ab^2x}{(ax+by)^3}, \quad \frac{\partial^2}{\partial x \partial y}f(x,y) = \frac{ab(ax-by)}{(ax+by)^3}$
The Hessian at point $(x,y)=\left(\frac{b}{a+b}, \frac{a}{a+b}\right)$ is $\begin{pmatrix} (-) & 0 \\ 0 & (+)\end{pmatrix}$ - not a possitive definite matrix. This should proove that function can not be convex.
In my research I am interested in functions of the form $g(x,y) = \frac{1}{1+ax+by}$.
The derivatives are $\frac{\partial^2}{\partial x^2}f(x,y) = \frac{2a^2}{(1+ax+by)^3}, \quad\frac{\partial^2}{\partial y^2}f(x,y) = \frac{2b^2}{(1+ax+by)^3}, \quad \frac{\partial^2}{\partial x \partial y}f(x,y) = \frac{2ab}{(1+ax+by)^3}$.
The Hessian at point $(x,y)$ is $\frac{2}{(1+ax+by)^3}\begin{pmatrix} a^2 & ab \\ ab & b^2 \end{pmatrix} = \frac{2}{(1+ax+by)^3} \begin{pmatrix}a \\ b\end{pmatrix} \begin{pmatrix}a&b\end{pmatrix}$ - a possitive semidefinite matrix in the unit cube. This can be generalized to more than 2 dimensions.


How to compute the Lipschitz constant for the multivariate function $f(x,y)=1-xy$?

Question: How to compute the Lipschitz constant for the multivariate function $f(x,y) = 1 - xy$?
I know the definition for one variable, but what is its definition for multivariate functions?
Comment: @DanieleA The wiki page only contains information for univariate function.
Comment: There is also the definition for a general metric space. In your case, a function $f\colon \mathbb{R}^2 \to \mathbb{R}^2$ is said to be Lipschitz continuous if there exists a $C>0$ such that $|f(x)-f(y)|\leq C\cdot |x-y|$ for all $x,y\in \mathbb{R}^2$. By $|\cdot |$ you could take the standard euclidean norm on $\mathbb{R}^2$.
Comment: https://en.wikipedia.org/wiki/Lipschitz_continuity
Answer: The function
$f(x,y)= 1 - xy \tag{1}$
is differentiable, and its derivative is both easy to compute and estimate; there is a more-or-less systematic procedure for finding a Lipschitz constant in such cases.  Allow me to explain:
Let us set
$\mathbf r = \begin{pmatrix} x \\ y \end{pmatrix}; \tag{2}$
then we may also write
$f(\mathbf r) = 1 - xy. \tag{3}$
With this notation, Lipschitz continuity may be expressed via the inequality
$\Vert f(\mathbf r_1) - f(\mathbf r_2) \Vert < K \Vert \mathbf r_1 - \mathbf r_2 \Vert \tag{4}$
for a suitably chosen constant $K > 0$ and any $\mathbf r_1$, $\mathbf r_2$ within some open set $\Omega$ on which $f(\mathbf r)$ is defined; but there is one caveat which should be mentioned:  when the function of interest such as $f(\mathbf r)$ is unbounded on $\Omega$, then quite often there will be no finite $K$ such that (4) holds for all $\mathbf r_1, \mathbf r_2 \in \Omega$; in such circumstances we may, however, be able to find a value of $K$ such that (4) holds if we restrict the set in which $\mathbf r_1$, $\mathbf r_2$ lie to be some suitable subset of $\Omega$; often, an open ball $B(\mathbf x, \rho)$, centered at $\mathbf x$ and with radius $\rho$, so that $B(\mathbf x, \rho) = \{ \mathbf y \mid \Vert \mathbf y - \mathbf x \Vert < \rho \}$, is chosen, provided $\mathbf x$ and $\rho$ are such that $B(\mathbf x, \rho) \subset \Omega$.  Then the unqualified assertion of Lipschitz continuity, i.e. that (4) holds for all $\mathbf r_1, \mathbf r_2 \in \Omega$, is replaced by the requirement that (4) apply for all $\mathbf r_1, \mathbf r_2 \in B(\mathbf x, \rho) \subset \Omega$ for any $\mathbf x \in \Omega$ with some suitable $\rho > 0$; the key here is that $K = K_{\mathbf x}$ may now depend on $\mathbf x$, as may $\rho = \rho_{\mathbf x}$.  Under such circumstances, we say that $f(\mathbf r)$ is locally Lipschitz on the domain $\Omega$; possession of this property is sufficient to guarantee that an ordinary differential equation of the form
$\dot{\mathbf r} = f(\mathbf r) \tag{5}$
has a unique solution $\mathbf r(t)$ satisfying
$\mathbf r(t_0) = \mathbf r_0 \tag{6}$
through any point $\mathbf r_0 \in \Omega$; such local solutions may indeed be pieced together to form solutions on maximal extent in $\Omega$; this is one of the main applications of the concept of local Lipschitz continuity.
We give examples to illustrate these ideas.  Let
$\Omega = (-\dfrac{\pi}{2}, \dfrac{\pi}{2}) \tag{7}$
and let
$f(x) = \tan x \tag{8}$
defined on $\Omega$.  $f(x)$ cannot satisfy a Lipschitz condition on $\Omega$, no matter how large the value of $K$ may be, for, taking $x_1 \in \Omega$ we see that, for any $K > 0$,
$K \vert x_2 - x_1 \vert < K\vert \dfrac{\pi}{2} - x_1  \vert \tag{9}$
since $x_2 < \pi / 2$.  But
$\vert \tan x_2 - \tan x_1 \vert \to \infty \; \text{as} \; x_2 \to \dfrac{\pi}{2}, \tag{10}$
so that
$\vert \tan x_2 - \tan x_1 \vert < K \vert x_2 - x_1 \vert \tag{11}$
cannot possibly be satisfied for all $x_1, x_2 \in \Omega$.  On the other hand, for any $x_0 \in \Omega$, if $\rho > 0$ is sufficiently small that $[x_0 - \rho, x_0 + \rho] \subset \Omega$, we can take
$K_{x_0} > \sup \{ \sec^2 x = (\tan x)', x \in [x_0 - \rho, x_0 + \rho] \}$
$= \max(\sec^2(x_0 - \rho), \sec^2(x_0 + \rho)), \tag{12}$
and then
$\mid \tan x_2 - \tan x_1 \mid < K_{x_0} \mid x_2 - x_1 \mid \tag{13}$
for $x_1, x_2 \in (x_0 - \rho, x_0 + \rho)$.  (13) holds by virtue of the fact that the derivative of $\tan x$ is $\sec^2 x$, as we shall see in somewhat greater generality below; this shows that $\tan x$ is in fact locally Lipschitz continuous on $\Omega$.  An example with two variables $x$ and $y$ may now easily be had by taking $f(x, y) = (\tan x)(\tan y)$ on the open set $(-\pi / 2, \pi / 2) \times (-\pi / 2, \pi / 2) \subset \Bbb R^2$; we refrain for the moment from presenting all the details in this two-dimensional case since they follow directly from the general result which will next be addressed.
We show that any $f(\mathbf r) \in C^1(\Omega, \Bbb R)$ is locally Lipschitz continuous throughout $\Omega$ for any domain $\Omega \subseteq \Bbb R^2$; to this end, let $\mathbf r_0 \in \Omega$ and select $\rho > 0$ sufficiently small that the closed ball $\bar B(\mathbf r_0, \rho) \subset \Omega$.  For $\mathbf r_1, \mathbf r_2 \in B(\mathbf r_0, \rho) \subset \Omega$ let $\gamma:[0, 1] \to B(\mathbf r_0, \rho)$ be the path
$\gamma(t) = (1 - t)\mathbf r_1 + t\mathbf r_2 \tag{14}$
from $\mathbf r_1$ to $\mathbf r_2$ in $B(\mathbf r_0, \rho)$.  Considering $f(\gamma(t))$, we have
$\Vert f(\mathbf r_2) - f(\mathbf r_1) \Vert = \Vert f(\gamma(1)) - f(\gamma(0)) \Vert = \Vert \int_0^1 \dfrac{df(\gamma(t))}{dt} dt \Vert \tag{15}$
and
$\dfrac{df(\gamma(t))}{dt} = \nabla f(\gamma(t)) \cdot \gamma'(t) = \nabla f(\gamma(t)) \cdot (\mathbf r_2 - \mathbf r_1); \tag{16}$
from (16) we have
$\Vert \int_0^1 \dfrac{df(\gamma(t))}{dt} dt \Vert = \Vert \int_0^1 (\nabla f(\gamma(t)) \cdot (\mathbf r_2 - \mathbf r_1))dt \Vert \le \int_0^1 \Vert \nabla f(\gamma(t)) \Vert \Vert \mathbf r_2 - \mathbf r_1 \Vert dt$
$= \Vert \mathbf r_2 - \mathbf r_1 \Vert \int_0^1 \Vert \nabla f(\gamma(t)) \Vert dt < K_{\mathbf r_0}  \Vert \mathbf r_2 - \mathbf r_1 \Vert \tag{17}$
for any finite $K_{\mathbf r_0} > \sup \{\Vert \nabla f(\mathbf r) \Vert \mid \mathbf r \in B(\mathbf r_0, \rho) \}$; that such a $K_{\mathbf r_0}$ exists is a consequence of the fact that $f \in C^1(\Omega, \Bbb R)$ implies $\Vert \nabla f \Vert$, being continuous, is in fact bounded on compact subsets of $\Omega$, of which  $\bar B(\mathbf r_0, \rho)$ is but one example.  It may be helpful to note that the vector form of the fundamental theorem of calculus has been used in establishing (15), as has the chain rule been deployed to arrive at (16).  Furthermore, a technique for obtaining a local Lipschitz constant $K_{\mathbf x}$ for any $x \in \Omega$ is implicit in the preceding argument: simply choose $K_{\mathbf x} > \sup \{\Vert \nabla f(\mathbf r) \Vert \mid \mathbf r \in B(\mathbf x, \rho) \}$ for $\bar B(\mathbf x, \rho) \subset \Omega$.
Bearing the above discussion in mind, we return to $f(\mathbf r) = 1 - xy$.  Whereas there is no global Lipschitz constant $K$ valid on all of $\Omega = \Bbb R^2$ in this case, as has been shown by xavierm02 and Christian Blatter in their answers, $f(\mathbf r)$ is in fact locally Lipschitz.  To see this, observe that $\nabla f = (-y, -x)^T$ so that $\Vert \nabla f \Vert = \sqrt{x^2 + y^2}$; thus $\Vert \nabla f \Vert$ is bounded on any closed ball $\bar B(0, R)$ centered at the origin; thus for $\mathbf x \in \Bbb R^2$ and for any $\rho \in \Bbb R$ taking $R > \Vert \mathbf x \Vert + \rho$ we have $\Vert \nabla f \Vert < R$ in $\bar B(\mathbf x, \rho)$; taking $K_{\mathbf x} = R$ thus provides a local Lipschitz constant at $\mathbf x$.
Just to round things out, consider once again the previously mentioned example
$f(\mathbf r) = (\tan x)(\tan y), \mathbf r \in \Omega = (\dfrac{-\pi}{2}, \dfrac{\pi}{2})^2; \tag{18}$
by holding $y = y_0 \ne 0$ constant, it is easy to see that there can be no Lipschitz constant for $f(\mathbf r)$ on $\Omega$; the argument is essentially the same as that given for $\tan x$ above.  Also, $\nabla f = ((\sec^2 x)(\tan y), (\tan x)(\sec^2 y))^T$ for every $\mathbf r \in \Omega$ and thus
$\Vert \nabla f \Vert = \sqrt{(\sec^4 x)(\tan^2 y) + (\tan x)^2 (\sec^4 y)}; \tag{19}$
given $\mathbf r = (x, y)^T \in \Omega$, it is easy to find a bound for $\nabla f$ on $\bar B(\mathbf r, \rho) \subset \Omega$, $\rho$ sufficiently small, by noting that $[x - \rho, x + \rho] \times [y - \rho, y + \rho] \subset \Omega$ as well.  I leave the simple details to any reader interested enough to execute them.
Hope this helps.  Cheerio,
and as always,
Fiat Lux!!!
Comment: I lost on $r = \binom{x}{y}$ — you didn't mean a binomial coefficient, did you? Otherwise the following $f(r) = 1-xy$ doesn't make sense because $x$ and $y$ would never be equal to anything.
Comment: @Hi-Angel:  $\mathbf r = \begin{pmatrix} x \\ y \end{pmatrix}$ is the two-vector whose entries are $x$ and $y$.
Answer: As $f$ is a quadratic polynomial in $x$ and $y$ you cannot expect that there is a globally valid Lipschitz constant for $f$, because such a constant would allow only a linear increase of $f$ on a large scale.
For a formal proof consider the point ${\bf z}_0:=(x_0,0)$ and the "nearby" point ${\bf z}:=(x_0,h)$, $\>h>0$. Then $|{\bf z}-{\bf z}_0|=h$ and
$$|f({\bf z})-f({\bf z_0})|=|(1-x_0h)-1|=|x_0|\>h=|x_0|\>|{\bf z}-{\bf z}_0|\ .$$
Since $|x_0|$ can be arbitrarily large it follows that there is no universal $C>0$ such that
$$|f({\bf z})-f({\bf z_0})|\leq C\>|{\bf z}-{\bf z}_0|$$
for all ${\bf z}$, ${\bf z}_0\in{\mathbb R}^2$.
Answer: There is no Lipschitz constant.
Suppose there was one. $\forall x_1,y_1,x_1,y_2 \in \Bbb R, |(1- x_1y_1)+(1-x_2y_2)|\le C \|(x_1,y_1)-(x_2,y_2)\|$
$|x_1y_1-x_2y_2|\le C \|(x_1,y_1)-(x_2,y_2)\|$
Take $x_1=x_2=2C$
$|2Cy_1-2Cy_2|\le C \|(2C,y_1)-(2C,y_2)\|=C|y_1-y_2|$
$2C|y_1-y_2|\le C|y_1-y_2|$
Take $y_2\not=y_1$
$2C\le C$ which is absurd since $C>0$
Comment: Can we find an $L$ if we restrict the domain of this function, say, for example, $[-1,1] \times [-1,1]?$


SQLite não está criando uma tabela

Question: Imagens do ERRO que aparece.
SQLite não está criando uma tabela e não consigo resolver o erro, se alguém puder me ajudar
Comment: Detalhe melhor seu problema informando o trecho do código (texto não imagem) onde o erro ocorre. Prefira informar o texto do erro ao invés da imagem.
Answer: Pelo código que está sendo exibido na mensagem de erro, você está tentando fazer uma inserção na tabela table.
Porém está criando uma tabela com outro nome.
O trecho de código do insert não está na pergunta, vendo pela mensagem de erro exibida o comando correto seria:
INSERT INTO tabela (id, nome) VALUES (?,?)

Comment: ok, deu certo!!

SQLite não está criando uma tabela


Setting DataGridRow RowDetails visibility after toggling between TabItems

Question: I have a TabControl, in each TabItem there is a DataGrid. Each DataGridRow has a button on the DataGridRowHeader, which expands and collapses the RowDetails.
As I use the row details expansion functionality, so have set the VirtualizingPanel ScrollUnit to Pixel, so scrolling is a bit more natural.
The program captures which rows have been expanded in an ObservableCollection<int> which holds the row index to expand.
When I toggle to a new TabItem and back to the original TabItem, it loses which rows have been expanded.
Upon the DataContext being changed, I'd like to use the ObservableCollection to reset the expanded rows. I have tried this in the DataGrid DataContextChanged event.
public class DataGridBehaviors : Behavior<DataGrid>{
    protected override void OnAttached(){
        base.OnAttached();
        this.AssociatedObject.DataContextChanged += DataGrid_DataContextChanged;
    }

    protected override void OnDetaching(){
        this.AssociatedObject.DataContextChanged -= DataGrid_DataContextChanged;
        base.OnDetaching();
    }

    private void DataGrid_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e){
        ModuleGeometry oldModuleGeometry = (ModuleGeometry)e.OldValue;
        ModuleGeometry newModuleGeometry = (ModuleGeometry)e.NewValue;

        Task.Factory.StartNew(() => {
            PerformRowExpansions(newModuleGeometry);
        });

        ScrollViewer scrollViewer = GetVisualChild<ScrollViewer>(this.AssociatedObject);
        if (scrollViewer != null){
            /*
             * do some stuff
             */
        }
    }

    private void PerformRowExpansions(ModuleGeometry newModuleGeometry){
        ObservableCollection<int> tempExpandedIndexes = new ObservableCollection<int>(newModuleGeometry.ExpandedIndexes);
        newModuleGeometry.ExpandedIndexes = new ObservableCollection<int>();

        if (this.Dispatcher.CheckAccess()){
            foreach (int index in tempExpandedIndexes)
            {
                DataGridRow row = this.AssociatedObject.ItemContainerGenerator.ContainerFromIndex(index) as DataGridRow;
                row.DetailsVisibility = Visibility.Visible;
            }
        }
        else{
            this.Dispatcher.Invoke(new Action(() =>{
                foreach (int index in tempExpandedIndexes){
                    DataGridRow row = this.AssociatedObject.ItemContainerGenerator.ContainerFromIndex(index) as DataGridRow;
                    row.DetailsVisibility = Visibility.Visible;
                }
            }));
        }
    }

    private static T GetVisualChild<T>(DependencyObject parent) where T : Visual{
        T child = default(T);

        int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
        for (int i = 0; i < numVisuals; i++){
            Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
            child = v as T;
            if (child == null)
                child = GetVisualChild<T>(v);
            if (child != null)
                break;
        }
        return child;
    }
}

However, it doesn't like doing this on rows that are not currently in the VirtualizingPanel.
How can I accomplish this?
Should I just do the expand the currently virtualized rows?
Should the DataGrid ScrollViewer be manipulated programmatically as well? How can I account for the rows not visible in the ScrollViewer?
Is there another object, other the DataGridRow that I should be setting the RowDetails Visibility to?
Answer: There are no DataGridRow containers for the rows that are not currently in the VirtualizingPanel. That's how the virtualization works.
If you want to persist some information between tab switches, you should store the data to be persisted in your view models. You could for example bind the Button in the DataGridRowHeader to some command that adds and removes indexes from a collection in the underlying data class, i.e. the DataContext of the parent DataGridRow, TabItem or TabControl.
Trying to iterate through the visual DataGridRow containers won't work unless you disable the UI virtualization. And this may of course lead to performance issues.
Comment: The elements are re-created or re-used from a previous container and the details are still visible because of some property being set to true or Visible. But this won't help you.
Comment: Have put most of what you talked about in, though I'm just using code-behind. My issue now is restoring that stored data.
Comment: One more question: So if a bunch of RowDetails are set to visible and then the user scrolls them off the VirtualizingPanel, which causes the rows to be destroyed. Where does the DataGrid keep this information, because they're still expanded when you scroll them back into view?


What is the area of intersection between two circular sectors? (Where can I find more information?)

Question: I am trying to find an expression for the area of the intersection of two circular sectors.
There are some obvious and trivial solutions for some special cases,  but I'm trying to generalize.
Here is an example of the kind of problem I'm envisioning:

I have tried to work out ways of dissecting the shapes and calculating areas with trigonometry or integration.
At the moment, I'm playing with polar coordinates and integrating, treating the centre of A as the origin, then generating expressions for each line of B's perimeter.
I've also been trying to find examples of where this might have been solved before. So far, though, I haven't found anything useful.

Are there any formulae that I should be looking at?
Does this kind of problem crop up anywhere else that I could research?
Even better, does anyone have a good starting point so I can derive it myself?
Comment: You should start by outlining each of the possible cases (one is [well-known](https://mathworld.wolfram.com/Circle-CircleIntersection.html))
Comment: This doesn't look too hard. The shape is a tetragon with some curved edges. Two of its vertices are intersection points which you haven't marked. Dissect the shape using its four vertices, and you can calculate its area in terms of triangles and [circular segments](https://en.wikipedia.org/wiki/Circular_segment).
Answer: This can be solved (in a somewhat fancy way) by using Green's Theorem. Green's Theorem converts the area calculation to a line integral around the oriented boundary of the region. That boundary consists of circular arcs and line segments, both of which are easy to parametrize. You will need to know all the vertices of the region in your picture.
See this related post. area between three annulli
Comment: For the larger problem I'm working on, this seems like a great path to follow, thank you!
I am sure I can find the vertices of the region and equations for each of the curves/lines. This was almost exactly how I had started to continue working the problem since posting, so I'm glad I seem to be on the right road!
Comment: Pun intended I assume?
Answer: In short, we want to calculate the double integral:
$$
||D|| \equiv \iint\limits_D 1\,\text{d}x\,\text{d}y\,,
$$
$$
D \equiv \left\{(x,y) \in \mathbb{R}^2 : x^2 + y^2 \le 1, \; |y|\cos\frac{\alpha}{2} \le x\sin\frac{\alpha}{2}, \; (x-x_C)^2 + (y-y_C)^2 \le r^2, \\ \left|(y-y_C)\cos\gamma-(x-x_C)\sin\gamma\right|\cos\frac{\beta}{2} \le \left((x-x_C)\cos\gamma+(y-y_C)\sin\gamma\right)\sin\frac{\beta}{2}\right\}
$$
with $x_C,y_C \in \mathbb{R}$, $r\ge0$ and $0 \le \alpha,\beta,\gamma \le 2\pi$ known parameters.
For example, assuming the following numerical values:
{xC, yC, r, α, β, γ} = {1, -1, 6/5, π/3, π/4, 4π/7};

domainA = x^2 + y^2 <= 1 && Abs[y] Cos[α/2] <= x Sin[α/2];

domainB = (x - xC)^2 + (y - yC)^2 <= r^2 && Abs[(y - yC) Cos[γ] - (x - xC)
          Sin[γ]] Cos[β/2] <= ((x - xC) Cos[γ] + (y - yC) Sin[γ]) Sin[β/2];

RegionPlot[{domainA, domainB}, {x, -2, 2}, {y, -2, 2},
           Axes -> True, AxesLabel -> {"x", "y"}, Frame -> False,
           GridLines -> Automatic, PlotPoints -> 100]

$\quad\quad\quad\quad\quad$
NIntegrate[1, {x, y} ∈ ImplicitRegion[domainA && domainB, {x, y}],
           WorkingPrecision -> 10]

0.308723

which can be obtained in an elementary way by applying the Monte Carlo method:
ParallelTable[m = 0; Do[{x, y} = RandomReal[{-2, 2}, 2];
              If[domainA && domainB, ++m], {10^n}];
              16. m/10^n, {n, 8}]

{0., 0.64, 0.416, 0.28, 0.29792, 0.308816, 0.306883, 0.308919}

As has already been written, for the exact calculation an efficient way is the application of the Gauss-Green theorem in the plane, but the difficult part is to decline the various cases and sub-cases involving the six parameters!


UILocalNotification Schedule Daily Until Date

Question: I already schedule a daily notification with this code:
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay:7];
[components setMonth:3];
[components setYear:2014];
[components setHour:9];
NSInteger minute = arc4random() % 59;
[components setMinute:minute];
[components setSecond:0];
[calendar setTimeZone:[NSTimeZone defaultTimeZone]];
NSDate *dateToFire = [calendar dateFromComponents:components];

UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.userInfo = @{@"uid": DailyNotificationUid};
localNotification.fireDate= dateToFire;
localNotification.timeZone = [NSTimeZone defaultTimeZone];

NSString *body = NSLocalizedString(@"Local Notification Alert Body", nil);
localNotification.alertBody = body;
localNotification.alertAction = NSLocalizedString(@"Local Notification Alert Action", nil);
localNotification.soundName = UILocalNotificationDefaultSoundName;
localNotification.applicationIconBadgeNumber = 1;
localNotification.repeatInterval = NSCalendarUnitDay;

[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];

But I miss a expire date. The notification should end on christmas without that the user has to start the app. Is this possible?
Comment: Possibly duplicate question you can cheek this post [http://stackoverflow.com/questions/6340664/delete-a-particular-local-notification][1]

  [1]: http://stackoverflow.com/questions/6340664/delete-a-particular-local-notification
Comment: how you do that ????
Answer: You can't specify expiry date in UILocalNotification. Instead you will need to create UILocalNotification till christmas. But there is also a limit of 64 UILocalNotification.


Twitter Bootstrap Glyphicons

Question: I believe I have the correct file path but I can still not get the glyphicons to appear. I have shared the link to the site and other info.
file path ../assets/img/glyphicons-halflings.png

assets contains css files & JS files
I changed file path in given bootstrap css file to match (add assets).

here is the mark up

        Email Me: email@example.com

        Call Me: 419.233.0955

     Call Me: 419.233.0955

Answer:
../assets/img/glyphicons-halflings.png *assets contains css files & JS files *

If the css file of bootstrap is in the assets folder, then you're directory traversing unnecessarily. Just remove ../assets/.
img/glyphicons-halflings.png

Answer: Changing the default folder hierarchy often results in such issues. The fonts & bootstrap folder should be at the same level folder.
See another similar question:
Bootstrap loading wrong glyphicon

Twitter Bootstrap Glyphicons


"Simple FB Connect" module return page not found when user path replace with another module called "Rename Admin Paths"

Question: Hi I am using "Rename Admin Paths" module for replace "user" path to "account" & working good. But today when I am trying to integrate "Simple FB Connect" module with my drupal 7 site, it return Page Not Found - when try to navigate domain.com/account/simple-fb-connect. But when i try domain.com/user/simple-fb-connect after disable rename_admin_paths module, its working, i can connect with facebook.
I am trying to replace all 'user/simple-fb-connect....' path to 'account/simple-fb-connect....' into simple_fb_connect modules files, but no luck!
Can anyone help me please... how can i configure simple_fb_connect with rename_admin_paths module.
Thanks.
Answer: after 2 days, i solved my problem by change 'user/simple-fb-connect' to 'connection/simple-fb-connect' and its now working.


Problems creating close me link in javascript bookmarklet

Question: I am trying to add a close me link to this function.  The way this works, is you paste all of this code without newline characters into a bookmark and the bookmark brings up a blue box on the screen.
Here is what I have so far, the close me link I have created is the "eleCloseLink" node I created:
javascript:(
  function(){

var pagebody = document.evaluate( '/html/body' ,document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue;
if (pagebody != null) {
  var node = document.createElement("DIV");
   node.style.position="fixed";
   node.style.color="white";
   node.style.background="blue";
   node.style.width="350px";
   node.style.top="50px";
   node.innerHTML = "
BLUE BOX
2
";

   var box = pagebody.appendChild(node);

   /* Creating close link here */
   var eleCloseLink = document.createElement("a");
   eleCloseLink.setAttribute('href', 'javascript:( function(){ node.parentNode.removeChild(node); })();');
   eleCloseLink.innerHTML = 'close me';
   box.appendChild(eleCloseLink);

}

})();

So far I have tried doing this about 10 differen't ways and none have succeeded.  The most recent way is putting javascript:( function(){ node.parentNode.removeChild(node); })(); inside of a  and that is not working either.  I feel like this should be one of the most common things to code as I see them on websites often and therefore there should be a lot of information on it.  My scenario may be a little more specific than most b/c the box I am creating is just a DIV element and I am essentially trying to delete the DIV element (i have tried using this as well) with my close me link.  Please let me know if anyone has any suggestions on how to create this close me link.
Comment: need to understand scopes better, you are creating a closure in your IIFE and `node` won't be available outside that closure. use `addEventListener` instead of inline code
Comment: Are you referring to something such as `eleCloseLink.setAttribute('onclick', 'RemoveThisNode(this)'); `  ?  What functions or method should I essentially be using to remove or delete elements?  I'm also having problems determine the best way to reference the node (a parent of the element itself) which I want to remove.
Answer: To resolve this, I created a click event listener which called a function that removes the object.  To accompany this, I added a id attribute to the DIV object I was trying to remove.  When the click event is triggered, the close function then evaluates the div object with XPATH referencing by id attribute.  I was then able to run a remove() method on that object.
End Snippet:
   /*Create Link in box to close box*/
   var eleCloseLink = document.createElement("a");

   eleCloseLink.innerHTML = '|CLOSE|';
   eleCloseLink.addEventListener("click", CloseBox, false);
   eleCloseLink.background = 'red';
   box.appendChild(eleCloseLink);
 }

 /*Function to close the box */
 function CloseBox() {
    document.evaluate( "//*[@id='thebox']" ,document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue.remove(this);
 }

Still not completely sure if I had to use "this" or not in the remove() method as I was calling the remove() method on the object itself.  However this is now working.


Why computed field is not getting displayed while creating content

Question: I using "computed field" Module. I have installed the 7.x-1.0-beta1 version computed field module. Enabled and save the configuration.
I have created a computed field and just displayed "Hello" in my content type "abc".
But this "computed field is not getting displayed while content creation.
Any ideas why this computed field is not getting displayed.
Answer: Try adding the following JavaScript to your theme or in a module (so it's added on the page you are working on with the fields):
It's pretty rudimentary, but it works!  You might want to expand it to work on keypresses rather than .change() events.
Drupal.behaviors.jqFill = {
    attach: function(){
      $('#edit-field-half-und-0-value, #edit-field-full-und-0-value').change(function(){
        half = parseInt($('#edit-field-half-und-0-value').val());
        full = parseInt(+$('#edit-field-full-und-0-value').val());
        total = half + full;

        if(!isNaN(total)){
          $('#edit-field-total-und-0-value').val(total);
        }
      });
    }
  }

Note I got the field names from your other question here.
Comment: Should I disable the computed field module?Do I need to add this code to hook_form_alter in a module?
Comment: I'd be inclined to leave computed field enabled, just in case the JS fails or someone has it disabled.  That way the right value will still be saved.  You can add the JS however you want, although adding it using `#attached` in `hook_form_alter()` is probably a good idea!
Comment: Do I need to add the code to hook_form_alter in a module?
Comment: " You can add the JS however you want, although adding it using #attached in hook_form_alter() is probably a good idea!"
Comment: used the following code:$form['#attached']['js'][] =
      $('#edit-field_half_baths-und-0-value, #edit-field_full_bat-und-0-value').change(function(){
        half = parseInt($('#edit-field_half_baths-und-0-value').val());
        full = parseInt(+$('#edit-field_full_bat-und-0-value').val());
        total = half + full;

        if(!isNaN(total)){
          $('#edit-field_baths_total-und-0-value').val(total);
        }
      });
     => array('type' => 'inline'); But its not working. Is this the correct way to add javascript. sorry I am not good in drupal.
Comment: Check out the [docs](http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#attached) - they should help!


ModX Revo: form action not working?

Question: I have a form on a ModX Revo resource that looks fine and is nothing special:
<form id="contactform" action="http://mysite.com/index.php?id=41" method="send">

Name*
<input size="24" type="text" name="name" id="name">

etc...

<input type="submit" value="Send">

</form>

But when I hit send I just get redirected to the home page (404). The receiving resource (resource 41) is published and can be accessed fine in other ways, just not with this form action.
Tried both Send and Get methods as well as short and absolute URLs, but no difference.
Would anyone know why this would be occurring? Thanks!
(ps: FURLs are turned off on this site if it matters).
UPDATE: Seems to not just be resource 41 thats an issue - doesnt work with any resource
Comment: Also what you can do is instead of: action="http://mysite.com/index.php?id=41", use: action="[[~[[41]]]]" assuming of course you are posting to a modx resource :)
Answer: Used method="post" instead. Seems to work ok. Closing question

ModX Revo: form action not working?


Não faz nada ao tentar abrir popup

Question: No HTML
Eu tenho este footer :

1

2

3

4

E criei esta popup :

A

B

C

D

E criei na página JavaScript esta função que deveria, quando se clica no tab 1 do footer abrir a popup:
$('#btnCl').click(function () {
        $("#popupMenu").popup("open");
    });

Problema:
Quando se carrega no tab 1 do footer nada acontece...
Answer: Popups jQuery Mobile
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />

Basic Popup

This is a completely basic popup, no options set.

Site do projeto: http://demos.jquerymobile.com/1.4.5/popup/
Não esqueça de linkar sempre os endereços do jQuery Mobile. Basta escolher seu modelo e adaptar as tags html, clique em View Source

Para popups
Use esta função javascript

No link a hrefutilize o onClick="MM_openBrWindow('http://google.com','popup1','scrollbars=yes,resizable=yes,width=500,height=500')"
Resultado
Neste exmplo a popup abre ao clicar no link 1
https://jsfiddle.net/tiagoboeing/nhmwfdpm/

Atributos possíveis
*Neste exemplo está como google.com para exibir
Popup 1: nome da sua janela, chamada javascript
Scrollbars: mostra barra de rolagem se necessário (yes, no)
Resizable: deixa redimensionar a janela (yes, no)
Width: largura da janela (em pixels)
Height: altura da janela (em pixels)
menubar: mostra barra de menus (yes, no)
toolbar: barra de ferramentas (yes, no)
status: barra de status (yes, no)
Comment: Eu não pretendo que a popup aberta seja uma janela nova. Eu estava a tentar fazer uma coisa deste genero http://prntscr.com/7php72
Comment: Você quer um lightbox com um conteúdo dentro, correto?
Comment: Confira um exemplo do `colorbox`: http://www.jacklmoore.com/colorbox/example1/ Clique sobre inline html
Comment: sim, algo do genero. Que quando clico, neste caso, no 1º tab, me abre essa janelita com os 4 botões
Comment: Eu estava a tentar basear-me nisto: http://demos.jquerymobile.com/1.4.5/popup/#&ui-state=dialog (no exemplo da **dialog**)

Não faz nada ao tentar abrir popup


Algorithmic or structural limitations of space-filling Latin hypercube sampling

Question: I'm new to Latin hypercube sampling, and am trying to understand if the somewhat odd sampling that results from the Matlab function lhsdesign is a limitation of the particular algorithm or something deeper within LHS, which I've failed to realize from the literature.  I suppose the fact that the results are SO bad is what makes me doubt that this is Matlab's mistake, though I'm almost certain it is.  A toy example:
n=3;                %dimensions
p=1e5;              %samples
s=lhsdesign(n,p);   %default algorithm maximizes min distance between samples
figure
plotmatrix(s.')
figure
scatter3(s(1,:),s(2,:),s(3,:),'.')
xlabel('1'),ylabel('2'),zlabel('3')

The following figures result (first figure is with 1e4 samples so that individual points are visible):

As is quite visible, there are p block-gaps along the main diagonal (testing with other p confirms this).  I understand that it's easy to make an LHS that isn't space-filling (e.g. the identity matrix), but Matlab's explanation of the algorithm,although brief, doesn't suggest this behavior should arise.
Answer: You (I) have specified n and p backward, thus the plots are for 3 samples of a 1E5 dimensional space, and the gaps correspond to LHS doing exactly what it's designed to do.  In short, I'm an idiot.


login destination redirect to previous page adding #

Question: The following code works for me to redirect the user back to the previous current page after he/she logs in.
 <?php
    print l(t('Please Log in'),'/user/login', array(
    'attributes' => array('title' => t('Log in page')),
    'query' => drupal_get_destination()));
    ?>

However, how can I add # to the previous current page?
For example, if the user was on /node/1 and go to the login page.
Then How can I redirect this user to /node/1#article_1 ?
(How can I add this #article_1? )
Answer: This can be done via
<?php
  print l(t('Please Log in'),'/user/login', array(
    'attributes' => array('title' => t('Log in page')),
    'query' => drupal_get_destination(),
    'fragment' => 'article_1'));
?>


how do i force to set charset while writing to a file setting charset 1256 in php

Question: how do i force to set charset while writing to a file setting charset 1256 in php
i have some data in sql which reads as ÇáÓáÇã Úáíßã æÑÍãå Çááå æÈÑßÇÊå and i am trying to convert it into correct (Arabic) format charset Windows-1256
my code is
$text = "ÇáÓáÇã Úáíßã æÑÍãå Çááå æÈÑßÇÊå";
$file = fopen("test.txt","w");
fwrite($file, $text);
fclose($file);

it saves the data same as it is although it display in correct format on browser
i want to save it into text or maybe CSV as
السلام عليكم ورحمه الله وبركاته يا اخوان هذا الفيروس
which is its correct format
Comment: try using mb_convert_string
Comment: possible duplicate of [How to write file in UTF-8 format?](http://stackoverflow.com/questions/4839402/how-to-write-file-in-utf-8-format)
Answer: Did you try iconv() ?
echo iconv('WINDOWS-1256', 'UTF-8', "ÇáÓáÇã Úáíßã æÑÍãå Çááå æÈÑßÇÊå");

Comment: it worked fine however if i put this file into sql table field it becomes more gabrish like السلام عليكم ورحمه الله can you help please
Comment: It might be related to encoding of your db. I will suggest to check encoding of file which you are importing into db and also make sure your encoding of dbare correct.
Answer: Use iconv() function.
Example:
fwrite( $file, iconv('UTF-8', 'Windows-1256', $text) );

From UTF-8 to Windows-1256
Comment: iconv(): Detected an illegal character in input string in //path
Comment: You need know, what charset in your file.
And correct iconv() first parameter 'UTF-8' on your charset.
Comment: i open up the gabrish into notepad++ and it only displays correct Araic when i chose Encoding -> Character set -> Arabic -> windows-1256 on all other options it do not displays well so i assume it is 1256
Comment: what charset set in the begining?
Comment: reordring UTF-8', 'Windows-1256' to vise helped as Tomasz Turkowski answerd thank you very much


Rain fall a full day in big matches

Question: What will happen if the rain stops play for the whole day in big matches such as finals played for World Cup or Asia cup or currently being played Champions Trophy.
Does the match will be played again if the rain does not stop? as the match which was supposed to be played was having a big value.
Also what will be action if the match stopped for whole day after the toss was won by a team ?
What will be considerations for such rain affected matches?
Answer: If rain fall a full day on final matches of a big tournament, then the teams will be declared joint winners. This is the rule on current ICC champions trophy.
But, in 2002 ICC Champions Trophy final between India and Srilanka, when the result was not able to find as the minmum number of overs required for DL method was not bowled, the match was rescheduled to the next day. But, the same story continues on next day, then both the teams were announced joint winners.
Source -wikipedia.

Rain fall a full day in big matches


Ideal, not finitely generated

Question: This exercise is driving me insane. I think there might be a mistake in it.

Consider the ring $R$ of matrices of the form:
$ R = \lbrace \begin{pmatrix}
  z & q_{1}  \\
  0 & q_{2}  \\
 \end{pmatrix} , z\in\mathbb{Z}, q_{1},q_{2}\in\mathbb{Q} \rbrace$
I have to find a left ideal of $R$ which is not finitely generated.

I write:
$R = R_{1} \times R_{2}$ where
$R_{1} = \lbrace \begin{pmatrix}
  z & q_{1}  \\
  0 & 0  \\
 \end{pmatrix} , z\in\mathbb{Z}, q_{1}\in\mathbb{Q} \rbrace$
$R_{2} = \lbrace \begin{pmatrix}
  0 & 0  \\
  0 & q_{2}  \\
 \end{pmatrix} , z\in\mathbb{Z}, q_{2}\in\mathbb{Q} \rbrace $
Every ideal of $R$ must have the form (since both $R_{1}, R_{2}$ contain an identity element):
$I\times J$ where $I$ is an ideal of $R_{1}$, $J$ is an ideal of $R_{2}$.
The ideals of $R_{1}$:
$ R_{1} = \lbrace \begin{pmatrix}
  z & q_{1}  \\
  0 & 0  \\
 \end{pmatrix} , z\in\mathbb{Z}, q_{1}\in\mathbb{Q} \rbrace$
$ \lbrace \begin{pmatrix}
  0 & q_{1}  \\
  0 & 0  \\
 \end{pmatrix} , q_{1}\in\mathbb{Q} \rbrace$
$0 = \lbrace \begin{pmatrix}
  0 & 0  \\
  0 & 0  \\
 \end{pmatrix} \rbrace$
Let $n\in\mathbb{Z}$:
$\lbrace \begin{pmatrix}
  n\cdot z & q_{1}\\
  0 & 0  \\
 \end{pmatrix} ,  q_{1}\in\mathbb{Q}, z\in\mathbb{Z} \rbrace$
The ideals of $R_{2}$
$R_{2} = \lbrace \begin{pmatrix}
  0 & 0  \\
  0 & q_{2} \\
 \end{pmatrix} ,  q_{2}\in\mathbb{Q} \rbrace$
$0 = \lbrace \begin{pmatrix}
  0 & 0  \\
  0 & 0  \\
 \end{pmatrix}   \rbrace$
When I check the possible constructions I obtain that they are all finitely generated. Is there a mistake in this exercise (maybe a right ideal of $R$ instead of left??) or where is the mistake?
Comment: Dear postguest12, The decomposition $R = R_1 \times R_2$ is not a ring direct product, since typically, if $r_1 \in R_1$ and $r_2 \in R_2$, it is not true that $r_1 r_2 = 0$.   (Conider $\begin{pmatrix} 0 & 1 \\ 0 & 0 \end{pmatrix} \begin{pmatrix} 0 & 0 \\ 0 & 1 \end{pmatrix}$.)  I don't think this was the source of your problem, since you actually found the correct ideal in your list but didn't recognize it for some reason.   Still, it seems worth noting.  Regards,
Answer: The left ideal $I=\{\begin{pmatrix} 0 & q_{1} \\ 0 & 0\end{pmatrix} | q_1 \in \mathbb{Q} \}$ is not finitely generated. This follows by the fact that $\mathbb{Q}$ is not a finitely generated $\mathbb{Z}$-module. (What happens when you multiply elements of $I$ by elements in $R$?)

Ideal, not finitely generated


Setting up PPTP VPN server, cannot access remote hosts

Question: I'm attempting to set up a VPN server on an industrial ProRoute M2M 4G router. My goal is for a client to be able to log in on the VPN and be able to "locally" hosts that are on the router's LAN. My first challenge comes from the obscure PPTP server settings on the router configuration pages. I have tried every possible combination I can think of. However, the one's included below are what were used to generate the following outputs.
My local machine is 192.168.1.64 and my local gateway 192.168.1.254. The remote router has gateway 192.168.8.1 and DHCP assigns LAN addresses 192.168.8.100-192.168.8.200. I am running Windows 7, but have also experimented with this using OS X. The router is using a fixed public IP sim card.
Router Settings
Local IP - 192.168.8.100-192.168.8.200
Remote IP - 192.168.1.100-192.168.1.200
Encryption - MPPE 128 bit (tested everything without encryption too)
Username and Password - Set
User Static IP - Left blank
Remote LAN/Mask - 192.168.8.0/24
Please note that I have no option of enabling DHCP for the PPTP server anywhere.
Local Client Settings
IPv6 - Disabled
IPv4 - All automatic, although tested with static with identical results, DNS manually pointed to 220.127.116.11/18.104.22.168 (Google Public DNS) and default gateway box is checked
ipconfig output without VPN connection:
Windows IP Configuration

Ethernet adapter Local Area Connection:

   Connection-specific DNS Suffix  . : gateway.2wire.net
   Link-local IPv6 Address . . . . . : fe80::a985:527b:f5e3:a66b%11
   IPv4 Address. . . . . . . . . . . : 192.168.1.64
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 192.168.1.254

Tunnel adapter isatap.gateway.2wire.net:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . : gateway.2wire.net

Tunnel adapter Local Area Connection* 11:

   Connection-specific DNS Suffix  . :
   IPv6 Address. . . . . . . . . . . : 2001:0:5ef5:79fd:34ff:3fd9:3f57:febf
   Link-local IPv6 Address . . . . . : fe80::34ff:3fd9:3f57:febf%13
   Default Gateway . . . . . . . . . : ::

route print without VPN connection:
===========================================================================
Interface List
 11...44 8a 5b 61 bd d3 ......Realtek PCIe GBE Family Controller
 1...........................Software Loopback Interface 1
 12...00 00 00 00 00 00 00 e0 Microsoft ISATAP Adapter
 13...00 00 00 00 00 00 00 e0 Teredo Tunneling Pseudo-Interface
===========================================================================

IPv4 Route Table
===========================================================================
Active Routes:
Network Destination        Netmask          Gateway       Interface  Metric
          0.0.0.0          0.0.0.0    192.168.1.254     192.168.1.64     10
        127.0.0.0        255.0.0.0         On-link         127.0.0.1    306
        127.0.0.1  255.255.255.255         On-link         127.0.0.1    306
  127.255.255.255  255.255.255.255         On-link         127.0.0.1    306
      192.168.1.0    255.255.255.0         On-link      192.168.1.64    266
     192.168.1.64  255.255.255.255         On-link      192.168.1.64    266
    192.168.1.255  255.255.255.255         On-link      192.168.1.64    266
        22.214.171.124        240.0.0.0         On-link         127.0.0.1    306
        22.214.171.124        240.0.0.0         On-link      192.168.1.64    259
  255.255.255.255  255.255.255.255         On-link         127.0.0.1    306
  255.255.255.255  255.255.255.255         On-link      192.168.1.64    266
===========================================================================
Persistent Routes:
  None

IPv6 Route Table
===========================================================================
Active Routes:
 If Metric Network Destination      Gateway
 13     58 ::/0                     On-link
  1    306 ::1/128                  On-link
 13     58 2001::/32                On-link
 13    306 2001:0:5ef5:79fd:34ff:3fd9:3f57:febf/128
                                    On-link
 11    266 fe80::/64                On-link
 13    306 fe80::/64                On-link
 13    306 fe80::34ff:3fd9:3f57:febf/128
                                    On-link
 11    266 fe80::a985:527b:f5e3:a66b/128
                                    On-link
  1    306 ff00::/8                 On-link
 13    306 ff00::/8                 On-link
 11    266 ff00::/8                 On-link
===========================================================================
Persistent Routes:
  None

ipconfig with VPN connection:
Windows IP Configuration

PPP adapter VPN Connection:

   Connection-specific DNS Suffix  . :
   IPv4 Address. . . . . . . . . . . : 192.168.1.100
   Subnet Mask . . . . . . . . . . . : 255.255.255.255
   Default Gateway . . . . . . . . . : 0.0.0.0

Ethernet adapter Local Area Connection:

   Connection-specific DNS Suffix  . : gateway.2wire.net
   Link-local IPv6 Address . . . . . : fe80::a985:527b:f5e3:a66b%11
   IPv4 Address. . . . . . . . . . . : 192.168.1.64
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 192.168.1.254

Tunnel adapter isatap.gateway.2wire.net:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . : gateway.2wire.net

Tunnel adapter Local Area Connection* 11:

   Connection-specific DNS Suffix  . :
   IPv6 Address. . . . . . . . . . . : 2001:0:9d38:6abd:102f:dd7:3f57:fe9b
   Link-local IPv6 Address . . . . . : fe80::102f:dd7:3f57:fe9b%13
   Default Gateway . . . . . . . . . : ::

Tunnel adapter isatap.{C4127ACE-546B-4448-B79A-D0807C092C0B}:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :

route print with VPN connection:
===========================================================================
Interface List
 20...........................VPN Connection
 11...44 8a 5b 61 bd d3 ......Realtek PCIe GBE Family Controller
  1...........................Software Loopback Interface 1
 12...00 00 00 00 00 00 00 e0 Microsoft ISATAP Adapter
 13...00 00 00 00 00 00 00 e0 Teredo Tunneling Pseudo-Interface
 14...00 00 00 00 00 00 00 e0 Microsoft ISATAP Adapter #2
===========================================================================

IPv4 Route Table
===========================================================================
Active Routes:
Network Destination        Netmask          Gateway       Interface  Metric
          0.0.0.0          0.0.0.0    192.168.1.254     192.168.1.64   4235
          0.0.0.0          0.0.0.0         On-link     192.168.1.100     11
     18.104.22.168  255.255.255.255    192.168.1.254     192.168.1.64   4236
        127.0.0.0        255.0.0.0         On-link         127.0.0.1   4531
        127.0.0.1  255.255.255.255         On-link         127.0.0.1   4531
  127.255.255.255  255.255.255.255         On-link         127.0.0.1   4531
      192.168.1.0    255.255.255.0         On-link      192.168.1.64   4491
     192.168.1.64  255.255.255.255         On-link      192.168.1.64   4491
    192.168.1.100  255.255.255.255         On-link     192.168.1.100    266
    192.168.1.255  255.255.255.255         On-link      192.168.1.64   4491
        188.8.131.52        240.0.0.0         On-link         127.0.0.1   4531
        184.108.40.206        240.0.0.0         On-link      192.168.1.64   4485
        188.8.131.52        240.0.0.0         On-link     192.168.1.100     11
  255.255.255.255  255.255.255.255         On-link         127.0.0.1   4531
  255.255.255.255  255.255.255.255         On-link      192.168.1.64   4491
  255.255.255.255  255.255.255.255         On-link     192.168.1.100    266
===========================================================================
Persistent Routes:
  None

IPv6 Route Table
===========================================================================
Active Routes:
 If Metric Network Destination      Gateway
 13     58 ::/0                     On-link
  1    306 ::1/128                  On-link
 13     58 2001::/32                On-link
 13    306 2001:0:9d38:6abd:102f:dd7:3f57:fe9b/128
                                    On-link
 11    266 fe80::/64                On-link
 13    306 fe80::/64                On-link
 13    306 fe80::102f:dd7:3f57:fe9b/128
                                    On-link
 11    266 fe80::a985:527b:f5e3:a66b/128
                                    On-link
  1    306 ff00::/8                 On-link
 13    306 ff00::/8                 On-link
 11    266 ff00::/8                 On-link
===========================================================================
Persistent Routes:
  None

tracert 192.168.8.1 (remote router gateway) with VPN connection:
Tracing route to 192.168.8.1 over a maximum of 30 hops

  1     *        *        *     Request timed out.
  2     *        *        *     Request timed out.
  3     *        *        *     Request timed out.
  4     *        *        *     Request timed out.
  5     *        *        *     Request timed out.

I can get a VPN connection successfully. I can access the internet through the router if using IP addresses (DNS doesn't seem to work). However, I cannot access any internal hosts on the remote router LAN.
Answer: Solved! The issue was incorrect remote/local IP ranges. Make sure that remote IP and remote subnet are the IP ranges of your client's network and local is that of the router network.


Trying to understand log-likelihood estimation for exponential smoothing models in R forecast function ets()

Question: I am doing work on AIC comparisons. For this purpose, I am trying to understand how log-likelihood is calculated for exponential smoothing models (ETS models) in different R packages.
In particular, ets in R forecast and es in R smooth appear to give very different log-likelihood values for the same model fitted to the same data set, as follows.
# data simulation y as ETS(A,N,N)
set.seed(546)
n = 300
y <- smooth::sim.es("ANN", obs = n)

# fit E(A,N,N) and ARIMA(0,1,1) models to simulated data with R packages smooth and forecast
es_smooth_model <- smooth::es(y$data, model = "ANN", initial ="optimal")
es_forecast_model <- forecast::ets(y$data, model = "ANN", lambda = NULL)

Not surprisingly, both models give near identical fitted values, residuals, forecasts, coefficients, error variances, etc.
However, their log-likelihood estimates give very different values
# comparing loglikelihoods
es_smooth_model$logLik    # -1215.57
es_forecast_model$loglik  # -1645.456

Manual calculation for both models (assuming Gaussian error distributions) gives:
#manual loglikelihoods:

# es_smooth_model :         -1215.578
- 0.5 * (n * (log(2) + log(pi) + log(es_smooth_model$s2)) +
  1/ es_smooth_model$s2 * sum(es_smooth_model$residuals^2))

# es_smooth_model :         -1215.574
- 0.5 * (n * (log(2) + log(pi) + log(es_forecast_model$sigma2)) +
           1/ es_forecast_model$sigma2 * sum(es_forecast_model$residuals^2))

Can somebody help me to understand why forecast::ets gives a different log-likelihood value? And which of the two log-likelihoods is the correct value?
Answer: For this model, the log likelihood is given by
$$-\frac{n}{2}\log(2\pi\sigma^2) - \frac12 \sum_{t=1}^n e_t^2 / \sigma^2.$$
Taking the partial derivative with respect to $\sigma^2$ and setting it to zero gives the MLE of $\sigma^2$ to be
$$\hat{\sigma}^2 = \frac1n\sum_{t=1}^n e_t^2$$
Substituting $\hat\sigma^2$ for $\sigma^2$ in the log likelihood gives the concentrated log likelihood:
$$-\frac{n}{2}\log\left(\frac{2\pi e}n\right) -\frac{n}{2} \log\left( \sum_{t=1}^n e_t^2\right) = c_n -\frac{n}{2} \log\left( \sum_{t=1}^n e_t^2\right),
$$
where $c_n = -\frac{n}{2}\log(2\pi e/n)$, which does not depend on the data. The forecast package drops $c_n$ as it makes no difference to the parameter estimates, or the calculation of the AIC, and saves a small amount of computation.
Reference: Hyndman et al (2008, p69).


Who decides how a historic piece is adjusted (if at all) for modern instruments?

Question: Here we have a video of a historically-informed (or period) performance of Moonlight Sonata's first movement.
Wikipedia notes:

Some critics contest the methodology of the HIP movement, contending that its selection of practices and aesthetics are a product of the 20th century and that it is ultimately impossible to know what performances of an earlier time sounded like. Obviously, the older the style and repertoire, the greater the cultural distance and the increased possibility of misunderstanding the evidence. For this reason, the term "historically informed" is now preferred to "authentic", as it acknowledges the limitations of academic understanding, rather than implying absolute accuracy in recreating historical performance style, or worse, a moralising tone.

The impossibility of knowing what a historical performance sounds like seems to me to pose problems to normal (or inauthentic) performances too.
As I understand it, the third movement of the Moonlight Sonata is played rather differently on a modern piano due to how the notes sustain for longer.  Presumably there are many other pieces where the same thing applies.
Who decides how such a historic piece is adjusted for modern instruments? Or do players learn to adjust themselves?
On a larger scale (i.e. an Orchestra) and with enough ambiguity, it seems that decisions might be made which drastically change a piece.  Or that modern assumptions about a composer/period would overly-inform how a piece is played.
Comment: The video shows the first movement of the Moonlight Sonata.  How is the third movement played differently on modern pianos as compared to contemporaneous instruments?
Comment: @phoog Yeah I know, I only found that part. Take with a massive pinch of salt, but I remember that due the speed of notes in the third movement, some bits need to played with a damper pedal on a modern piano.
Answer: A combination of people.
First, unless you're playing from a facsimile of a period edition of the music, the person who prepared the modern edition of the music will have made some decisions in their translation of the notation to modern conventions, maybe filling in some missing information not customarily included at the time but helpful to modern performers, maybe making further additions aimed at helping people not trained in the style of the composer. And some editions are just plain wrong when looked at in the light of scholarship which has been conducted since their publication.
Second, if you're playing in a group then the group will make decisions. Maybe there's a person who does all that and just tells everyone else how to do it, maybe it's more of a group effort, but it will happen. Most older music is very sparse on things like performance directions, dynamics, ornamentation and decisions need to be made especially when playing with others as some choices individual players could make would conflict with each other despite both being valid.
Third, the actual performer, through their own training and abilities and also their choice of instrument upon which to perform the piece, as the instrument is highly unlikely to be the same as the kinds it was written for. Even HIP performers using "period" instruments aren't necessarily using exact duplicates or have their instruments configured in the same way. And again there's so much we don't know about authentic performance that we're making judgment calls all the time.
And of course all the influences on each performer from their teachers and colleagues and collaborators over their entire career.
So the answer to your question is "a lot of people". We may have studied early music, but we know we're making decisions about how to follow what we've learned. And more research is being done all the time, even as musical tastes change at the same time.
Answer: I had to carefully re-read your question to make sure you didn't really mean "who decides what is a historically informed performance?"
But the opposite of that - "who decides how to play for a modern performance?" - I think it is simply the editor of whatever modern edition being used.
For example, I have two editions of Bach's Two-Part Inventions, one by Mason the other by Palmer. They aren't exactly the same and there are differences that would clearly suggest different performances. Many of the editorial marking do not appear in autograph copies of the scores.
Tempo markings differ and Palmer gives metronome markings. Slurs are different. Expression marks like crescendo, forte, etc. differ and in some places the two editors contradict each other. Palmer gives about 15 pages of introductory text discussion issue about the inventions with historical context so I consider it more authoritative. Mason's was published in 1894 and Palmer's in 1991 so Palmer had the benefit of about 100 years of additional scholarship to rely on.
Answer: Historically informed is a very broad range of topics, depending on what the original period was. Note, that Beethovens era pianoforte was quite close to modern piano - at least if compared to a harpsichord. (Sometimes two manuals of the latter compensate for the loss of dynamic expression.) In Baroque harpsichord music, trills or other ornaments were required as substitute for any longer sounding tone, but they are seldom dropped for modern grand pianos, since the change may be more drastic than what the auditory expects.
In other instrument families the progress has less striking (e. g. gut strings and bows before Tourte) and the implications are far less clear.
As Michael points out, one decision is made by the editor of the chosen edition, but:

metronome markings, which are not authorized by the composer will typically be ignored (and are not much more than suggestions). Superfrequent dynamic indications strongly signal presence of such noise.
for professional soloists I can hardly imagine anything else but an urtext edition being used: while editor markings are eliminated by that, this is desired, since different decades had widely different ideas of useful editor additions. Less advanced artists may still use a carefully augmented edition, at least at the beginning for getting ideas. (This is similar to "training wheels" editions, where experts like well-known soloist added fingerings, bow marks, slurs or even whole cadenzas.)

This leaves the performer (in case of bigger ensembles the conductor, because all have to contribute to the same interpretation), who has to provide ideas of her own (education, training, practice), but this has to be done anyway, no matter how strict the score.
Answer:
Who decides how such a historic piece is adjusted for modern instruments?

The performers.

Or do players learn to adjust themselves?

Of course.  That's precisely what learning to play an instrument is all about, whether the piece was written in 1621, 2021, or any other year.  No two performers play the same piece identically, and indeed the same performer doesn't necessarily play the same piece identically every time.
Part of learning to play the modern piano or violin or what have you is learning how to make music with the instrument rather than just playing the notes on the page.  Phrasing, articulation, and expression are different on modern instruments as opposed to older ones, but if you consider a single instrument they also differ from one style of music to the next.  Beethoven sounds different on a piano built in 1790, 1830, or today, but on a modern piano one plays Beethoven differently from Bach and differently from Brahms and differently from Stravinsky.  Learning to play any instrument means learning to play all different parts of its standard repertoire effectively, and with the piano the standard repertoire reaches back to the 18th century, with occasional appearances by pieces from as early as the 16th.

On a larger scale (i.e. an Orchestra) and with enough ambiguity, it seems that decisions might be made which drastically change a piece. Or that modern assumptions about a composer/period would overly-inform how a piece is played.

Overly?  What's "too much" here?  Our modern assumptions are what they are.  Perhaps they will change over time as we learn new things (or forget old things) about the past.
But our audiences are modern, too.  All we can do is read what people wrote about performance practice at the time, see what we can learn from it, and produce the best performance we can.  One person's idea of "best" will differ from another's.  I saw a recording a few months ago of a master class given by the pianist Murray Perahia on a Bach piece.  He mentioned that the music had been written for a different instrument and spoke of the things a pianist must do to deal with that.  Different pianists approach the issue differently.  But, as with all performances, the choices shaping the performance are the performer's.
In a comment, you ask:

It's interesting you put way more emphasis on players than other answers. I presume the average classical musician could play from any edition in your opinion?

I emphasize the performers (not always "players") because it is the performers who make the choices that the audience hears.  One such choice is to decide which edition to use if multiple editions are available.  That is, the editor's decisions are little more than advice to the performer.  Even after choosing an edition, the performer can (should!) choose which of the editor's marks to observe and which to disregard.  That is why a good edition makes it clear which aspects of the edition are in the source and which are due to the editor, as well as the reasons behind editor's choices.
It may not even be possible to notate subtle choices such as the one mentioned in the question, articulation of the third movement of the "Moonlight" Sonata.  For example, there are infinite degrees of variability in the articulation of a simple scale.  One infinitely variable parameter is the relative time between the damper of one note falling on the string and the hammer of the next note hitting its string (or perhaps these things happen in the opposite order).  There is also the velocity of the hammer (and of the damper) to consider, and probably others besides.
These subtle distinctions can't be captured fully with articulation marks such as the staccato dot, a legato slur, and so on; there is only a finite set of permutations of this finite set of symbols.  That infinite variability is the province of the performer alone; notation (and even instructions from a conductor, teacher, or coach) can only be a guideline.
Comment: @ModalNest I've edited the answer to address your question.  I question "overly" because I inferred a question about whether a given performance might be sufficiently or insufficiently "authentic," though I don't suppose that's your primary concern.
Comment: Overly is maybe a bad word, as it is subjective I suppose.  It's difficult on this particular SE to try to keep questions objective sometimes.  I suppose I was thinking it would be something very noticeable to me which is a poor way to put it.  I'm not sure how to quantify it so it's probably moot.  It's interesting you put way more emphasis on players than other answers.  I presume the average classical musician could play from any edition in your opinion?


SVM-Light displays corrupted precision/recall results

Question: I run SVM-Light classifier but the recall/precision row it outputs seem to be corrupted:
<code>Reading model...OK. (20 support vectors read)
Classifying test examples..100..200..done
Runtime (without IO) in cpu-seconds: 0.00
Accuracy on test set: 95.50% (191 correct, 9 incorrect, 200 total)
Precision/recall on test set: 0.00%/0.00%
</code>
What should I configure to get valid precision and recall?
Comment: How are you running the model?
Comment: Can you provide a reproducible example (a little piece of code with a little piece of example data)?
Answer: The fact that your model's accuracy is high (95.5%) but its precision/recall are 0 shows your learning problem is highly unbalanced. Your data set likely contains most negative class, ~ 95.5%. As a result your model will classify every examples as negative class and achieve 95.5% accuracy but since there is no examples classified as positive class, model's precision/recall are 0.
To avoid that, you need to balance positive/negative class ratio in the training set by sub-sampling negative class or put a high weight on positive class examples.