csc compiler for C# code

Question: I am using Visual studio 2015. I think it uses the cl.exe compiler which is inside the Microsoft Visual Studio 14.0\VC\bin folder to compile C++ code. Also, my understanding is that the compiler used to compile C# code is csc.exe. However, I could not find this csc.exe inside my visual studio like cl.exe. I am curious to know how visual studio compiles C# code then. I think Visual Studio uses the csc.exe which comes with .Net, generally installed in C:\Windows\Microsoft.NET\Framework\\csc.exe to compile C# code. Is my understanding correct ?
Comment: I have just [answer another question](https://stackoverflow.com/a/50939232/815938) on this topic. Please check. Visual Studio 2015 uses the default Roslyn compiler, not the one shipped with .NET Framework.
Comment: Thanks, I went through the link. Inmycase, my visual studio 2015 does-not have Roslyn\csc.exe. Basically it does-not have csc.exe installed. So in this case, can we assume it is taking csc.exe from my .Net installation?
Comment: Did you install VS2015 or did someone else install it?  Was the option to install C# unticked?
Answer: I cannot answer why Roslyn is not present in your VS 2015 install dir. But you can examine how Visual Studio runs the csc.exe in the output window.
Go to Tools->Options->Projects and Solutions->Build and Run, and select the build output verbosity. (you can select the most verbose option)

Then build your program. You can then check the command line used by MSBuild in the output window.
Something like, ooh, I am using VS 2017...

C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin\Roslyn\csc.exe /noconfig /nowarn:1701,1702,2008 /nostdlib+ /platform:anycpu32bitpreferred ... (a bunch of switches omitted)
Comment: Thanks got it, I see in mycase it is taking csc.exe from the following path -- C:\Program Files (x86)\MSBuild\14.0\bin\csc.exe

csc compiler for C# code


Split semantic version number using zsh

Question: With the release of macOS 10.15 Catalina, the default shell will be switched from bash to zsh. While reviewing some scripts and documentation, I realized that parameter expansion changes would need to be made.
Following the question bash regex to match semantic version number, I needed to update my method of collecting semantic version numbers.
In zsh, how can I split semantic version numbers using parameter expansion?
Answer: While using my previous answer as a template, I was able to convert my code to use zsh parameter expansion.
product_version=$(sw_vers -productVersion) # 10.14.6
os_vers=( ${(@s:.:)product_version} ) # ( 10 14 6 )
os_vers_major="${os_vers[1]}" # 10
os_vers_minor="${os_vers[2]}" # 14
os_vers_patch="${os_vers[3]}" # 6
os_vers_build=$(sw_vers -buildVersion) #18G87
echo "${os_vers_major}.${os_vers_minor}.${os_vers_patch}+${os_vers_build}" # 10.14.6+18G87

Note that (by default) zsh arrays start at index 1 not 0

Split semantic version number using zsh


Limiting number of multiples in a drupal webform in an ajax callback

Question: I have a form with a select element to choose the number of guests you want to add to an event.  This select has an ajax callback that updates a container that holds a contact composite element.
I am trying to in my ajax callback update the number of multiple contact elements to the value of the number of guests select box.  Anyone have any thoughts?  If I use a form alter like below on initial load the number of elements updates correctly.
My alter attempting to just set multiple number outside ajax
function lebow_events_webform_submission_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  $form['elements']['guest_info']['guest_contact']['#type'] = 'webform_multiple';
  $form['elements']['guest_info']['guest_contact']['#webform_multiple'] = TRUE;
  $form['elements']['guest_info']['guest_contact']['#multiple'] = 10;
  $form['elements']['guest_info']['guest_contact']['#cardinality'] = 10;
  $form['elements']['guest_info']['guest_contact']['#sorting'] = FALSE;
}

My webform source
registration_type:
  '#type': select
  '#title': 'Registration Type'
  '#options': registration_types
guests_container:
  '#type': container
  '#states':
    invisible:
      ':input[name="registration_type"]':
        value: ''
  number_of_guests:
    '#type': select
    '#title': 'Number of guests'
    '#options':
      - '0'
guest_info:
  '#type': container
  '#title': 'Guest Info'
  guest_contact:
    '#type': contact
    '#title': 'Contact Info'
    '#multiple': 2
    '#multiple__add_more': '2'
    '#company__access': false
    '#phone__access': false
    '#address__access': false
    '#address_2__access': false
    '#city__access': false
    '#state_province__access': false
    '#postal_code__access': false
    '#country__access': false

My alter to add ajax callback (and try setting number of multiples)
function lebow_events_webform_submission_form_alter(array &$form, FormStateInterface $form_state, $form_id) {

  $form['elements']['guests_container']['number_of_guests']['#options'] = ['' => '- None -'];
  $form['elements']['registration_type']['#ajax'] =
    array(
      'callback' => 'lebow_events_registration_change',
      'wrapper' => 'edit-guests-container',
    );
  $form['elements']['guests_container']['number_of_guests']['#ajax'] =
    array(
      'callback' => 'lebow_events_guests_change',
      'wrapper' => 'edit-guest-info',
    );

  $form['elements']['guests_container']['number_of_guests']['#validated'] = TRUE;
  $form['elements']['guest_info']['guest_contact']['#type'] = 'webform_multiple';
  $form['elements']['guest_info']['guest_contact']['#webform_multiple'] = TRUE;
  $form['elements']['guest_info']['guest_contact']['#multiple'] = 10;
  $form['elements']['guest_info']['guest_contact']['#cardinality'] = 10;
  $form['elements']['guest_info']['guest_contact']['#sorting'] = FALSE;
}

My ajax callback
function lebow_events_guests_change(&$form, \Drupal\Core\Form\FormState $form_state) {

  $form['elements']['guest_info']['guest_contact']['#type'] = 'webform_multiple';
  $form['elements']['guest_info']['guest_contact']['#webform_multiple'] = TRUE;
  $form['elements']['guest_info']['guest_contact']['#multiple'] = $form_state->getValue('number_of_guests');
  $form['elements']['guest_info']['guest_contact']['#cardinality'] = $form_state->getValue('number_of_guests');
  $form['elements']['guest_info']['guest_contact']['#sorting'] = FALSE;
  $form['elements']['guest_info']['guest_contact']['#element']['#webform_multiple'] = TRUE;
  $form['elements']['guest_info']['guest_contact']['#element']['#multiple'] = $form_state->getValue('number_of_guests');

  $message = $form['elements']['guest_info'];

  $response = new \Drupal\Core\Ajax\AjaxResponse();
  $response->addCommand(new \Drupal\Core\Ajax\HtmlCommand('[data-drupal-selector=edit-guest-info]', $message));

  return $response;

}

Answer: It is very difficult and sometimes impossible to alter a form via an Ajax callback.  Generally, an Ajax callback just returns the updated form element from the $form render array.
The Examples for Developers module includes several Ajax form examples that you can use as a starting point.
Comment: Ah actually I figured it out.  I updated my hook_webform_submission_form_alter to use the value of number_of_guests and works and submits perfectly.

Thank you for all your hard work on this module!


How to prove that $GF(p^n)$ contains an element of degree n?

Question: I am reading Gallian's Algebra book, and I am lapsing on Corollary 2 to Theorem 22.2. The statement goes: "Let $a$ be a generator of the group of nonzero elements of $GF(p^n)$ under multiplication. Then $a$ is algebraic over $GF(p)$ of degree $n$."
I totally understand the proof in which it says $[GF(p)(a):GF(p)]=[GF(p^n):GF(p)]=n$. But why can we use this argument to show that $a$ is algebraic over $GF(p)$? I only know that we can deduce $[F(a):F]=n$ if $a$ is algebraic over $F$ with minimal polynomial of order $n$, but not the other way around...
Comment: You probably have also covered the part that if $[F(a):F)]$ is infinite if and only if $a$ is transcendental. So here $a$ is necessarily algebraic of **some** degree. And that result then tells you that the degree has to be equal to $n$.
Answer: Every element of $GF(p^n)$ is algebraic over $GF(p)$.  Indeed, if $x\in GF(p^n)$ is nonzero, then $x^m=1$ for some $m$, and so $x$ is a root of the polynomial $x^m-1$.  (I'll leave the case that $x=0$ to you.)
Comment: Is the case trivially true?
Answer: Any finite field extension is necessarily algebraic, so $a$ as the generator of this extension is certainly algebraic.


Concatenate items in a python list if '\\' is at the end of item

Question: I need to merge with next item in a list if previous item has '\' at the end. Example:
original_list = ['first.key=First value', 'second.key=Second value, first line\\',
'Second value, second line\\', 'Second value, third line\\', 'Second value, fourth
line', 'third.key=Third value']

Expected result is:
desired_list = ['first.key=First value', 'second.key=Second value,first line\\ Second
value, second line\\ Second value, third line\\ Second value, fourth line',
'third.key=Third value']

Do not assume that the first item ending with '\' is the second item in the list. I dont know which will it be.
Answer: It is a crude solution, but should be working:
desired_list = original_list[:1]
for x in original_list[1:]:
    if desired_list[-1].endswith('\\'):
        desired_list[-1] += x
    else:
        desired_list.append(x)
print(desired_list)

If you work with huge lists, it may be worth to think of some optimization.
Comment: Thank you. This is working for the example list above. But if we do not assume that the first item ending with '\\' is the second item in the list and we actually dont know which will it be, how would this look like?
I will include this condition to avoid misleading anyone else.
Comment: It should work anyway - it just checks lastly updated element of desired_list, iteratively going through all elements in original list.
Comment: I like the way you initialize with `desired_list = original_list[:1]` instead of `original_list[0]`, it means it will work even with empty input.
Comment: @Maciej Wrobel, Thank you! Really. It does work. Have a nice evening.


Avoid Int to double typecast rounding?

Question: I am converting an int to a double by dividing the integers by powers of 10. For integers with 7 or greater digits, it appears that rounding is performed when I cast an int into a double. Why is this happening and how can I avoid this rounding?
#include <iostream>
using namespace std;

double add_decimals(int x, int decimal_places)
{
    double ret = 1.0 * x;
    cout << "x= " << x << endl;
    cout << "ret before changes= " << ret << endl;
    for (int i = 0; i < decimal_places; ++i)
    {
        ret /= 10;
    }
    return ret;
}

int main()
{
    double d = add_decimals(1234566, 2);
    cout << "d= " << d << endl;
}

Answer: There isn't any; you're just not observing the values correctly.
Quick fix:
std::cout << "d= " << std::fixed << d << endl;

You'll need #include <iomanip> to use std::fixed.

Avoid Int to double typecast rounding?


Dropping an item on a sortable list that only has excluded items

Question: I have several sortable lists connected together, so I can drag one item from one list and put it in another. Every list also has one item at its bottom that is neither sortable nor a drop target, making it impossible to drop any items below it.
That's the intended use, I want the excluded item at the bottom of each list to always stay at the bottom.
Problem is if I empty a list, say I drag out all of its items and place them in another list, so that all that is left is the non-sortable item. If I then drag a new item into it it will always go to the bottom, below my non-sortable, not-a-drop-target item.
Is it possible, when dropping an new item into a sortable list that only has one non-sortable, not-a-drop-target, item, to have it be placed at the top of the list?
Example code:
$('.segment ol').sortable({
  connectWith: '.segment ol',
  distance: 25,
  items: 'li:not(.disabled)'
});

HTML:

word word word

word word word

must stay at bottom

must stay at bottom

If you were to drag a "word word word" li to the other list it would get appended below the disabled li.
Comment: Please post some sample html, and the jquery code you have tried
Comment: Done. Thing is it's not a bug, it's just the default way that sortable lists work, I'd like to know if there's a workaround.
Answer: You can use the "receive" event on the sortable list (when you supply options), and do something like this:
$('.segment ol').sortable({
    connectWith: '.segment ol',
    distance: 25,
    items: 'li:not(.disabled)',
    over: function(event,ui){ ui.placeholder.insertBefore($(this).children('li.disabled:first')); }
});

That will make the currently dragged element prepend itself onto the list (prepend and prependTo will effectively move an item unless you clone it first).
Comment: Yes. That should work. I just figured it myself, your initial answer definitely put me on the right track. Here's what I'll be using: `over: function(event, ui) { ui.placeholder.prependTo(ui.placeholder.parent()); }` Thanks a lot!
Comment: You could fix this by adding `if($(this).children().length == 2) { }` around your `insertBefore()`.  It would be 2 because of the static item plus the placeholder.
Comment: Thanks @JeffB. `if ($(this).children().length == 2) { $(this).prepend(ui.placeholder); }` is indeed the complete answer to the problem I had.
Comment: Right. Thank you. The problem I have with this is that when you are dragging the item the placeholder will still be shown below the disabled item. So that's where it would be expected to land. I'm hoping for a more user-friendly solution.
Comment: Ah ok, that should fix it then. Now when you move an item to a connected sortable list, it should insert the placeholder before the first disabled li.
Comment: Hmm, except now, when you first hover over the drop area, the placeholder will be at the bottom, even if you are at the top.  It will eventually move to the right spot once you move in the list.
Answer: This might be more on the hack side of things, but you could add a sortable item to the top of each list that is 0px tall or display: none.  This will force the item to get sorted after that item instead of your un-sortable item.

word word word

word word word

must stay at bottom

CSS:
.hidden {
   display: none;
}

http://jsfiddle.net/HPM7V/2/
Comment: I like this better, actually. That way I don't have to worry about quirks in my manual override of the placeholder, as the other answer suggests. Once there's an item in the list, I want it to be 100% default. This route accomplishes that. I remove the hidden li on drop, and add it to any list that's empty after the move. Thanks for the idea.


JSP Code not running on server

Question: I have recently started learning jsp and have chosen eclipse as my working IDE, and Glassfish 4 as server. After finishing all the necessary setups I created my first jsp script and after running it on glassfish localhost server I got an error stating
org.apache.jasper.JasperException: PWC6345: There is an error in invoking javac. A full JDK (not just JRE) is required

After trying almost everything available on the internet for about 3-4 hours I gave up and downloaded apache-Tomcat. After starting tomcat by running the startup.bat it started. But when I tried loading localhost:8080 the same old glassfish page opened. Even after I stopped glassfish using asadmin stop-domain domain1
Still I kept getting the same localhost page opened whenever I tried opening the localhost:8080
And when I started to run the dynamic web project in a new apache tomcat server inside eclipse it kept saying
Several ports (8005, 8009) required by Tomcat v7.0 Server at localhost are already in use. The server may already be running in another process, or a system process may be using the port. To start this server you will need to stop the other process or change the port number(s).
I guess its glassfish which is using them still but I don't know how to stop it. Yeah, everything is messed up here.
After that I deleted everything inside eclipse the dynamic web project and all other servers(inside eclipse). And created both tomcat and glassfish seperately one after one to run the jsp. After running it the console window gave the following messages
Mar 13, 2014 12:12:39 AM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in             production environments was not found on the java.library.path: C:\Program      Files\Java\jdk1.7.0_51\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program    Files/Java/jre7/bin/client;C:/Program Files/Java/jre7/bin;C:/Program   Files/Java/jre7/lib/i386;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\    System32\WindowsPowerShell\v1.0\;C:\Program   Files\Java\jdk1.7.0_51\bin;C:\glassfish4\bin;C:\eclipse;;.
Mar 13, 2014 12:12:39 AM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source'        to 'org.eclipse.jst.jee.server:DemoJSP' did not find a matching property.
Mar 13, 2014 12:12:39 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
Mar 13, 2014 12:12:39 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
Mar 13, 2014 12:12:39 AM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 476 ms
Mar 13, 2014 12:12:39 AM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Mar 13, 2014 12:12:39 AM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.52
Mar 13, 2014 12:12:40 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
Mar 13, 2014 12:12:40 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
Mar 13, 2014 12:12:40 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 474 ms

And the eclipse web browser opened a window which said HTTP Status 404 - Not Found The requested resource is not available.
And when I tried running it on glassfish nothing happened just nothing. However when I opened the admin page in glassfish server page there was the jsp file i tried to run using eclipse. when I tried launching it, a new webpage opened with HTTP Status 404 - Not Found The requested resource is not available. And when I stopped glassfish and ran the jsp again the console window of eclipse flowed with almost 3-4 pages of texts of which I was unable to figure out a single thing.
Now I am absolutely new in this field. I don't have much idea about setting up servers in a system. I was just following tutorials available in the internet. Now though I have already stopped glassfish several times but still when I try to open localhost:8080
the same glassfish server page opens, not the tomcat one which is currently active. Its all messed up. I don't even know how to uninstall these servers. I think I have made a mistake by chosing eclipse and setting these up manually. The netbeans JavaEE with Glassfish server package would have been better.
Please somebody get me out of this mess. It is simply painful. And thanks in advance.
EDIT : The problem is solved partially, the tomcat is working under eclipse. I don't know how and why but after I deleted the glassfish servers and and stopped it via the command prompt and created new tomcat servers in eclipse it worked. Whenever I try to run the whole Dynamic web project it gives me a 404 HTTP error. But if I select  the jsp file and run it separately on server it runs. But still whenever I try going to localhost:8080 through my web browser it still brings me to the glassfish page, which I have already stopped several times and deleted from eclipse.
Comment: Well do you have a JDK installed?
Comment: Yeah I have jdk  1.7.0_51 installed in my system.
Comment: Well http://stackoverflow.com/questions/16340711/tomcat-http-status-404  solved it. Thanks for all other responses.
Answer: It will be good to use Apache tomcat with the eclipse but for that you need not to install that separately it may cause dangerous situation as some ports already remains in use.tomcat by default uses 8080 to which you can change from eclipse also.

go to services and stop all the Apache services running and set them to manual start.

2.In eclipse create a new server by specifying the location of your server directory
3.start you project in it. also if you want to run that in browser use window ->run on default system browser.
Comment: Sorry sir, but i was unable to find a single apache service running through the taskmanager. Can ypu please tell me how to do it? The other steps are ok by me.
Comment: type service in windows start screen you will get something life services .and try finding like the snapshot i have shared.
Comment: Sorry but no luck again. No I don't have any services running in my PC which has the name apache in it.
Comment: did you check in control pannel is there any tomcat/apache program there or may be you using tomcat for xampp i.e for php.
Comment: start from initial uninstall all the servers from your machine either xampp,wamp,apache ,glashfish ,iis or whatever it is,and check for the post using netstat -o command,and dont use those ports.and 2nd thing are you using apache installer file or zip contents?
Comment: I have installed the servers by simply unzipping them to C:\ and starting startup.bat for tomcat and running the asadmin start-domain --verbose for glassfish and adding the glassfish/bin directory to my path variable. And about uninstalling them again I don't have much idea :)
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/49634/discussion-between-a5l-le5-and-allocated)
Comment: i think you are at a wrong path.start eclipse and it will give you an option to run your code ,you don't need to start tomcat explicitly eclipse will take care of that and glassfish is pretty boring i think so better use apache.

JSP Code not running on server


Transformation of mix normal and skew features

Question: I have a weather dataset containing four features that are continuous values. Temperature is almost normal, but precipitation is highly negatively skewed. In addition, wind speed and humidity are positively skewed!
Performing log transformation on all features can somehow improve the skewness of the precipitation but no other features.
Can I perform a transformation on each feature separately? For example, implementing log transformation on temperature, and cube root on precipitation.
It should be noted that features are independent and not correlated.
Comment: Are you really sure those features are independent? Precipitation and Humidity?
Comment: Yes, they are independent. Their dependencies are not my issue. My objective to ask this question is can I transform each column according to its skewness condition? For example, np.log(df['Precipitation']), np.sqrt(df['Temperature']) are acceptable or not?
Answer: It is absolutely standard to perform a transformation of your features and then fit a model to those transformed features. Authors like Bishop even use the name "linear regression" for this combination of transformation and fitting a linear model, see e.g. his book:

Bishop, Christopher M., and Nasser M. Nasrabadi. Pattern recognition
and machine learning. Vol. 4. No. 4. New York: springer, 2006.

So, in particular, if your transformations np.log(df['Precipitation']) and np.sqrt(df['Temperature']) satisfy the assumptions of your model better than the original features, you should apply them.
Answer: First, note that there is no normality assumption about the features, so you might be transforming for nothing.
However, if you choose to transform, it is fine to use different transformations of different variables. The following is still a linear regression.
$$
\hat y=\hat\beta_0
+
\hat\beta_1 \log(x_1)
+
\hat\beta_2 \sqrt[3]{x_2}
$$
If you have theoretical reasons to care about the logarithm and cube root, or if those transformations improve your performance, perhaps those transformed variables and the features to input into your regression.
Jeffrey Miller's  "mathematicalmonk" channel on YouTube has a good video about this topic. He takes it a step further and allows for transformations involving multiple variables, such as using $\sqrt{x_1x_2}$ as a feature.


Upload imagem no servidor AJAX serialize e PHP

Question: Boa tarde amigos, eu estou fazendo um website que a pessoa faz o cadastro no meu form e eu, utilizando AJAX, jogo os dados no banco.
Eu queria saber como faço pra guardar essa imagem que a pessoa colocou no form em alguma variavel, para que minha function de upload possa usa-la assim que ele for cadastrado.
Por exemplo:
function saveCliente(){
    $.post("../setters/addLojaPainel.php", $('#form').serialize(), function (response) {
        if (response.result == "1") {
            doUpload(response.id);
            getData();
        }else{
            alert(response.exception);
        }
    });
}

ou seja, quando o resultado da request for 1 (sucesso) ele utiliza o doUpload, função para armazenar a imagem no servidor, utilizando outro dado do request.
Porem, não sei como armazeno a imagem que está no form.
Espero ter sido claro, é que o codigo é muito extenso e ficaria inviavel colar aqui.
Grato
Comment: No momento que você envia os dados via POST para realizar o cadastro, você poderia também enviar a imagem usando um input do tipo file. No PHP você usa $_FILE['nomeDoInput'] pra controlar o arquivo enviado.
Comment: mas eu consigo pegar essa variavel no JS? @ClaydersonFerreira
Comment: Não. Mas precisa mesmo pegar no JS? Pelo que entendi da sua pergunta, você poderia fazer o cadastro do cliente e upar a imagem via PHP em uma requisição AJAX.
Answer: A função serialize para formulários só é capaz de serializar dados que não sejam do tipo file
Para fazer upload da imagem, você precisará contornar essa situação alterando a forma com que a função $.ajax trata os dados:
upload sem refresh com FormData, jquery
Se preferir ainda tenho uma solução pronta no gist para resolver esse problema:
https://gist.github.com/wallacemaxters/7f29b8c8702d06a2afdf
Vou lançar o código aqui por conta da recomendação do site de não depender apenas de links externos:
(function ($) {

    var defaults = {
        cache: false,
        contentType: false,
        processData: false,
        type: 'POST',
        onProgress: new Function,
        xhr: function (xhr) {

            var xhr = $.ajaxSettings.xhr();

            xhr.upload.addEventListener('progress', function(e) {
                var percent = parseFloat(((e.loaded / e.total) * 100).toFixed(2));

                defaults.onProgress(percent, e);

            }, false);

            return xhr;
        },

    };

    $.fn.ajaxUpload = function (options) {

        var formData = new FormData;

        // if element is a form, find all inputs

        if (this.is('form')) {

            var $el = this.find(':input');

        } else {

            var $el = this;
        }

        $el.each(function() {

            var $that = $(this);

            var name = $that.attr('name');

            var files = $that.prop('files');

            var value = $that.val();

            if (!name) return;

            // when input not has file, we know that is a common input

            if (!files) {

                formData.append(name, value);

            } else {

                // Handles single file or multiple file

                $.each(files, function(i, file) {
                    formData.append(name, file)
                });
            }
        })

        options = $.extend(defaults, options, {
            data: formData
        });

        $.ajax(options);
    }

})( jQuery );


How to find a bug in my date arithmetic shell script?

Question: I wrote below piece of code to calculate the date after a given date:
date=$DATE_FINAL
declare -a  max_month=(0 31 28 31 30 31 30 31 31 30 31 30 31)
eval $(echo $date|sed 's!\(....\)\(..\)\(..\)!year=\1;month=\2;day=\3!')
(( year4=year%4 ))
(( year100=year%100 ))
(( year400=year%400 ))
if [ \( $year4 -eq 0 -a \
        $year100 -ne 0 \) -o \
     $year400 -eq 0 ]
then
declare -a  max_month=(0 31 28 31 30 31 30 31 31 30 31 30 31)
fi
day=$((day+1))
if [ $day -gt ${max_month[$month]} ] >| /wload/baot/home/baoted9/logs_bde27_conversion_1/ataa_display.logs 2>&1
then
  day=1
  month=$((month+1))
  if [ $month -gt 12 ]
  then
    year=$((year+1))
    month=1
  fi
fi
if [ $month -eq "08" ] ||  [ $month -eq "09" ]
then
future_date_final=$(echo $year"$month"$day)
else
future_date_final=$(printf "%4.4d%2.2d%2.2d" $year $month $day)
fi
echo "this is your final business date $future_date_final"

It calculates the date correctly however throws an error at the end of the code as below -
line 79: 08: value too great for base (error token is "08")

It just looks too ugly, not sure how to remove it as otherwise code is working fine, tried redirecting it to a log file still appearing.
Also, I am facing issue with below code for a plain cd command with code highlighted in red -
echo "pset  date $Param_date_1"
cd /wload/baot/home/baotasa0/sandboxes_finance/ext_ukba_bde/pset >| /wload/baot/home/baoted9/logs_bde27_conversion_1/at_display.logs 2>&1
sh UKBA_publish.sh UKBA $Param_date_1 3 >| /wload/baot/home/baoted9/logs_bde27_conversion_1/ate_display.logs 2>&1

Error is -
./auto2.sh: line 190: syntax error: unexpected end of file

Comment: Run your code through http://shellcheck.net/ and fix what it finds. And [stop using `eval`](http://mywiki.wooledge.org/BashFAQ/048).
Comment: Hmmm, may I suggest https://unix.stackexchange.com/questions/49053/linux-add-x-days-to-date-and-get-new-virtual-date ?
Comment: The error on line 79 *does* impact correctness -- it'll make your comparison always false, whether it *should* be true or false.
Comment: ...that issue is because numbers starting with a leading 0 are parsed as octal, and `8` is of course an impossible digit in octal numbers. Don't put leading zeros on your values used for calculation -- add them in at output time only.
Comment: (BTW -- StackOverflow is a Q&A database, not a forum. That's critical, because it's why we insist on having quality questions as well as quality answers: Both are written not just to help the person with a problem, but to help *everyone with a similar problem* in the future; thus, we care more about future readers, of which there are many, than the person who first came in with a question, of which there is only one -- hence all the rules lawyering, of which you're likely to see much).
Comment: You might be better off with a conversion to and from a julian day number.
Answer: The problem is, that if you're using $((val+1)) where $val is beginning with a 0, then bash isn't operating on decimal base but on octal base. Since 08 isn't a valid number in octal base, it complains.
You can force decimal representation by writing
$((10#$val+1))

Please note, that by doing so, any preceding zeros are removed. If you need to have a representation with preceding zero, just use
val=$(printf '%02d' $((10#$val+1)))

For reference, see the bash manual:

Constants with a leading 0 are interpreted as octal numbers. A leading '0x' or '0X' denotes hexadecimal. Otherwise, numbers take the form [base#]n, where the optional base is a decimal number between 2 and 64 representing the arithmetic base, and n is a number in that base. If base# is omitted, then base 10 is used. When specifying n, the digits greater than 9 are represented by the lowercase letters, the uppercase letters, '@', and '_', in that order. If base is less than or equal to 36, lowercase and uppercase letters may be used interchangeably to represent numbers between 10 and 35.

P.S.: This is a very good article about falsehoods programmers believe about time I had to read myself. If possible, try to use date -d instead of doing manual date arithmetic. You can use for instance date -d "+5 days" +%d.%m.%Y to get the date in five days.


Equivalence relation/class on the quotient ring $\mathbb{R}[X]/(X^2 + 1)$.

Question: I an going through a class in abstract algebra, as we go from one chapter to another, the quotient theory comes back over and over, but the teacher never explicitly states the equivalence relations used, I am rather unsure how is the relation equivalence defined when we work, for example, with: $$\mathbb{R}[X]/(X^2 + 1)$$
If I take two polynomials $A,B \in \mathbb{R}[X]$, then we have $A = (X^2 + 1)Q + R$ and $B=(X^2 + 1)Q' + R'$, so what is the condition so that $A \sim B$? Would it be $R = R'$, or maybe $Q = Q'$.
Answer: The easiest way to say it is that $P \sim Q$ if $P-Q \in (X^2+1)$.
To see this, suppose that $P(x) \sim Q(x)$, then $P(x)-Q(x)= g(x)(x^2+1)$, so $P(x)=Q(x)+g(x)(x^2+1)$, or in other words, $P(x) \in Q(x)+(x^2+1)$, and likewise, $Q \in P(x)+(x^2+1).$
The same can be said when they are equivalent in the quotient.
Comment: @user401855 yes.
Comment: What does $P-Q \in  (X^2 + 1)$ exactly mean? Is it $P-Q = (X^2 + 1)C$ for some polynomial in $\mathbb{R}[X]$?


Man of the series award for two players from same team

Question: From this post, it's clear that more than one player can get the player of the series award in cricket.
From this post, it's clear that more than one player can get the player of the match award that too from the same team.
I have a query that,
Is there any instance in the history of cricket that more than one player from the same team got the man of the series award?
Comment: There is no rule at all in the question. It's just a trivia and history question IMO.
Comment: @hims056, I think batting performance or bowling performance will come under physical performance :)
Comment: I think you are misinterpreting the tag "*performance*". That tag is relating to the physical, mental, emotional performance not the overall performance (e.g. batting performance or bowling performance) in the match.
Comment: @hims056, removed that tag. Does the tag `officiating` suit this post?
Comment: Okay I have added [a question on Meta](http://meta.sports.stackexchange.com/q/527/540). Let's see what others think. If it is okay then I will try to edit the excerpt.
Answer: Having researched, I can not find any instance where man of the series has been awarded to two players from the same team, there have been instances of the single award being shared as described in the top link you provide.
Where there is a seperate award for each team I have been unable to find any sharing.


Convergence of one sequence

Question: If $(x_n)_{n\in\mathbb N}$  is sequence such that $\lim_{n\to\infty}|x_n-4|=3$ then $(x_n)_{n\in\mathbb N}$ must converge to what?
The answer is undecided but I can't understand why?
Is it a hint or clarification that helps me to understand.
Answer: It is undecided because:

if $(\forall n\in\mathbb{N}):x_n=7$, then $\lim_{n\to\infty}x_n=7$;
if $(\forall n\in\mathbb{N}):x_n=1$, then $\lim_{n\to\infty}x_n=1$;
if $x_n=7$ if $n$ is odd and $x_n=1$ otherwise, then the limit $\lim_{n\to\infty}x_n$ does not exist.

And in each case $\lim_{n\to\infty}|x_n-3|=4$.
Comment: When  the questions without  absolute like $ x_n -4 →3  is it undecided or covergence to 7 ?
Comment: @FatimHasan Then it converges to $7$.
Answer:
Let $x_n=1$ for all $n$. Then $|x_n-4|=3 \to 3$, as $n \to \infty$, $(x_n)$ is convergent.
Let $x_n=4+3(-1)^n$. Then $|x_n-4|\to 3$, as $n \to \infty$, $(x_n)$ is divergent.

Convergence of one sequence


Not Able To Access Google Cloud Bucket From VM?

Question: I am trying to transfer files from cloud bucket to VM. I am getting below error:
ServiceException: 401 Anonymous caller does not have storage.objects.get access to the Google Cloud Storage object.

How to resolve this issue?
Answer: The user of service account you use do not have permissions to access the bucket and copy from it. Add roles "Storage Admin" or "Storage Object Admin" to the user you are trying to connect to the bucket.
Add role to a user:
https://cloud.google.com/iam/docs/granting-changing-revoking-access#grant-single-role
Cloud Storage roles overview:
https://cloud.google.com/storage/docs/access-control/iam-roles#standard-roles
Answer: What I ended up doing, on my local machine (it is slightly different on Colab), was to create a Google Cloud service account.
You can then do 2 things:

create a key for this service account that you then download on your VM, and set the path as export GOOGLE_APPLICATION_CREDENTIALS=<JSON_FILE_PATH>.
add roles to this service account so that it can read/write from the right buckets.

You can find more about it in the docs.
You then authenticate with this service account using gcloud auth activate-service-account --key-file=<JSON_FILE_PATH>.


Add C object to Python List & return the list of C objects to python

Question: I am writing C extensions for python.
I want to know how to add a C object to python list using PyList_SetItem.
For example,
I have a C object.
Atom *a = (Atom *)(PyTuple_GET_ITEM(tmp2, 0));

I made a list:
PyObject* MyList = PyList_New(3);

I am not sure what the third argument must be in the following statement.
PyObject_SetItem(MyList, 0, a);

Also how do I return this list of C objects to python.
Answer: The third argument to PyList_SetItem is the Python Object to be added to the list, which is usually converted from a C type, as in this simple example:
/* This adds one to each item in a list.  For example:
        alist = [1,2,3,4,5]
        RefArgs.MyFunc(alist)
*/
static PyObject * MyFunc(PyObject *self, PyObject *args)
{
   PyObject * ArgList;
   int i;

   PyArg_ParseTuple(args, "O!", &PyList_Type, &ArgList));

   for (i = 0; i < PyList_Size(ArgList); i++)
   {
      PyObject * PyValue;
      long iValue;

      PyValue = PyList_GetItem(ArgList, i);

      /* Add 1 to each item in the list (trivial, I know) */
      iValue = PyLong_AsLong(PyValue) + 1;

      /* SETTING THE ITEM */
      iRetn = PyList_SetItem(ArgList, i, PyLong_FromLong(iValue));

      if (iRetn == -1) Py_RETURN_FALSE;
   }

   Py_RETURN_TRUE;
}

PyObject_SetItem is similar.  The difference is that PyList_SetItem steals the reference, but PyObject_SetItem only borrows it.  PyObject_SetItem cannot be used with an immutable object, like a tuple.
Comment: What is the equivalent function for PyLong_FromLong if I want to add a C object (Atom) to the list?
Comment: Not to be nitpicking, but this answer doesn't add an item to a list.  It takes an existing list and updates the values.
Comment: @Jiminion:  you are right, that is what `PyList_SetItem` does.  The OP specifically asked for this API, but of course it does not append: `PyList_Append()` is required for that (or `PyList_Insert()` could be used).


How do I restrict uploaded images to a specific aspect ratio?

Question: What I would like to do is, using the Image field in core, to restrict uploaded images not just on resolution, but also on aspect ratio.
In other words, the image must be 2:3 width to height, and at least 200 by 300 pixels.
I know that Image Styles can manipulate the way an image is viewed. I'm not interested in that. Rather, I want to restrict uploads the same way that you can currently set min/max settings for resolution, I want to add aspect ratio.
My guess is that I'll need to write my own module to add a new check to Image's checks, but perhaps you know of a simpler way.
Comment: I'm not aware of such module either. Upvoted.
Answer: My advice would be to implement a custom file validator.
To see how these are used when saving files, you can check out file_save_upload. For an example implementation that is very close to what you want to achieve, check out file_validate_image_resolution.
My super quick attempt at this
<code>/**
 * Validates an image upload as having a particular aspect ratio
 *
 * @param $file
 *   - the uploaded file
 * @param $aspect_ratio
 *   - the apect ratio in the format [WIDTH]:[HEIGHT]. E.g. '3:2'
 */
function file_validate_image_aspect(stdClass $file, $aspect_ratio = 0) {
  $errors = array();

  // Check first that the file is an image.
  if ($info = image_get_info($file->uri)) {
    if ($aspect_ratio) {
      // Check that it is smaller than the given dimensions.
      list($width, $height) = explode(':', $aspect_ratio);
      if ($width * $info['height'] != $height * $info['width']) {
        $errors[] = t('The image is the wrong aspect ratio; the aspect ratio needed is %ratio.', array('%ratio' => $aspect_ratio));
      }
    }
  }

  return $errors;
}
</code>
Comment: Supremely helpful. This was the pointer in the direction I was looking for. I am going to give it a shot. Tons of thanks.
Comment: I looked around, and I was confused as to why file_validate_image_resolution always returned an array, even if there were no errors. Then I found the discussion of [file_validate](http://api.drupal.org/api/drupal/includes%21file.inc/function/file_validate/7) which I am linking to here for anyone else.


How to warmup Symfony environment before a functional test to check execution time?

Question: In the functional tests of a Symfony5.2 application, I added some profiling assertions to check execution time.
    private static function assertTime(?Profile $profile, int $milliseconds = self::MAX_TIMES)
    {
        if (null === $profile) {
            static::markTestSkipped('To test time of this use case, please unable profiling');
        }

        /** @var TimeDataCollector $time */
        $time = $profile->getCollector('time');
        static::assertLessThan(
            $milliseconds,
            $time->getDuration(),
            sprintf(
                'Checks that execution time (%dms) is less than %dms (token %s)',
                $time->getDuration(),
                $milliseconds,
                $profile->getToken()
            )
        );
    }

It works fine.
But each time I launch my testsuite, the first test failed because of execution time:
symfony php ./bin/phpunit
PHPUnit 9.5.0 by Sebastian Bergmann and contributors.

Runtime:       PHP 7.4.6 with Xdebug 2.9.5
Configuration: /home/alexandre/PhpstormProjects/bb-one/phpunit.xml.dist

Testing
F.........................                                        26 / 26 (100%)

Time: 00:19.352, Memory: 82.50 MB

There were 1 failure:

1) App\Tests\Functional\MailTest::testShowArchived
Checks that execution time (2952ms) is less than 1000ms (token b6742a)
Failed asserting that 2952.1640625 is less than 1000.

I know this is the first functional test, because, if I change default order, I have:
symfony php ./bin/phpunit --order-by reverse

There were 1 failure:

1) App\Tests\Functional\MailTest::testShowTrash
Checks that execution time (2868ms) is less than 1000ms (token a3342a)
Failed asserting that 2868.4316425 is less than 1000.

I tried to purge then warmup cache, before launching testsuite but it changes nothing.
I read this answer, but it isn't a good answer.
I tried to start the server in test mode, no change.
I tried to create a kernel in the bootstrap to call the console and clear the test cache (it didn't help)
I tried to create an initial test like AAATest::testAAA(){/*..some functional test without profiling assertion ..*/}, this solution is acceptable when we launch our full tests as you can see in the below output:

Testing
...........................                                       27 / 27 (100%)

Time: 00:20.783, Memory: 76.50 MB

OK (27 tests, 174 assertions)

But when a developer is optimizing a specific use case of the site, he only launchs the corresponding test, and the time is increased by startup and the test failed.
I find a bad solution to avoid that the first one failed during the full testsuite. Now, I'm searching a solution to avoid that my test failed when I launch only one test!
Comment: Can you post your bootstrap.PHP
Comment: When you warm up the cache you do it for the test environment? `php bin/console cache:warmup --env=test`
Comment: Yes, it is. As I am on linux env, I launch `APP_ENV=test symfony console cache:warmup`. I don't think it change anything, but I will check with your command when I come back home and reply to you. Thank you.
Comment: As I expected it, it doesn't change anything. The first functional test fails.
Comment: Have a look at https://symfony.com/doc/current/testing/bootstrap.html that should help with what you are trying to do.
Comment: Have you tried to disable Xdebug?
Comment: @Artem : I need it for code coverage.
Comment: @nicholasnet I used it to force the cache to clear and warmup. It doesn't change. The first functional test is always slowed down.
Comment: @nicholasnet it is now empty. I instanciated a kernel to call the console command that clear cache. As it didn't change anything, I removed it. (I edited my answer to explain it. You could look it in the list explaining my tries.
Answer: We probably miss more context on the aim of your tests because I don't understand how you can collect usable results with a single run of each test to get an accurate profiling.
I think what you are looking for is of course cache warm-up as already said but you might solve your problem taking advantage of PHP preloading and its integration with Symfony.
By tagging your services accordingly to your tests you will probably yield the necessary performance to pass your tests.
But again, give more context about your intentions profiling your code in tests. I suggest that you take other approaches to load testing.
Comment: Main objective is to detected slow pages during development. So for each functional test, we add an assertion to check that execution time is under a defined time.
Comment: And it works for all tests but the first one.
Comment: Makes sense. Have a look at codeception, it might handle warmup in a better way?
Comment: As a workaround, you might get a more reliable metric of performance by counting the requests Doctrine makes and their execution time. We implemented such a method on a python project wich automated database access monitoring while running tests to warn about potential bottlenecks.
Comment: It's already done, I catch the Doctrine DataCollector and I detect similar queries to avoid the "n+1 queries" bug. I check execution time of each query, too. I only have a problem with the first functional executed test.


error in unwind command "Neo.ClientError.Statement.SyntaxError: Invalid input 'p': expected whitespace"

Question: While loading data from csv file to neo4j, I am using below cypher query.
Load csv  from
   "file:///resume" AS row
FIELDTERMINATOR
   '\u0001'
WITH
   row, split(row[4], "|") AS pskills ,
   split(row[5], "|")  As frameworks,
   split(row[6], "|") As databases,
  UNWIND
     pskills AS lang
  UNWIND
     frameworks AS fw
  UNWIND
     databases As db
  MERGE
   (p1:Person {name: row[1],id:row[0]})
  MERGE
    (p2:Skill:language {name: lang})
  MERGE
    (p3:Skill:framework {name: fw})
  MERGE
    (p4:Skill:database {name: db})
  MERGE
    (p1)-[:SKILLED_IN]->(p2)
 MERGE
    (p1)-[:SKILLED_IN]->(p3)
 MERGE
    (p1)-[:SKILLED_IN]->(p4);

which is giving error:

Neo.ClientError.Statement.SyntaxError: Invalid input 'p': expected
  whitespace, comment, '{', node labels, MapLiteral, a parameter, a
  relationship pattern, '(', '.', '[', "=~", IN, STARTS, ENDS, CONTAINS,
  IS, '^', '*', '/', '%', '+', '-', '=', '~', "<>", "!=", '<', '>',
  "<=", ">=", AND, XOR, OR, AS, ',', ORDER, SKIP, LIMIT, WHERE, FROM
  GRAPH, CONSTRUCT, LOAD CSV, START, MATCH, UNWIND, MERGE, CREATE
  UNIQUE, CREATE, SET, DELETE, REMOVE, FOREACH, WITH, CALL, RETURN,
  UNION, ';' or end of input (line 5, column 10 (offset: 189)) "  UNWIND
  pskills AS lang "
Answer: Remove the extra comma(,) before first UNWIND
Comment: Load csv  from  "file:///resume" AS row
FIELDTERMINATOR  '\u0001'
WITH row, split(row[4], "|") AS pskills ,
  split(row[5], "|")  As frameworks,
   split(row[6], "|") As databases
  UNWIND
     pskills AS lang
  UNWIND
     frameworks AS fw
  UNWIND
     databases As db
  MERGE
   (p1:Person {name: row[1],id:row[0]})
  MERGE
    (p2:Skill:language {name: lang})
  MERGE
    (p3:Skill:framework {name: fw})
  MERGE
    (p4:Skill:database {name: db})
  MERGE
    (p1)-[:SKILLED_IN]->(p2)
 MERGE
    (p1)-[:SKILLED_IN]->(p3)
 MERGE
    (p1)-[:SKILLED_IN]->(p4);


How can a guitarist treat and avoid lateral epicondylitis in the fretting arm?

Question: I've been playing guitar (both electric and acoustic) pretty seriously for about a year, 2-3 hours a day most days. I couple months ago I developed tendonitis in my fretting arm, which my doctor diagnosed as lateral epicondylitis, i.e. tennis elbow. My doctor predictably recommended laying off guitar for a while, using a compression bandage, icing it, taking ibuprofen, that sort of thing. I didn't see a specialist or physical therapist so the advice was sort of general.
I did more research on my own and found this article which describes a simple exercise that does eccentric loading of the tendon and is supposed to be great for this sort of injury, and it's been helping over the past few weeks. I do that plus daily icing of the tendons, which is also good. After a few weeks of abstinence I've worked up to playing a total of maybe 20 minutes every other day in short sessions (it's really bumming me out and I want to play a little). If anyone has more helpful advice on how I can treat it, I'm open, but I think it's just one of those things where you have to give it a few months to sort itself out.
My main question is this: assume I do all these things and in a few more weeks or a couple months, the pain is gone. How I prevent it from coming back? Do I need to make changes in my warmup/practice or my technique? I've read other questions from guitarists who have had fretting finger or hand pain; mine is related but in a different place.
My teacher, who's been teaching for 30+ years, didn't have anything at all to say about it; he's hardly heard of anyone having this sort of problem. I've talked to others and haven't learned a lot, other than that if you let it heal, you're not doomed to have it come back once you start playing again. I should definitely learn to develop a lighter touch when fretting notes and chords, which is something I've been working on, but other than that while I've heard of other guitarists who have had my condition, I haven't read a lot about what got them there and how they could avoid it.
Symptoms
Here's some additional information on my exact symptoms in case folks find this question because they're looking for info.
The pain is in my forearm, on the top/outside, a few inches below my elbow. When I first started getting it, I thought I might have had pain in the inside of my elbow too, but that wasn't the case -- I just wasn't locating the pain precisely. The pain isn't in the muscle, but the tendons that attach the muscles to the elbow. The pain isn't constant, but only comes on when I move my elbow to the extremes of its range, either bending or straightening, and also if I rotate my forearm outward. I have noticeable pain and greatly decreased grip strength if I extend my arm all the way and grasp something by pinching it between my thumb and other fingers. From what I've read these are all classic symptoms of tennis elbow.
Ironically, I have very little pain while playing, and I don't notice a particular pattern of more or less pain after I play or don't play, even into the next day. The pain isn't that intense; I wouldn't describe it as sharp, but any sort of chronic pain is something to be concerned about and correct; I don't want permanent damage.
Comment: I can't offer any advice on the physical condition that hasn't already been mentioned. But I have an idea to help with being bummed out about not being able to play: try playing a different instrument (with different arm mechanics) while healing. Or try to sharpen your singing. You can still make music and keep your ear sharp.
Answer: After a mononucleosis I had tendonitis twice in my right forearm.
The things you can do:

RELAX WHILE YOU PLAY!!!! That's the most important. Period. Ridiculously small amount of force you need when you play guitar. The approach of most people (including me, before I get to know methods of Jamie Andreas) is to use a lot of force, to ensure the string is pushed down, the strings are picked, etc. This is entirely wrong. You have to start from lightly touching the fingers and the neck of the guitar, and then figuring out the minimal required force to achieve your goals. First it will be very odd, as you will be losing the control. Then you understand that you can very much control the guitar with minimal energy as well. Later on, you will use force wisely, when needed.
My experience with the inflammation is that if you pay attention to your muscles, they will be telling you that you've worked too much. You had tendonitis, you KNOW that burning pain. You will start to feel that burning sensation again when you play too much; that's the limit your body can endure - injuries occur when people ignoring their limits. If you stop there, it will heal and strengthen for tomorrow. Take your time. Work on different talents: rhythm, train your ears, etc.
As Tim said, you better be playing daily less then having one-day marathons. Especially in the healing period. It's like if you are a runner who has inflammation, it's much better to walk daily a small amount, then sitting on your ass whole weeks. Also, muscles used for guitar playing are the same muscles then the rest. They performance is better with frequent small practice.

With the above methods I didn't have tendonitis for (about 7-8) years. I listened to my body and acknowledged my limits.
Comment: And what about the days after the next day? If there's no pain on those, you can increase the amount of practice. Also, please note that I had a serious viral infection that I wasn't aware of (after the visible syndroms I would have to be train lightly for a year!), so probably you can have a hidden inflammation in your body or an infection which wasn't completely healed.
Comment: The interesting thing with my injury is that I don't have any discomfort at all while playing, maybe only slightly if I'm stretching for a barre chord. I also didn't notice a particular pattern of having more or less pain the next day after practicing a lot or not at all.
Comment: The pain seems to follow overuse by maybe 2-3 days, though with a response that slow it's hard to tell if it's a real pattern or not.
Comment: To be honest, I'm not familiar with that pattern. My common sense would say you got to practice small amount every day (20 mins seems OK, to me). Seek out someone with a similar sport injury pattern, who has dealt with it. Also if a professional hasn't adjusted the neck of your guitar for you, it can be a huge a difference in terms of force needed to play the guitar.
Comment: Since the problem was in your right arm, I'm hoping you play left-handed. Otherwise you've been holding your pick too tightly.
Answer: Sounds like you need to address several issues. You're probably squeezing the guitar neck way too tightly using your thumb more as a vice than a guide. Not necessary at all. You may need to change the angle you hold the guitar at- it could be pulled into your body.Let it out so that your fretting arm has fresh air all around it : too many players have the arm resting on or touching their leg. You may need to consider the height you have your guitar at - if it's low, there's too much bending of the wrist. You may need to think about the angle of the guitar compared to the floor. If it's pointing upwards, it'll relieve the strain.
Apart from all the stuff above - play little and often. Your teacher should have picked up on any/ many of these points, and suggested alternatives. I'm guessing that in the long periods of playing, you're sitting down. Try different seat heights.You may even find that a change to lighter strings, or setting the guitar up properly, so you don't have to press so hard will make a big difference. Cure the cause rather than the symptom !!
Comment: I've definitely been squeezing too hard with the thumb, and I've also been pressing too hard when fretting notes, which puts even more stress on the thumb... I've been paying more attention to that since I started having pain. It hasn't made the pain go away, but I think I may need to let it heal completely and then better technique will hopefully keep it from recurring. Do you know more about problems with these specific tendons? They're involved with extending the fingers, not contracting them, which always I thought counterintuitive in a guitar RSI.
Comment: @Scott - it's not a problem I've come across in guitarists. The muscles/tendons of the thumb/wrist are more commonly affected, again, through gripping the neck too hard. I've posted on this site that one actually doesn't need to squeeze the neck to produce clear notes/chords.Tennis elbow is a misnomer - any overuse of a joint will produce some problems. Overuse in your case may well be physical positioning combined with prolonged playing. However, I'm not a doctor - never had the patients...
Answer:
How I prevent it from coming back?

To build on atoth's answer and his first point about relaxing your hand and arm:
I feel it is worth mentioning to all others who come and see this question, the possibility of changing your seated guitar playing position to help in the prevention of these sorts of problems.
Having started with a classical guitar and its traditional position and then moving to the electric guitar and its common position, I noticed increased strain on both the left and right arms (the right especially with fast picking sections) and more left-hand fatigue as well. I recommend, as my old guitar teacher did, trying the classical guitar position for seated practices.
The position is very comparable to the way which one must sit with a flying-V style guitar (A quick image search of "classical guitar position" will yield great visual examples),  with the bridge at about a 45 degree angle to the floor, the butt of the guitar resting on the inside of the right leg, the left leg raised (no need to buy a foot stool, just use some old books or small box if you have one lying around) and the crook of the guitar resting on the left leg. This position mechanically benefits both the elbows by opening up their bends to about 90 degrees (a more natural position, allowing more circulation)  and reduces how much ccw rotation the left arm requires for the hand to properly work its way around the fingerboard.
Try it at least once or twice and see if you feel any immediate benefit, but of course bodies are different: If you feel more pain in the short or long term, stop and return to the position which gives you the least discomfort
Answer: I haven't heard of this in any of my colleagues (guitarists) either, but I would say that you're right when you say that time will heal it. You'll probably have to put your gat aside for a couple of weeks for the sake of letting it heal, do some semi-regular stretches and light, easy strength exercises.
As for preventing it in future, my experience with this sort of injury is that once you've had it once, it's a whole lot more likely to come back again. You could try some physio on it while you're recovering (acupuncture, radiology, massage etc) - but keep doing light stretches and exercises on it and take it easy!
Answer: I'm answering my own question to document what I've been doing in case others find this question looking for help.
As of right now, I can only talk about what I've done to try to treat the injury; time will tell if changes I make to my technique (the other answers which suggest relaxing and not squeezing so hard seem right-on) prevent it from coming back.
Researching my symptoms more carefully, it seems like I may have tendonosis more than tendonitis. -itis is inflammation of the tendon, and I haven't seen other symptoms of inflammation -- no swelling, no redness, the pain isn't constant, and it didn't respond well to ibuprofen or basically not playing at all for about three weeks. -osis is degeneration of the tendon, from micro-tears that build up scar tissue.
I continued playing for maybe a couple months after first noticing the onset of symptoms (the pain was never so great that it was a dire concern, and I reached a good stopping place). Then I stopped playing and started trying to treat it.
In my question, I linked to an article about an exercise for tennis elbow. That describes an inexpensive piece of exercise equipment, a Thera-Band FlexBar, which is a rubber bar about a foot long that comes in varying diameters which correspond to resistance; I started with the red (10 lb) one and have worked up to the green (15 lb) one. You do an exercise where you grasp it in both hands, twisting it to force the hand of your bad elbow to try to curl inward, and do reps of straightening and slowly releasing your hand at the wrist; you can find pictures and videos of the exercise. This builds muscle and tendon strength by loading the tissues while they're stretching, which is supposed to be good for this type of injury (there's a similar type of thing you can do for -osis of the Achilles tendon in runners).
That exercise has helped somewhat. I've been icing the joint a couple times a day (always after doing that exercise to knock down any inflammation it may cause), and the icing has helped somewhat. I haven't been taking ibuprofen. I used an elbow brace for some number of weeks but stopped when it didn't really seem to be helping me. I stopped playing altogether for about three weeks, and after that would play a total of maybe 20 minutes every other day in short sessions, and only doing easy stuff.
All of these measures helped to a small degree, but after maybe six weeks of that I was at the point where the pain had lessened by maybe a third to half on a good day, but it was far from gone, and I still had decreased grip strength. The nature of the pain had changed a little, becoming slightly less localized and more diffuse, maybe due to the exercises, but I was starting to get a little discouraged even though I know these injuries can take a very long time to heal.
Within the past few days I've started heat treatment as well (a heating pad wrapped around my forearm), usually alternating with icing the joint, and that has made a huge improvement almost immediately. Within a couple days my pain is down by about 75%, even though I've been playing more (I got a new guitar, can't help myself). We'll see if this takes me to complete recovery, but I'm hopeful. If you're reading this because you have similar symptoms, you might want to evaluate your injury carefully to see if it's inflammation or not, because heat may not be the best treatment for inflammation, but if you're like me and ice alone isn't doing it, give it a shot.
Answer: I play bass and have had tennis elbow 4 times (3 in the plucking, 1 in the fretting). Each time I've gotten TE has been because of marathon practice sessions. I did not realize until after practice, that I'd gone too far and TE had started.
I've done everything out there to remedy TE- exercises/stretches, icing, heat, anti-inflammatories, playing relaxed, trigger point therapy, accupressure, massage, using an elbow straps, etc... unfortunately, the only way I've gotten completely gotten rid of if it to STOP playing (100% cold turkey) until it heals. In my case each time has taken 7-8 weeks.
Good luck with healing, Paul
Answer: i play guitar a lot, and new years eve the pain in my left arm was so constant and intense i had to call the emergency services. apart from the worry of nerve damage from the doctor that night my own doctor has diagnosed carpal tunnel and is booking me in for an op. it is very difficult to stop playing, been two weeks now and i can eel that my arm is still bad, or at least isnt gonna let me play too much. i havent tried any of the above treatments like cold compress or heat pads but am going to try them as i am getting to the point where i have to try everything to help. i think mine is a combination of tennis elbow and carpal tunnel problems. in the mean time i found this and boy, straight away i could feel it helped. check it out http://www.tennisarm.ch/  i am going to go easy with the exercises but his advice is to not stop what your doing, that there isnt a real trigger rather it is been a barrel filling up for years and you've just tipped obver the edge. the whole site makes a lot of sense and i felt the tension/pain ease almost immediatly. not to the point that it was healed but it has been the only thing that felt good and that was helping! hopefully it will help you.
Comment: If the injury really is more of a muscle cramp as that website says, it would explain why heat worked so well on it -- heat is great for cramped muscles. Be careful you have no inflammation if you try heat though, because inflammation needs ice, not heat. Also, check out that exercise equipment I linked to -- it does the same thing as the stretches the website talks about, but it does a fantastic job really targeting the muscles and tendons to be stretched. Also, if you have carpal tunnel at the same time, be careful you don't aggravate that while treating the elbow.
Answer: I have unfortunately had tennis elbow in both my elbows over the years. I am a panel beater and a guitar player. I've tried icing and stretching exercises and had cortisone injections when it got unbearable. By far the best for pain relief is a clasp that fits over my forearm just below my elbow. A simple device made of material and Velcro , a bit
Like a tourniquet. It stops the tendon from pulling away from the bone.i use it at work so I can continue to operate even when afflicted. Worth a try. Good luck
Comment: They make those devices specifically for tennis elbow.  I have used them in playing tennis.  They defiantly help.
Answer: I have also played guitar (classical) for 4 years. I practised a lot, especially the last 2 years 4 hours a day, and I was diagnosed with Epicondilitys.  I did some exercises and I got much better, I'm about to start using a brace.
The most important thing to do is relax while playing, as mentioned earlier. Very wise, but also very difficult if are not trained to hear your body. You must stop regularly, even if you don't hurt, for a minute or two. Relax and "contact" with your hands. Breaks are very important.
I think that patience and working with yourself will yield faster and better results.
Answer: I am a violinist, and lateral epicondylitis is common among classical string players, in my experience.  I have suffered from tennis elbow and various tendon injuries of the forearm for 10 years.  Please please, take it easy on the playing, even if it bums you out. Here's what happened to me: I played long hours, ignoring pain and stiffness, and caused an injury.  I didn't do the exercises that my physical therapist prescribed(just like the eccentric ones you found).  I have re-injured myself quite easily after a 6-month break.  Icing, taking a break and loading up on NSAIDS seems to help me, along with doing stretches and exercises from the PT.  .  Try to practice mindfully, thinking about where in your left hand you CAN relax, and practicing slowly enough so your left hand can relax in between chords or fingerings.
In reality though, tendons are really susceptible to re-injury.  Be careful!
Answer: Well, you asked how to prevent this in the future.  You need to build those muscles back up, preferably stronger than they were before the injury, without causing muscle strain/damage.  How do you do this?  Just do your guitar stretches!!!  Do your stretches!!!  And do them well.  If your fingers and arms do not feel limber (appropriately lubricated) before you begin playing, you are not ready yet.  You should literally be able to feel that your muscles are stretched and ready to be pulled.  It's like working a rubber band, warming and stretching those molecules, rather than just pulling it tight right off the bat.
Answer: I've never heard of or had this in my fretting hand/arm. But I do have the same thing you have in my picking hand/arm. I wear a Tommy Copper sleeve for the elbow 3 to 4 times a week, plus a compression wrap. I also have a friend that has the same thing I do in his picking hand/arm. What I do is stretch constantly, I find the tendons in both my forearms are very tight most days. I played last night, all I did was record 2 rhythm tracks, and today I'm sore. Also like you, when I'm playing I don't feel it, possibly because I'm so focused on playing, or maybe because I'm loose. Good luck to you getting healed up, its been my experience that this is a chronic type thing that will always return as long as your playing heavily.
Answer: I've been suffering similar tendonitis, but was diagnosed with both Tennis and Golf Elbow which basically means that the tendons on the top of my forearm, and the bottom, as if you were putting your palm out were badly inflamed along with inflammation of several nerve sheaths that were actually visibly inflamed.  Basically my fretting arm was a train wreck!
This problem was exacerbated during a time of high stress in my life, I was playing guitar probably about 6-8 hours a week, and I was working on rebuilding an old car in my spare time, plus the usual stuff work family etc. I advise that physical therapy is very useful if your insurance covers it.  I also received a cortisone shot that got me through the worst of it.  It has been more than a year now and it has settled down considerably.  I have not stopped playing, but I do play in short 20-30 min sessions and continue to use ibuprofen and icing after playing, which really work for me.  I had inflammation of the ulnar nerve which is particularly painful, which is a nerve that runs through the notch on the tip of your elbow. This is aggravated by something as simple as the arm rest in your car, wrenching or lifting up a heavy frying pan or a 40 pound kid. So you have to look at all your activities as a whole I've found to get better. The pain has gone from something that kept me up at night to manageable.
There is a lot of good advice in this thread, strengthening exercises I learned during PT with the large elastic bands or small dumbbells have helped. I have stopped using a death grip in my fretting hand most of the time and found it improved my technique. Stretching has helped, and destressing my life has helped.
Another thing that my PT taught me is that the muscles in your back balance the muscles in your arm, so doing rowing type exercises for your back and pushups or bench presses for your chest, along with forearm, upper arm and wrist exercises all help to balance out the delicate instrument that is your body.
Answer: Another consideration: do you slouch at the table, resting your upper body weight on your elbows? I noticed that after correcting for this bad habit, my forearm pain diminished. Could be related.
Answer: Bro I think I'm starting to have the same issue, no inflammation, but tightness and pain in the forearm below the elbow - I've been stressing about it for the last week and scouring the net for solutions. This video is the best I've found - do the digging in exercises, in and around the areas in your forearm that are tight. Do your stretching as well. I've just been doing this today and noticed a big improvement!!!
Answer: I've been playing guitar since 13, and I will be 27 soon.  This pain did not seem to show until I switched to playing more with my thumb.  I was also heavy in the gym which seems to exacerbate the issue.  Also big into saltwater and boy how that made the issue worse.  It mostly seems to deal with the aggravation of the ulnar nerve.  Try compression sleeves and wrist wraps it's just according where anatomically you are feeling the pain.  From PT videos I've gathered, the Ulna side of the foreman is always trying to overcompensate during certain activities bc the radius bone is longer than the ulna.  If I go weeks without playing which is rare and kick the bicep exercises it tends to subside.  Fishing causes the pain immediately.
Answer: I play both classical and pick-led styles of guitar, so I utilise a variety of techniques, playing positions etc. I also play squash regularly - I'm right handed. I had a two year period during which i played no squash and very little classical guitar (with the raised right hand plucking fingers). I restarted both simultaneously - and within a matter of weeks, I had acute right hand wrist pain (carpal tunnel/tendonitis) and also acute 'golfer's' elbow in the right arm. It was so bad that my whole right arm from wrist upwards was very painful and virtually useless for a while - bad when you can no longer indulge in two of your favourites pastimes; not fun with young children around the house either.
Fast forward 6 years on. I have been a regular squash player over the last 4 years or so and I still get golfer's elbow, but just do basic stretches and it rarely gets so bad that I cant play squash, although sometimes it is sufficiently painful that it restricts movement/cramps my style. I wear a simple neoprene sleeve over my right elbow whilst playing. With regard to guitar, I still play different styles on different guitars, but since the acquisition of a hand made concert classical, I went through an 18 month period pf practicing classical quite seriously (90 - 120 minutes per day).
Here's the new part: I have now developed golfer's elbow shooting/sharp pains in my LEFT elbow as well, something I never had until recently. Like other players have stated, it rarely bothers me whilst actually playing - it is in doing normal day to day stuff when I notice it.
Maybe it's something to do with the rigour involved in going through technical warms ups/exercises on the classical guitar, which has a fatter/wider neck than most steel string acoustics or electric guitars.
Anyway, glad to have found this forum and I will certainly be looking at some of the videos and exercises shared - thanks to those who posted helpful tips.
Comment: I appreciate your sharing this story, but it doesn't really seem to answer OP's question. Maybe this could be made into a genuine answer if you added more detail about the stretches and warmups that you found useful. Do you wear the neoprene support sleeve when playing music or when playing squash (or both)?
Answer: You can wear a tennis-elbow brace while playing because that's when the irritation initiates. I do the strengthening and stretching exercises but need to wear the tennis-elbow brace when sleeping and playing. I think the need to compress my grip on the fretboard aggravated the elbow tendons. Two costs about $8-9 on Amazon.


Otimização de condição

Question: É possível fazer uma comparação (se igual a 1 ou igual a null) mais simples do que a feita em meu código?
@((Model.Visibilidade == 1 || Model.Visibilidade == null) ? "checked" : "")

Comment: o `Visibilidade` é um `int?` assim?
Comment: Isso mesmo, é um `int?`
Answer: Não dá.
Eu faria assim:
@((Model.Visibilidade == null || Model.Visibilidade == 1) ? "checked" : "")

Coloquei no GitHub para referência futura.
Neste caso não dá problema porque é um int?, mas em casos de tipos por referência daria erro. Se for nulo e tentar fazer a comparação com um valor vai dar erro, então é o correto é comprar o nulo primeiro. Pra manter a consistência eu sempre faria nesta ordem, mesmo que neste caso possa comparar o valor primeiro.
Comment: Realmente a ordem está invertida, deveria dar erro, mas não deu. Sim é um `int?`
Comment: Não deu porque o valoe é 1, se fosse `null` daria erro.
Comment: Não, o valor realmente é null, o código está em um fomulário de inclusão/alteração, onde não exite valor default para o registro `Model.Visibilidade `
Comment: Isso aqui dá erro `Model.Visibilidade === 1`
Comment: C# não tem `===`. De fato não dá erro, não me lembrava desse comportamento do `int?`, e até faz sentido. Atualizei a resposta.

Otimização de condição


Big O Time Complexity of While Loops

Question: I am a bit confused about the time complexity, in the case of two seperate while loops.
I am aware that the code:
while(i<N){
     code
    while(k<N){
       code
    }
}

will have a complexity of O(n^2)
What about the case where we don't have nested loops, though?
while(i<N){
}
while(k<N){
}

Answer: So you run two loops, one after the other. If they both perform n iterations, then your code performs 2n loop iterations in total.
Now, 2n = O(2n) = O(n) (by the properties of big-O notation), so that is your time complexity.

Big O Time Complexity of While Loops


How to return a table of tables to Lua from C/C++ function, through a for loop

Question: I have a std::list of objects, and I want to give Lua a function that returns its 2D positions.
So I need to create a table of tables
<code>{ {x,y}, {x,y}, {x,y}...}
</code>
And since its all on a list, I need to create it while iterating the list..
<code>    lua_newtable(L_p);  // table at 0
    int tableIndex = 1; // first entry at 1

    for(    std::list<AmmoDropped*>::iterator it = m_inputAmmosDropped.begin();
            it != m_inputAmmosDropped.end();
            ++it ){

        // what do I do here

        ++tableIndex;
    }

    // returns the table
    return 1;
</code>
Indexed by integer keys, and by 'x' and 'y':
<code> positions[0].x
 positions[0].y
</code>
Id try by trial and error, but since I don't know / don't have how debug it for now, I'm really lost.
Comment: related to http://stackoverflow.com/questions/453769/how-do-i-create-a-lua-table-in-c-and-pass-it-to-a-lua-function
Comment: See also my library https://github.com/prapin/LuaClassBasedCall
Answer: It will go like this:
<code>lua_newtable(L);    // table at 0
int tableIndex = 1; // first entry at 1

for(std::list<AmmoDropped*>::iterator it = m_inputAmmosDropped.begin();
      it != m_inputAmmosDropped.end();
      ++it ){
    lua_createtable(L, 2, 0);  // a 2 elements subtable
    lua_pushnumber(L, it->x);
    lua_rawseti(L, -2, 1);     // x is element 1 of subtable
    lua_pushnumber(L, it->y);
    lua_rawseti(L, -2, 2);     // y is element 2 of subtable
    lua_rawseti(L, -3, tableIndex++)    // table {x,y} is element tableIndex
}
return 1;
</code>
warning: this is untested code from the top of my head...


Why isn't my sub-theme using its CSS file?

Question: I created a sub-theme of the Drupal8 W3CSS theme and followed their directions about copying and renaming files, and editing the info.yml file. I installed it, and set it as default theme. It works. (I can see my custom logo.) The styles.css file is not coming from my files, but from the default sub-theme, which I haven't enabled. When I view the source of a page, I see the following tag, which doesn't contain the path for the CSS file used in my sub-theme.
<code><link rel="stylesheet" media="all" href="/themes/d8w3css/drupal8_w3css_subtheme/css/styles.css?qbo25b" />
</code>
It could be I missed a step.
Do I have to do something with Composer after changing any .yml file of the theme? I did clear all the cache bins.
Comment: Without seeing the theme files, answering is most like blindfolded shooting. Did you check every template file? If there isn't anything there, it could be a hook implementation that changes a file path. I would rather search for *drupal8_w3css_subtheme* in all the files your theme is using.
Comment: Side note: You should put contrib themes under themes/contrib/ and your custom sub-theme under themes/custom/.
Comment: Thanks for the suggestions. Yes, I did a text search for drupal8_w3css_subtheme but couldn't find any references. Might have to walk through it with a debugger. I've done a lot of Drupal 7 theming, this is my first 8 project, lots of things to learn yet. I agree with creating contrib and custom subpaths. I installed the theme from the appearance page, and it didn't give me an option for destination, I would think they would figure it was a contrib and put it in the better place..
Comment: In which path is the theme installed? Instead of /themes/d8w3css/drupal8_w3css_subtheme, what should you see?
Comment: Yes, the user interface installs the themes in /themes,  not /themes/contrib. That's not something you can change.
Answer: In Drupal 8 you setup your subtheme libraries in subtheme.libraries.yml. These libraries are then loaded from subtheme.info.yml.
You should check the paths in those files if they are correct.
It's good practice to search for all occurrences of the base_theme's machine_name inside your subtheme folder and replace those with the machine_name of your subtheme.


parsley.js: Error trying to add custom validator

Question: I am trying to add a custom validator
window.ParsleyValidator
  .addValidator('invalidWords', {
    requirementType: 'regexp',
    validateString: function(value, requirement) {
        console.log(value,requirement);
      return /^\b(?:Stadium|GT|BB|HB|Simul|VNOSE|LT|combination|LT1|SSGT|BW|HBS|simul|combo|2hbs|4d|lt2|theatre)\b$/i.test(value)
    },
    messages: {
      en: 'Invalid words detected.'
    }
  });

with HTML as...

        <input type="text" name="company" data-parsley-group="eventinfo" id="Company" class="form-control" placeholder="Company" maxlength="60" tabindex="3" title="Company" parsley-trigger="keyup" data-parsley-invalidwords="" value="#request.args.company#">

I keep getting the error Callback must be instanciated with a function and I am not sure why. I am following the directions on the site. http://parsleyjs.org/doc/index.html#custom
It also doesn't seem to trigger on keyup either.
using version 2.0.7
Answer: I noticed I was on an older version so I have updated to 2.2-rc4 and the issue seems to be resolved.


On the existence of limits of multivariable rational functions

Question: Standard limit-related counterexamples in multivariable calculus include limits like
$$\lim_{(x,y) \to (0,0)} \frac{2xy}{x^2 + y^2}$$
which tends to $0$ if the origin is approached along $x=0$ or $y=0$, but approaches $1$ if the origin is approached along the line $x=y$. This implies that the limit does not exist.
Indeed, there's rational functions for which the limit exists (and is the same) along all lines containing $(x_0, y_0)$, and yet the limit still fails to exist. For example, if we consider
$$\lim_{(x,y) \to (0,0)} \frac{2xy^2}{x^2 + y^4}$$
the limit is $0$ along lines of the form $y=\alpha x$ but $1$ along the curve $y^2 = x$.
I was wondering if we could have a more general counterexample of this sort.

Suppose $g(x,y)$ and $f(x,y)$ are two-variable polynomials defined on an open subset of $\mathbb{R}^2$ containing the origin such that $\lim_{(x,y) \to (0,0)} f(x,y) = \lim_{(x,y) \to (0,0)} g(x,y) = 0$.
In addition, suppose the rational function $$\frac{f(x,y)}{g(x,y)}$$
tends to some limit $L$ when $(0,0)$ is approached along curves of the form $y=\alpha x^{\beta}$ where $\alpha \in \mathbb{R}$ and $\beta>0$ (the limit $L$ is independent of the curve). Does it follow that
$$\lim_{(x,y) \to (0,0)} \frac{f(x,y)}{g(x,y)} = L?$$
Comment: In curves $y=ax^b$ are you assuming $x>0?$
Answer: Take $f(x,y)=xy$ and $g(x,y)=x-y$. Then $$\frac{f(x,a x^b)}{g(x,a x^b)}=\frac{a x^{b+1}}{x-ax^b}.$$
Note that $a=1$ and $b=1$ are not allowed. If $b< 1$ you get
$$\frac{f(x,a x^b)}{g(x,a x^b)}=\frac{a x^{b+1}}{x^b(x^{1-b}-a)}
=\frac{a x}{x^{1-b}-a}\to \frac{0}{0-a}=0.$$
If $b> 1$ you get
$$\frac{f(x,a x^b)}{g(x,a x^b)}=\frac{a x^{b+1}}{x(1-ax^{b-1})}
=\frac{a x^b}{1-ax^{b-1}}\to \frac{0}{1-0}=0$$
and if $b=1$ you get
$$\frac{f(x,a x)}{g(x,a x)}=\frac{a x^{2}}{x(1-a)}
=\frac{a x}{1-a}\to \frac{0}{1-a}=0$$
since $a\ne 1$.
However the limit does not exist since if you take $y=x+x^3$ you get
$$\frac{f(x,x+x^3)}{g(x,x+x^3)}=\frac{x^2+x^4}{x^3}
=\frac{1+x^2}{x}\to \infty$$
as $x\to 0^+$.
Comment: Good example, although it didn't answer the question because we are to assume limit $L$ on all those curves.
Comment: Thanks! The curve $y=x$ is not in the domain of the function $\frac{f}{g}$. When you calculate a limit $\lim_{x\to x_0}h(x)$ you only approach $x_0$ along points $x$ in the domain of $h$. So the limit is $L$ along all the curves which belong to the domain of $\frac{f}{g}$.


UnexpectedParameter MessageGroupId for SQS

Question: I have created a FIFO SQS queue.
When sending a message to the queue using the below params,
var params= {
    MessageBody: payload,
    QueueUrl: sqsURL + body.device + ".fifo"
}
sqs.sendMessage(params, function(err, res) {
    err ? callback(err) : callback(null, res);
});

I get a warning that says "missing parameter messagegroupid"

I then proceed to add in MessageGroupId into my params.
var params= {
    MessageBody: payload,
    MessageGroupId: "posts",
    QueueUrl: sqsURL + body.device + ".fifo"
}
sqs.sendMessage(params, function(err, res) {
    err ? callback(err) : callback(null, res);
});

SQS then throws me "UnexpectedParameter: Unexpected key 'MessageGroupId' found in params".
Am confused by this set of conflicting instructions.
I'm using the same SDK region in both my createQueue and sendMessage command.
var sqs= new aws.SQS({ region: "us-east-2" });

Comment: FIFO queues seem to require the [SDK from 2016-11-17 or later](https://aws.amazon.com/releasenotes/Amazon-SQS/9087335643077522).  What version are you using?
Comment: Thank you for the suggestion... I change to var sqs= new aws.SQS({ region: "us-east-2", apiVersion: "2016-11-17" }); Same result though.
Comment: Same result for var sqs= new aws.SQS({ region: "us-east-2", apiVersion: "2012-11-05" });
Answer: I ran into this same error using Lambda (hence finding your post).  Wondering if they forgot to refresh the native SDK, I uploaded the latest version of the SDK(2.7.7) with my function and the error went away.
Since uploading the SDK removes the ability to edit in Lambda, I then deleted it and re-uploaded the function the error came back :(.
So for now, if you want to use it with Lambda, you have to include the SDK with your deployment package.
Comment: For Node.js, installing the latest aws-sdk using npm worked for me.
Answer: You've missed passing "MessageGroupId" parameter. You should pass Message group id as a parameter. It is mandatory for FIFO.
Please refer the below-mentioned link,
https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-sqs-2012-11-05.html#sendmessage


How to display field revisions?

Question: I want to keep field revisions: I want to see who changed a field to which value and when. Currently I can keep node revisions, but in the revisions tab, it only shows title and body changes.

How can I also keep field revisions?
How can I display revisions preferably like this:

User 1 changed Color: red to Color: green
User 2 changed Color: green to Color: white

Is the second one achievable by Views?
Answer: I came across a similar issue and found your post last week. After a bit of searching around I found this module:
https://drupal.org/project/track_field_changes
It appears to cover what you were looking for in terms of functionality as well as what I was trying to cover. I've since installed the module and set it up, but unfortunately whilst some of it is working for me I can't get a view to display the 'value after' or 'value before' fields (See https://drupal.stackexchange.com/questions/81507/how-to-display-values-in-the-value-after-value-before-fields-track-field).
If you still need this functionality perhaps try out the module - if you have success with it let me know as it's still not quite working fully for me, but that could be down to user-errors perhaps.
All the best
Tom
Answer:
Field revisions, at least in Drupal 6, exist alongside node revisions.
At least some of that functionality exists in the Diff module.
Comment: Indeed, the Diff module takes care of that.
Answer: Using the track_field_changes module, I was able to get the side by side values in a view.  Note , I also have revisions turned on for this node type.

How to display field revisions?


Basic vectors question

Question:
The components of a vector along $x$ and $y$ directions are $(n+1)$ and $1$ respectively. If the $xy$ coordinate system is rotated by an angle $θ=60°$ then the components change to $n$ and $3$. The value of $n$ is?
Answer: I think there is something wrong with your angle $\theta = 60°$.
Nevertheless the problem can be turned into a meaningful one.
Put $u = \begin{pmatrix} n+1 \\ 1\end{pmatrix}$, $v= \begin{pmatrix} n \\ 3\end{pmatrix}$. Since $v$ is obtained from $u$ by rotating, you have
$$|u|^2 = |v|^2 \Leftrightarrow (n+1)^2+1 = n^2 + 9 \Leftrightarrow 2n=7 \Leftrightarrow \boxed{n= \frac{7}{2}}$$
But, this corresponds to an angle of $\boxed{\theta \approx 28.1°}$.
Answer: You get something like:  $\begin{pmatrix}\frac12&\frac{\sqrt3}2\\ -\frac{\sqrt3}2&\frac 12\end{pmatrix}\begin{pmatrix}n+1\\1\end{pmatrix}=\begin{pmatrix}n\\3\end{pmatrix}$
Multiply through and solve for $n$.
So, from the first coordinate, we get  $n=1+\sqrt3$.  On the other hand,  setting the second coordinates equal yields $n=-\frac{5+\sqrt3}{\sqrt3}$.
Apparently we have $2$ equations in $1$ unknown,  and it's not consistent. So it's not possible...

Basic vectors question


using the webclient to upload a file in post and the php to recive and handle file

Question: how do i get the php to reconize that there is a file being uploaded to it by the vb webclient
current php code is this
if(count($_FILES)==1) {
    //move_uploaded_file
    ( $_FILES[0]["tmp_name"]  , "./imgs/curdesktop.png"  );

    file_put_contents("./nin.txt",print_r($_FILES));
}

all it does right now is check the FILE array and supposed to print the attributes out into a text file. however the vb program says that the file is uploaded with no errors and the $_FILES array returns 1 which is invalid for that array
Comment: What functions/methods do you use in vb to upload the file?
Does this perform a RFC 1867 compatible upload?
Answer: You have print_r() as a function which returns a value. Check first wat print_r really prints on the screen. (I think it does print it now already)
Answer: Try using var_export():
file_put_contents("./nin.txt",var_export($_FILES,true));

Passing true as the second argument will return the variable representation instead of outputing it, so the contents should write to the file.
Answer: Make that print_r($_FILES, true).


Can't stop LAMP graceful restart

Question: I just got my first LAMP up and running, everything works fine except that my server is restarting itself every sunday.
When I read the logs I see "Graceful restart requested, doing restart"
Should I just let my server do this or should I stop it?
It seems that some settings get lost in this process, Eg: sudo chown -R name:name /var/logs/
after this restart I dont have the permission and then I have to run
sudo chown -R name:name /var/logs/
again in order to get it back.
Here are some logs if it would help:
<code>[Sun Sep 15 07:35:02 2013] [notice] Graceful restart requested, doing restart

127.0.0.1 - - [15/Sep/2013:07:35:02 +0000] "OPTIONS * HTTP/1.0" 200 126 "-" "Apache/2.2.22 (Ubuntu) (internal dummy connection)"

[Sun Sep 15 07:35:03 2013] [notice] Apache/2.2.22 (Ubuntu) PHP/5.4.17-5+debphp.org~precise+1 configured -- resuming normal operations
</code>
Could piped logs help?
I still testing my application so I do have alot of errors.
The "/etc/logrotate.d" says:
<code>/var/log/apache2/*.log {
    weekly
    missingok
    rotate 52
    compress
    delaycompress
    notifempty
    create 640 root adm
    sharedscripts
    postrotate
        /etc/init.d/apache2 reload > /dev/null
    endscript
    prerotate
        if [ -d /etc/logrotate.d/httpd-prerotate ]; then \
            run-parts /etc/logrotate.d/httpd-prerotate; \
        fi; \
    endscript
}
</code>
Answer: Have you checked your logrotation (ex. <code>/etc/logrotate.d/apache2</code>) there could be a postrotate for your daemon.
Comment: Thanks, this is what it says:

/var/log/apache2/*.log {
 weekly
 missingok
 rotate 52
 compress
 delaycompress
 notifempty
 create 640 root adm
 sharedscripts
 postrotate
  /etc/init.d/apache2 reload > /dev/null
 endscript
 prerotate
  if [ -d /etc/logrotate.d/httpd-prerotate ]; then \
   run-parts /etc/logrotate.d/httpd-prerotate; \
  fi; \
 endscript
}

Can't stop LAMP graceful restart


Is there a nice expression for $f(x) = (1+x)(1+x^2)(1+x^3)\cdots$

Question: While I was solving a problem, I stumbled upon this function
$$f(x) = (1+x)(1+x^2)(1+x^3)\cdots$$
I tried to write out the first few products but I couldn't recognize any meaningful pattern. Is there some well known facts about this special function?
Thank you very much!
Answer: This is the generating function
for the number of partitions into
distinct parts:
http://mathworld.wolfram.com/PartitionFunctionQ.html


R - Como transformar valores em porcentagem usando Data.table?

Question: Possuo um data.table() com as colunas Região, ano e Quantidade.
A quantidade está em valor total, gostaria de torna-las em porcentagem por ano.
O que eu tenho:
     Região  ano  Quantidade
      Norte  2017        252
   Nordeste  2017        281
    Sudeste  2017       2038
        Sul  2017       2246
Centro-Oeste 2017        525
   ...
   ...

O que eu quero:
     Região  ano  Quantidade    % por ano
      Norte  2017        252          4.5
   Nordeste  2017        281            5
    Sudeste  2017       2038           36
        Sul  2017       2246           40
Centro-Oeste 2017        525          4.1
   ...
   ...

Estou tentando fazer isso com o lapply()
Estab_regiao <- Estab_regiao[,Freq:=Quantidade/tapply(Quantidade, ano, FUN=sum)*100,]
Mas estou com o seguinte erro:
Error in eval(jsub, SDenv, parent.frame()) :
  dims [produto 8] não corresponde ao comprimento do objeto [40]

Dados:
 dput(Estab_regiao)
structure(list(Região = c("Norte", "Nordeste", "Sudeste", "Sul",
"Centro-Oeste", "Norte", "Nordeste", "Sudeste", "Sul", "Centro-Oeste",
"Norte", "Nordeste", "Sudeste", "Sul", "Centro-Oeste", "Norte",
"Nordeste", "Sudeste", "Sul", "Centro-Oeste", "Norte", "Nordeste",
"Sudeste", "Sul", "Centro-Oeste", "Norte", "Nordeste", "Sudeste",
"Sul", "Centro-Oeste", "Centro-Oeste", "Norte", "Nordeste", "Sudeste",
"Sul", "Centro-Oeste", "Norte", "Nordeste", "Sudeste", "Sul"),
    ano = c(2017, 2017, 2017, 2017, 2017, 2016, 2016, 2016, 2016,
    2016, 2015, 2015, 2015, 2015, 2015, 2014, 2014, 2014, 2014,
    2014, 2013, 2013, 2013, 2013, 2013, 2012, 2012, 2012, 2012,
    2012, 2011, 2011, 2011, 2011, 2011, 2010, 2010, 2010, 2010,
    2010), Quantidade = c(252L, 281L, 2038L, 2246L, 525L, 233L,
    265L, 1952L, 2193L, 502L, 187L, 247L, 1881L, 2059L, 469L,
    155L, 195L, 1808L, 1975L, 449L, 113L, 182L, 1758L, 1830L,
    441L, 108L, 186L, 1746L, 1835L, 423L, 397L, 106L, 206L, 1697L,
    1749L, 345L, 98L, 185L, 1653L, 1584L)), row.names = c(NA,
-40L), class = c("data.table", "data.frame"))

Answer: Se entendi bem você pode fazer em duas etapas:
# quantidade por região
d[, total := sum(Quantidade), by = Região]
# frequência
d[, Freq := Quantidade/total*100]
# rm columa
d[, total := NULL]

Comment: Pode ser feito em uma linha com `d[, Freq := Quantidade/sum(Quantidade)*100, by = Região]`
Comment: Trocar região por ano * , aí da certo ! Muito obrigado ! Mas não rola fazer uma linha?
Comment: Não que eu saiba.