how to prepend nested elements using Jquery/Javascript?

Question: Just wondering if there is a better way than this:
 var $lftWrp = $( document.createElement( "div" ) ),
     $ctrlGrp = $( document.createElement( "div" ) ),
        .attr({'data-role':'controlgroup', 'data-type':'horizontal'})
        .controlgroup(),
     $buttons = $('.someButtons');

 $(this).prepend( $lftWrp.prepend( $ctrlGrp.prepend( $buttons ) ) )

to get something like this:

       Click
       Click

Specifically, is there a better way than "nesting" prepends()?
Thanks for help!
EDIT:
The prepend looks like this. Specifically, my problem seems to be that the buttons only get added on the last each-iteration. All other elements get the div and controlgroup. The last element gets div, controlgroup and buttons. No clues as to why...
 $('.fiveElemnts').each(function() {

     var $lftWrp = $( document.createElement( "div" ) ),
        $ctrlGrp = $( document.createElement( "div" ) ),
          .attr({'data-role':'controlgroup', 'data-type':'horizontal'})
          .controlgroup(),
        $buttons = $('.someButtons');
     //if I log buttons here, they are there
     console.log( $buttons );
     $(this).prepend( $lftWrp.prepend( $ctrlGrp.prepend( $buttons ) ) )
     });

Comment: Instead of `$( document.createElement( "div" ) )`, write `$('')`. It's the same thing, just looks better.
Answer: try this:
pure js / jQuery
HTML:

   Click
   Click

JS:
$.fn.controlgroup = function() {
    return this;
};

(function() {

    var
        $template = $('

'),
        $buttons = $('.someButtons');

    $template
        .find('>div')
        .attr({'data-role':'controlgroup', 'data-type':'horizontal'})
        .controlgroup()
        .append($buttons);

    $(this).prepend($template);

}).call($('.result'));

example
template
HTML

       Click
       Click

JS
$.fn.controlgroup = function() {
    return this;
};

(function() {

    var
        $template = $('.template-container').find('>div').clone(),
        $buttons = $('.someButtons');

    $template.find('>div').controlgroup().append($buttons);

    $(this).prepend($template);

}).call($('.result'));

example
for edit (template)
HTML:

    Click
    Click

JS:
$.fn.controlgroup = function() {
    return this;
};

var
    $template = $('.template-container').find('>div'),
    $buttons = $('.someButtons');

$('.fiveElemnts').each(function(i, el) {

    //template
    var
        $templateForThisUse = $template.clone();

    //example append
    /*
    var $buttonsForThisUse = $buttons.clone();
    $templateForThisUse.find('>div').controlgroup().append($buttonsForThisUse);
    */

    //best append - form link control
    var $ref = $templateForThisUse.find('>div').controlgroup();
    $buttons.clone().each(function(ib, eb) {
        $(this)
            .bind('click', function(event) {
                console.log('fiveElemnts('+i+') -> link ('+ib+')');
            })
            .appendTo($ref.append(' <spam>link ('+i+'-'+ib+'): </spam>'));
    });

    $(this).prepend($templateForThisUse);
});

run example
Comment: ok. one last question. If $(this) are multiple elements inside a each() function, prepend always removes the template and adds it to the next each-iteration $(this). What would be a way to insert the template in each "$(this)"?


Does anybody wish to help a poor researcher publish a paper?

Question: I don't know if this is a good place to beg for help, but here it goes: basically, I need to run a secure recommender system simulation (C++ console application) in order to meet tonight's deadline, and the faculty's server grid decided to go offline. I could really use something like 10+ (actually, about 16 would be required to meet the deadline) virtual instances of some Linux that has GMP installed... Ideally, they should all have the same specs, because a part of the simulation will represent performance benchmarks.
If my question is inappropriate in any way, I kindly ask the administrators to remove it.
Comment: If you are new to Amazon AWS you get some CPU power for free ... Check this link http://aws.amazon.com/free/
Comment: What's the question ?
Comment: @xXx Well, I was hoping that there's a bored sysadmin lurking around here, who wants to do something fun in his spare time :)
Comment: Change the question to "How to get large amounts of computer power for short time cheaply?" and you're good for ServerFault IMO.
Answer: Amazon Elastic Computing Cloud is what you're looking for. Those are relatively cheap servers rent on demand.
32 Extra Large servers for 8h will cost you a bit under $164. Those are 15 GB, 4 core, 8 thread machines with 1690GB of storage.
If you don't need something as big, there are machines from 1 core, 1 thread, 1.7GB or RAM up. There are also memory and CPU optimised instances.
If you want to have an already configured cluster machine, Quadruple Extra Large machines (23 GB memory, 33.5 cores) cost $1.3 per hour...


Ansible how to run powershell script

Question: Im using ansible 2.9.2 and i want to run a script that creates user on my windows machine,
The script works if i run in my powershell localy like this :
powershell.exe -ExecutionPolicy Bypass -File create_user.ps1 -pass "{{ pass }}" -user "{{ user }}" -gr "{{ gr }}"

Playbook:
  tasks:
    - name: "Createing windows user"
      local_action:
        module: vmware_vm_shell
        cluster: "{{ cluster }}"
        datacenter: "{{ datacenter }}"
        hostname: "{{ vcenter_server }}"
        username: "{{ vcenter_user  }}"
        password: "{{ vcenter_pass }}"
        vm_id: "{{vm_name}}"
        vm_username: "{{ vm_username }}"
        vm_password: "{{ vm_password }}"
        vm_shell: 'C:\Windows\System32\WindowsPowershell\v1.0\powershell.exe'
        vm_shell_args: powershell.exe -ExecutionPolicy Bypass -File create_user.ps1 -pass "{{ pass }}" -user "{{ user }}" -gr "{{ gr }}"
        vm_shell_cwd: 'C:\Users\myuser\Desktop'
        wait_for_process: yes
        validate_certs: no
      register: info
    - debug:
            msg: "{{ info }}"

From playbook i dont get any error but user is not being created, manually with same command all works.
is it because i use powershell as admin localy ? is there a way to do it here?
here is the output:
ok: [localhost] => {
    "msg": {
        "changed": true,
        "cmd_line": "\"C:\\Windows\\System32\\WindowsPowershell\\v1.0\\powershell.exe\" powershell.exe -ExecutionPolicy Bypass -File create_user.ps1 -pass \"********7\" -user \"Tomy\" -gr \"Localgroup\"",
        "end_time": "2020-01-14T13:44:32+00:00",
        "exit_code": 0,
        "failed": false,
        "name": "powershell.exe",
        "owner": "myuser",
        "start_time": "2020-01-14T13:44:31+00:00",
        "uuid": "4256795-43ec-87c2-fd4bf-5dffv6f2a4"
    }
}
localhost                  : ok=3    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

Answer: After upgrading from vmtools version:10346 to version:11265 All works!
And i have made this changes in my playbook:
  tasks:
  - name: Get all tags
    vmware_vm_shell:
      cluster: "{{ cluster }}"
      datacenter: "{{ datacenter }}"
      hostname: '{{ vcenter_hostname }}'
      username: '{{ vcenter_username }}'
      password: '{{ vcenter_password }}'
      folder: "{{ folder }}"
      vm_id: "{{ name }}"
      vm_username: "{{ vm_username }}"
      vm_password: "{{ vm_password }}"
      vm_shell: 'C:\Windows\System32\WindowsPowershell\v1.0\powershell.exe'
      vm_shell_args: -ExecutionPolicy Bypass -File create_user.ps1 -pass "{{ pass_word }}" -user "{{ user }}" -gr "{{ gr }}"
      vm_shell_cwd: 'C:\Users\Administrator\Desktop'
      wait_for_process: yes
      validate_certs: no
    delegate_to: localhost

Ansible how to run powershell script


React wrapper with Routes

Question: have wrapped my Route with Routes but it keeps showing me error that it needs to be wrapped in Routes
here is the exact error from my console
react-router-dom.js?v=74614133:209 Uncaught Error: A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>
below is my actual code
 <Routes>
          <Route
            path={ROUTES.LOGIN}
            element={
              <IsUserLoggedIn user={user} loggedInPath={ROUTES.DASHBOARD} navigate={Navigate}>
                <Route index element={<Login />} />
              </IsUserLoggedIn>
            }
          />
          <Route
            path={ROUTES.SIGN_UP}
            element={
              <IsUserLoggedIn user={user} loggedInPath={ROUTES.DASHBOARD} navigate={Navigate}>
                <Route index element={<Signup />} />
              </IsUserLoggedIn>
            }
          />
          <Route path={ROUTES.PROFILE} element={<Profile />} />
          <Route
            path={ROUTES.DASHBOARD}
            element={
              <ProtectedRoute user={user} navigate={Navigate}>
                <Route index element={<Dashboard />} />
              </ProtectedRoute>
            }
          />
          <Route path="/" element={<NotFound />} />
        </Routes>
      </Suspense>
    </Router>
here was what i tried and it is supposed to run

Comment: Hello , could you please provide the entire code from the file?
Comment: okay let me do just that
Answer: Your issue is about the nested Route Component in the Route:
<Route index element={<Login />} /> <-- this one should be also a direct child of a `Routes` Component.

I am not sure 100% about what you are trying to do but I would suggest something different:
  <Route
    path={ROUTES.LOGIN}
    element={
      <IsUserLoggedIn user={user} loggedInPath={ROUTES.DASHBOARD} navigate={Navigate}>
        <Login />
      </IsUserLoggedIn>
    }
  />

Do you think it makes sense for you?
Comment: did this exact thing but it is still asking me to wrap it in routes@Prince Sadariya

React wrapper with Routes


Differential equation $x^2\ln^2(x)y''-2x\ln x(\ln x+1)y'+(2\ln^2x+3\ln x+2)y=0$

Question: $x^2\ln^2xy''-2x\ln x(\ln x+1)y'+(2\ln^2x+3\ln x+2)y=0$  (linear)
$A(x)y''+B(x)y'+C(x)y=0$ represents the equation.
What I've tried:

Solving it using substitution $y=UV$, which as far as I know, is used only when the power of x isn't decreasing going from left to right, but I've tried. I won't go into detail. For V you get $V=x\ln x$. When I plug that in you don't get a differential equation with constant coefficients.
$$x^2\ln^2(x)U''+2U=0$$ Which I can't solve also.

2.Using a $t=\displaystyle\int \sqrt{C(x)/A(x)} \, dx$ you get this. Used $z=\ln x$ to simplify, and $1/2$ as a allowed constant under the square. Result is not helpful.

Final method, which I know of, is finding a particular solutions, $y_p$ and then using a $y=zy_p$ substitution. I've tried so many combinations. Form of a particular solutions is so that's it's derivative is somewhere in a $B(x)/A(x)$. I'm not 100% sure about this statement.

Didn't want to write too much, I hope it's understandable.
Comment: one solution is $x\ln(x)$
Comment: i have sea´rched for solutions of the form $$x^{\alpha}\ln(x)$$
Comment: is the first summand $$x^2\ln(x)^2y''(x)$$?
Comment: the 'ln' is squared, not x, and about **y**, yes, it's linear
Comment: @Dr.SonnhardGraubner  Yes, It is. How did you get that particular solution?
Comment: @Dr.SonnhardGraubner   Thanks
Answer: $$x^2\ln^2(x)y''(x)-2x\ln(x)(\ln(x)+1)y'(x)+y(x)(2\ln^2(x)+3\ln(x)+2)=0\Longleftrightarrow$$

Let $y(x)=xv(x)$, which gives $y'(x)=v(x)+xv'(x)$ and $y''(x)=xv''(x)+2v'(x)$:

$$x^3\ln^2(x)v''(x)-2x^2\ln(x)v'(x)+x(\ln(x)+2)v(x)=0\Longleftrightarrow$$

Let $v(x)=u(x)\ln(x)$, which gives $v'(x)=\frac{u(x)}{x}+\ln(x)u'(x)$ and
$v''(x)=-\frac{u(x)}{x^2}+\ln(x)u''(x)+\frac{2u'(x)}{x}$:

$$x^3\ln^3(x)u''(x)=0\Longleftrightarrow$$
$$u''(x)=0\Longleftrightarrow$$
$$\int u''(x)\space\text{d}x=\int 0\space\text{d}x\Longleftrightarrow$$
$$u'(x)=\text{C}_1\Longleftrightarrow$$
$$\int u'(x)\space\text{d}x=\int\text{C}_1\space\text{d}x\Longleftrightarrow$$
$$u(x)=\text{C}_1x+\text{C}_2\Longleftrightarrow$$
$$\frac{v(x)}{\ln(x)}=\text{C}_1x+\text{C}_2\Longleftrightarrow$$
$$v(x)=\ln(x)\left(\text{C}_1x+\text{C}_2\right)\Longleftrightarrow$$
$$\frac{y(x)}{x}=\ln(x)\left(\text{C}_1x+\text{C}_2\right)\Longleftrightarrow$$
$$y(x)=x\ln(x)\left(\text{C}_1x+\text{C}_2\right)$$
Where $\text{C}_1\space\space\text{and}\space\text{C}_2$ are arbitrary constants.
Comment: I'm not familiar with this method. How did you choose the substitutions? $y=xV$ and $V=lnxU$
Comment: @Desperado are you new to differential-equations?
Comment: I know how to solve them. As far as theory goes, yes, I'm 'new'.
Comment: @Desperado I've choose my substitutions out of experience, you've train your skills in this subject to (quicky) find the right substitutions
Comment: @Desperado Theory is the last thing that makes ODEs hard to solve :) the method of "careful staring at equation and trying substitutions" -- yep, that's hard. And to some extent this is not what ODEs are about...
Comment: @Evgeny I totally agree!


Get values of IDENTITY values when inserting multiple rows into a table having instead of trigger

Question: I'm inserting several rows into a table A which has an instead of insert trigger and an identity column.
Then I need to insert so many rows in a table B where each row hold a reference to the rows inserted in A.
The problem is, I can't use the output clause on A since, the identity will not be set (due to the trigger).
I know for one row I could use @@identity as long as the insertion of rows in A is the last insertion statement inside the trigger, but here I'm talking about multiple rows.
How can I achieve this?
Comment: Friend had a similar problem, [I blogged about it here](http://www.sqlperformance.com/2014/01/t-sql-queries/ident-current).
Comment: are you inserting in table A and table B in same proc ?i think you hv to use one temp table
Comment: I would suggest to create those Identities appropriately before hand and use those to insert in to the tableA and TableB.
Comment: this is very good question .It can be dome without temp table
i)Create View on table A and table B
ii)Create instead of trigger on view.
iii)here after insert into view passing all the value
iv)inside trigger write query to insert in TableA using output
v)Next statement inside trigger insert into TableB
Try and let us know.
Answer: I used code like this ( You CAN use table variable in OUTPUT clause )
declare @T table (requestID int);
INSERT <tableA> (<fields>)
       OUTPUT inserted.RequestID into @T
VALUES( <fieldValues1> ),( <fieldValues2> ) ;
Insert <tableB> (ID) select RequestID from @T;


Python: Import directory from a file inside that directory

Question: I'm sorry if the title is confusing since English is not my first language. What I have trouble is running a python script that calls import of its own directory. The folder structure is like this:
MyProject
    |--Utils
          |-- util
          |     |-- __init__.py
          |     |-- run.py
          |-- __init__.py
          |-- test.py

And the code of test.py is as following
import Utils.util

if __name__ == '__main__':
   # Do something

When running test.py, I get this error
ModuleNotFoundError: No module named 'Utils'

Is there anyway to call import that's suitable for this folder structure? If it's possible, someone can please help me naming this problem for better searches?
I have tried create a new script in the root folder which runs normally. However, what if I want to store testing code like test.py in modular folders, the import command is not running
Answer: Your project structure is not formatted correctly,
but I think this should work in your case:
from .Utils import utils

Answer: The error "ModuleNotFoundError: No module named 'Utils'" occurs because Python doesn't automatically search for modules within subdirectories unless they are treated as packages.
from .util import

Comment: Thank you for your inputs very much. It have helped me finding out that the folder is structured for exporting pip packages, from this clue I found how to directly run the setup and run the script without calling pip install


Player of the year awards

Question: Has any player won both the Naismith player of the year and defensive player of the year in the same season before 2021-22?
Answer: The answer is no, but it's not a very interesting one: the Naismith Defensive Player of the Year awards have only been given out since 2018.  See the awards page for the list of players who won; Aliyah Boston from South Carolina is the first men's or women's player to win both awards.

Player of the year awards


Python : How to remove rows which has nan values for dict inside list

Question: Have a dict in list with values:
a:
[{'name': 'toom D',
  'status_ref': True,
  'date_status_ref': Timestamp('2018-12-17 09:29:58.864000'),
  'expiry': None,
  'renew': nan},
 {'name': 'russ arnold',
  'status_ref': True,
  'date_status_ref': Timestamp('2018-12-17 09:29:58.864000'),
  'expiry': None,
  'renew': nan},
 {'name': 'cart wright',
  'status_ref': True,
  'date_status_ref': Timestamp('2018-12-17 09:29:58.864000'),
  'expiry': 'no',
  'renew': 'yes'}]

How to remove whole rows for records having nan , None , NaN values in  list(dict)
expected_output:
b:
[{'name': 'toom D',
'status_ref': True,
'date_status_ref': Timestamp('2018-12-17 09:29:58.864000')
},
{'name': 'russ arnold',
'status_ref': True,
'date_status_ref': Timestamp('2018-12-17 09:29:58.864000')
},
{'name': 'cart wright',
'status_ref': True,
'date_status_ref': Timestamp('2018-12-17 09:29:58.864000'),
'expiry': 'no',
'renew': 'yes'}]

Comment: NaN isn't a thing in Python.
Comment: @KenKinder I'm guessing there's a `from math import nan` omitted.
Comment: @MarioIshac, oooh, that could be.
Answer: Assuming nan is math.nan, you can do this:
for sub_a in a:
    for key, val in sub_a.copy().items():
        try:
            if val is None or math.isnan(val):
                del sub_a[key]
        except TypeError:
            continue

The above will mutate the original a. If you want a separate dict b as the output, you can do b = a.copy() and replace a with b in the outer for.
The reason I wrapped math.isnan in a try / except is because not all values in your dicts are real numbers, some are strings. If the TypeError is thrown, we know that the value couldn't possibly be nan.
The resulting dict is:
[{'name': 'toom D',
  'status_ref': True,
  'date_status_ref': Timestamp('2018-12-17 09:29:58.864000')},
 {'name': 'russ arnold',
  'status_ref': True,
  'date_status_ref': Timestamp('2018-12-17 09:29:58.864000')},
 {'name': 'cart wright',
  'status_ref': True,
  'date_status_ref': Timestamp('2018-12-17 09:29:58.864000'),
  'expiry': 'no',
  'renew': 'yes'}]

Answer: You can iterate through key/values of your dicts and filter them. like this:
a = [{'name': 'toom D',
    'status_ref': True,
    'date_status_ref': Timestamp('2018-12-17 09:29:58.864000'),
    'expiry': None,
    'renew': nan},
    {'name': 'russ arnold',
    'status_ref': True,
    'date_status_ref': Timestamp('2018-12-17 09:29:58.864000'),
    'expiry': None,
    'renew': nan},
    {'name': 'cart wright',
    'status_ref': True,
    'date_status_ref': Timestamp('2018-12-17 09:29:58.864000'),
    'expiry': 'no',
    'renew': 'yes'}]

def filter_dict(d):
    new_dict = dict()
    for (key, value) in d.items():
        if not (value is None or np.isnan(value)):
            new_dict[key] = value
    return new_dict

b = [filter_dict(d) for d in a]

Answer: Not the best solution but you can try.
a = [{'name': 'toom D',
  'status_ref': True,
  'date_status_ref': 'a',
  'expiry': None,
  'renew': nan},
 {'name': 'russ arnold',
  'status_ref': True,
  'date_status_ref': 'b',
  'expiry': None,
  'renew': nan},
 {'name': 'cart wright',
  'status_ref': True,
  'date_status_ref': 'c',
  'expiry': 'no',
  'renew': 'yes'}]

for d in a:
    for k,v in d.copy().items():
        if (str(v) in ['None', 'NaN', 'nan']):
            d.pop(k)

a:
[{'name': 'toom D', 'status_ref': True, 'date_status_ref': 'a'},
 {'name': 'russ arnold', 'status_ref': True, 'date_status_ref': 'b'},
 {'name': 'cart wright',
  'status_ref': True,
  'date_status_ref': 'c',
  'expiry': 'no',
  'renew': 'yes'}]


accessing ERRORLEVEL from bash script

Question: I have an application that only works properly when called from a windows command prompt. Something to do with the input/output streams.
So I can call it from a bash script by passing it as an argument to cmd.
cmd /c "badapp"
This works fine - but occasionally badapp fails with network problems - and I get no feedback. Is there anyway to check the ERRORLEVEl from the bash script - or see the output from badapp on the terminal running the bash script?
Answer: Yes, $? is the variable that contains the error level.
Try echo $? for example.
An example from Cygwin bash (I'm guessing you are using Cygwin because you are using the Windows cmd in your example.)
susam@nifty /cygdrive/c/Documents and Settings/susam/Desktop
$ cmd /c "badapp"
'badapp' is not recognized as an internal or external command,
operable program or batch file.

susam@nifty/cygdrive/c/Documents and Settings/susam/Desktop
$ if [ $? -eq 0 ]
> then
>   echo "good"
> else
>   echo "bad"
> fi
bad

Comment: Yes! Why don't you simply try it out and confirm for yourself?
Comment: sorry I should have mentioned I was using cygwin. Are you sure this would convert a Windows ERRORLEVEL into the bash equivalent $?
Comment: thanks this does seem to work in general. The problem seems to be with "badapp" -when it fails with network problems it doesn't consistently set the errorlevel

accessing ERRORLEVEL from bash script


How to embed videos using the video module?

Question: I installed the video module and activated video and video ui modules using Drupal 7:
https://www.drupal.org/project/video
I created a content type with a video field. Now I can upload videos with this content type.
But I am not able to embed a youtube video. I can not find any settings or any embed widget as shown here.
I want to upload videos and I want to embed videos (youtube, vimeo..).
But I can not find any way to embed a video unsig this video module.
Do I have to install further modules?
On the module page you can read:

Video module allows you to embedded videos from YouTube, Vimeo,
  Facebook, Vine etc (Drupal 8 only) and upload videos and play using
  HTML5 video player.

I can not find out how to embed a video using this module. Can you help?
I do not want to use another module, I want to find out how to embed videos using THIS module. Be in mind of this when you write your answer. Thank you.
Comment: Are you required to use the Video module.  Or, are you just looking for a valid way to embed videos into some content?
Comment: I want to find out, why the desciption on the module page is wrong: "Video module allows you to embedded videos from YouTube, Vimeo, Facebook, Vine etc (Drupal 8 only) and upload videos and play using HTML5 video player."
Comment: Are you at all interested in an alternative way of embedding videos without  using a module?
Comment: Not here. You can tell me per mail.
Comment: I think you did not understand the question: I do NOT want to embed a video within the text/body of a node!!!! Instead I want to go to Youtube site and click there under the video on share. There I can copy the embed code of this Youtube video or I can copy the URL of the youtube video. This URL or embed code I want to include into a Drupal field. This is what the module mentioned above does, but not for Drupal 7???
Answer: If you install the WYSIWYG module, you can enable a button for embedding videos that have been uploaded using the Video module, and then you can use that button to embed videos into content.
Comment: Is this true for Drupal 7?
Comment: Yes. You marked the question Drupal 7.
Comment: I did not find this button in CK Editor. And how is the video been uploaded? In a node field?
Comment: You have to upload the video into a separate node before it can be embedded. For the button, go to Admin -> Config -> Content Authoring -> WYSIWYG Profiles, then click 'edit' for the profile you want, expand 'buttons', and make sure the 'video' button is checked.
Comment: I think you did not understand the question: I do NOT want to embed a video within the text/body of a node!!!! Instead I want to go to Youtube site and click there under the video on share. There I can copy the embed code of this Youtube video or I can copy the URL of the youtube video. This URL or embed code I want to include into a Drupal field. This is what the module mentioned above does, but not for Drupal 7???
Comment: Sorry, I can't help with that.
Answer: That's not what the Video module is for. It's for handling uploaded videos.
To get a video embed field use Video Embed Field.

Video Embed field creates a simple field type that allows you to embed videos from YouTube and Vimeo and show their thumbnail previews simply by entering the video's url.


javascript throwing exception in internet explorer

Question: below is my code,when i run this on internet explorer it throws exception of javascript on code which is highlighted with stars.
request you to please help me.
JavaScript critical error at line 200, column 5 in http://localhost:50317/js/functions.js\n\nSCRIPT1028: Expected identifier, string or number
<code>$(window).load(function() {
    $('.slider1').flexslider({
        animation: "slide",
        start: function (slider) {
            $('body').removeClass('loading');
        },
    **})**;

  $('.slider2').flexslider({
    animation: "slide",
    slideshow: false,
    animationLoop: false
  });
});

});
</code>
Comment: You have put stars line 7
Answer: You have a comma that shouldn't be there, and the final line is duplicated. This should be valid:
<code>$(window).load(function() {
    $('.slider1').flexslider({
        animation: "slide",
        start: function (slider) {
            $('body').removeClass('loading');
        } /* no comma here */
    });

    $('.slider2').flexslider({
        animation: "slide",
        slideshow: false,
        animationLoop: false
    });
});
</code>


Store values that are only numerical or alphabetical in Pandas dataframe column?

Question: Imagine I have a column called courses, where some are only numeric, some are alphabetical, some are both. These correspond to courses within a specific department. Imagine all values in courses are strings and there could be null values. I want to a) store the courses the are only numeric b) store the courses that are only alphabetical or c) store the courses that end with a number (but we don't care whether they otherwise contain numbers or letters). How could I do this leveraging Pandas capabilties?
Imagine courses looks something like this but much longer.
Courses
------------------------
181
71
CS 143
Machine Learning
Programming Languages 79
115
157 Neural Networks

So a) would contain 181, 71, 115 b) would contain Machine Learning and c) would contain Programming Languages 79, CS 143.
I could imagine doing this the longer way using non pandas approaches, but I imagine pandas can help significantly with this. For example, for the last task, I could do something along the lines of the following but am wondering if there is nicer way:
c = []
for course in courses:
    course = course.strip()
    if course:
        length = len(course) - 1
        if (course[length]).isdigit():
            c.append(course)

Answer: Use contains for boolean mask:
m1 = df['Courses'].str.contains('^\d+$')
m2 = df['Courses'].str.contains('\d')
m3 = df['Courses'].str.contains('^\D.*\d$')

df1 = df[m1]
print (df1)
  Courses
0     181
1      71
5     115

df2 = df[~m2]
print (df2)
            Courses
3  Machine Learning

df3 = df[m3]
print (df3)
                    Courses
2                    CS 143
4  Programming Languages 79

If you need a single dataframe as the output, you can use a single regex:
df[df.Courses.str.contains(r'^(?:\d+|[a-zA-Z\s]+|.*\d)$')]

                    Courses
0                       181
1                        71
2                    CS 143
3          Machine Learning
4  Programming Languages 79
5                       115


Problem with dynamics while playing

Question: I am a musician and I play keyboard but I have a problem that worries me. Whenever I play I tend to strike the bass key(s) very hard and that note(s) is very clearly heard and obscures the right hand. I am trying to learn to strike it softer but whenever I play it is difficult to control the amount of force. The same thing often happens with my 5th finger in my right hand. Often when I hit a chord, the 5th finger strikes the note with more force than I need. I can't always control that either.
Are there any exercises to fix that?
The key dynamics on my synth are okay, because whenever I play a grand, a piano or a digital piano the same thing occurs.
Edit: I am a right-handed person. I sometimes play the guitar and I used to play it a lot before I started playing the piano. I mostly play art rock, prog rock, hard rock, blues/jazz rock but lately have started playing pieces like Jon Lord has (including his music, Before I forget and Burntwood).
Comment: May I ask how long you have been playing?
Comment: My piano teacher wouldn't allow me to work on classical pieces that required refined "voicing" (different strengths for different notes in a chord) saying I needed to develop more first. Some things require neuronal connections and associated senses that take time to grow. In any event, try to hear it in your head the way you want it, and imagine playing it the way you want it, prior to playing it. Go as slow as needed to actually accomplish this. It is probably a stretch but doing this for a while every day should help.
Comment: "The key dynamics on my synth are okay, because whenever I play a grand, a piano or a digital piano the same thing occurs.": I'd (mildly) disagree: that doesn't have to be the case. Your keyboard may have worse dynamics (likely) than a pinao, but the symptom can still show. If you really want to get a good touch, get a good (digital) piano, and probably a teacher as well (expensive, yes, but as a musician, worth it).
Comment: @MPW 9 years. I started to play in September 2008. That's when I bought my first synth - Yamaha DGX-520. I mostly play art rock and prog rock, sometimes hard rock and mostly use a compressor and a limiter. Lately, I started playing Jon Lord's pieces like Before I forget and Burntwood and try to compose like he does and that's where I noticed my problem.
Comment: @Evert I attended a piano class one day and the teacher there told me that my playong is not natural and gave me a few tips none if which actually helped. I was studying guitar before and my keft gand got acustomed to pressing the string with force, I am not sure if that could be the reason since I play guitar rarely.
Comment: Practice playing very soft legato melodies (no chords) with left hand will probably help. Even just scales, or walking (c e d f e g f a etc), for 30 min daily.
Comment: @MPW I play scales a lot and often the loudest notes are where my left thumb hits the note. I'll try the pattern you wrote.
Comment: I think soft legato is important. It forces you to play lightly and smoothly. And it has to continue fora long time (weeks? months?). Nothing will happen overnight, you're having to unlearn a bad habit so hang in there
Comment: @MPW Alright, I'll be trying that
Comment: "told me that my playong is not natural": did you learn piano by yourself? Cause not having feedback may cause such issues later on, and then they are harder to unlearn. That won't help your current problem, but thinking what may (have) cause(d) it. And if so, it may take a while of dedicated practice to get rid of it
Comment: You mention 5th finger in your question, but thumb in the comments (former for chords, latter in scales though). Is that correct? Pinky uneveness I can understand; thumb would be an overall indication of uneven scales.
Comment: @Evert Yes, I learn to play all by myself. I didn't have a teacher only videos from YouTube and books.
Comment: @Evert Thumb in my left hand mostly, however all the fingers in my left hand are troubling me.
Answer: Over the internet, I imagine I'd make the following comment if you were to play in front of me: "Don't hammer the keys!"
A pianist once shared this advice in a master class: "treat your piano the same way you'd treat your boy/girlfriend."
You'd be amazed how little force it takes to produce a sound on a piano. It is almost like, very softly touching the hand of your partner, or a new born baby. Yup I am not exaggerating - it is exactly what you have to practice for.
You said you

learn to strike it softer

That's the problem. You don't strike the keys. You just relax and let the weight of the arm sink in.
It is more difficult to keep the tone soft while playing fast. Practice slowly first. Then gradually, try to build up speed without raising volume.
Answer: This is a normal part of learning to play the piano. My piano teacher wrote "balance" in most of my dictation books as a child - which actually means imbalance because you want the hand with the melody (usually the right hand) to come out stronger.
Try to lighten up the touch of your left hand and develop the finger muscles in your right hand with muscle training exercises, particularly your 4th and 5th finger which often play the melody - especially when you are playing chords in the right hand as well. Take a look at this question for some examples.
Also related: Playing one hand loudly and the other quietly
Comment: @SovereignSun "in thus case my left hand can do whatever it wants which is really annoying." It's much worse than "really annoying". If you keep practicing the *wrong* way to play, how do you expect to learn the *right* way? Either learn to live with the fact that you are never going to be a very good keyboard player, or get your head down and work at it. There isn't an "option 3"!
Comment: Good thing you aren't trying to learn to play a drum kit. They have to think about both hands and both feet, all at the same time.
Comment: The problem is with chords mostly, because when I play the melody in my right hand I focus on the keys and the force, in thus case my left hand can do whatever it wants which is really annoying.
Comment: @alephzero I am learning, I'm stating what my problem seems to be. When I am thinking about my left hand I can control it, but if I think of my right hand I cannot control my left hand.
Comment: @PhilFreihofner Yeh, drums aren't for me.
Answer: This is one of the (many) skills that playing scales helps with. Try first playing them with separate hands, and recording it, so you can hear any differences - better to play each hand in the same octave sometimes, too.
Sounds like you have a couple of dynamics - f and ff ! Again with scales, try playing each hand pp, ff, and the same together, then split into ff r.h. and pp l.h. Practise these until there is a marked difference. On electronic keyboards, turn the volume up to play quietly, and down to play loudly. Think about that!!
When things have improved, try to get moving dynamics - start pp and crescendo to ff after two octaves of scales, separate and together. Stick with scales until the levels are controllable. Playing pieces with l.h. block chords won't help at the moment.
Comment: That's what compressors do. Don't use them. Just a thought. When you play a block chord, it should be your *hand* playing, not your *fingers*. As in it is a whole hand movement rather than three individual fingers.
Comment: I tried to record midi while improvising and I have mist keys pkay 70-80 but often the bass hand plays 110-127 and the sometimes some notes in my right hand are below 50 in chords, that means some finger doesn't play at the same velocity. If I use a compressor the peaks are minimised.
Comment: Scales: definitely. But very controlled (slow at first), to obtain an even sound, and preferably with a teacher for feedback. But keep in mind that scales usually involve the fifth fingers (the OP's problem finger) very little!
Answer: This is definitely something that happens for most players.  Not only is it fairly instinctive, since most everyone is right or left handed and has a stronger hand/arm because of it, but it's also something that can be hard to break out of if you've been playing for a bit, as it is a habit that has been formed.  I would recommend trying to exaggerate what you're trying to change.  Try playing something relatively simple for both hands and play the left hand as quiet as you can and the right hand fairly loud.  This should help your brain break the habit a little and once you feel more comfortable doing that, reduce the exaggeration, bringing the two hands to a more similar volume.  As this gets easier for you, try making the parts for either hand more complicated, starting off exaggerated and moving toward a balance.
For the one finger, I don't have quite as good advice but I'd recommend focusing on the one hand, as opposed to playing with both while trying to fix the issue.  You might want to try playing with that finger and just one other at a time and focus on getting the same volume out of them.  You're probably just having that finger closer to the keys in general, so when they all come down, that one hits first and hardest, so you will probably notice that as you work through using different fingers.  You can try holding that finger further up than the others so that it hits at the same time, or you could try extending that finger further back on the key you are hitting.  The further up the key you are, the harder it is to get the note to sound, due to basic leverage, so it should naturally be quieter.  The only real issue with that approach is that you don't always have the option to do that since not all chord voicings allow for you to choose where on the key you hit.
On the whole, you're needing to get your brain to break a habit, so you have to actively seek the means of doing so through mindful practice.  You're probably currently doing things without actively thinking about them, so by actively thinking about it and using the right approach for you, you can retrain your brain and then won't have to think about it once you've broken the habit.
Comment: Definitely a very common problem. Some call it the human condition, that we are unbalanced as a result of the way we use our bodies. A right handed person will be stronger and more precise with that hand and the left hand tends to require a lot more work. So I think you really just need to focus on that hand and developing more precision. You can try playing the right hand parts with your left hand as a way of developing dexterity and precision.
Comment: I am trying different exercises, such as playing a chord stressing different notes of the chord every time you take it. Like in Cmaj first the C is stressed, then the E, then the G. And so on. With 4 and five note chords too. So far it's quite difficult. The left hand is my biggest problem since I can never control my dynamics, each time I try to play bass patterns unneccesary notes become stressed and I have to watch that.
Comment: Yeah, you probably also want to practice just playing with your left hand to get it to respond a little better.  Trying running scales more with your left hand than right so that you can really get control over it.
Comment: Is it a common problem or is it just me?

Problem with dynamics while playing


Nginx server works only locally

Question: I have set up a VPS on Vultr running Debian 10, and I've just installed nginx.
If my understanding is correct, at this stage, I should be able to see something like

when I visit my website. Indeed, when I run curl -i mydomain.com from the ssh terminal (i.e., from email@example.com), I see the html for the above webpage in the terminal, but when I run it from another terminal (or just my browser), I get no response.
I have read other answers to similar questions on this site which point to Firewall blocking port 80, but there is no Firewall set up from the Vultr side. Also, these are the records I currently have on my DNS:

I'm not sure what I'm doing wrong. I appreciate any assistance with this.
Answer: On your server, install a firewall, then allow traffic to the Nginx server.
sudo apt install ufw -y && sudo systemctl enable ufw && sudo ufw allow 'Nginx Full'

UFW is the package "uncomplicated firewall". By installing the firewall and granting access to 'Nginx Full', it should open access to your server, whereas right now, it's probably rejecting everything. We'll know after you try it and reply back.
Comment: Can you explain how/why this would help? Or link to an authoritative reference that suggests it? … … … … … … … … … … … … … … … … … Please do not respond in comments; [edit] your answer to make it clearer and more complete.
Comment: I will try this and let you know what happens.
Comment: I just visited the IP. You're good to go. I see the Nginx page.

Nginx server works only locally


FAPI Fivestar settings in custom form

Question: I have a multistep form with mforms in forth step my form have fivestar field from a review node content type.
All fivestar field display option are set to basic, but fields are displaying differently.
I tried to change the display widget in my module, with no luck. If i try to change the widget it returns to defaults.
Any suggestion are welcome. thx
function _reviewform_step4(&$form_state, &$next_step, $params) {

    $form = array();

    //attaching existing content type fields
    $review = new stdClass();
    $review->type = 'review'; //content type

    field_attach_form('node', $review, $form, $form_state);

    foreach ($form_state['field'] as $field) {
        if ($field['und']['field']['type'] == 'fivestar') {
            $field_name = $field['und']['field']['field_name'];
            // not working
            $form[$field_name]['und'][0]['rating']['#settings']['widget']['name'] = 'flames';
            $form[$field_name]['und'][0]['rating']['#settings']['widget']['css'] =     'sites/all/modules/fivestar/widgets/flames/flames.css';
            // not working to
            $form[$field_name]['und'][0]['rating']['#widget']['name'] = 'flames';
            $form[$field_name]['und'][0]['rating']['#widget']['css'] = 'sites/all/modules/fivestar/widgets/flames/flames.css';
        }
    }

Answer: I am not familiar with mforms, but I see a few potential issues:
1)  your form doesn't have a standard signature ($form, &$form_state, ...).  I obviously can't see how you're calling it, but this is not a typical thing to do.
2)  when getting the path of the css, you should be using drupal_get_path
https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#attached
3)  widget is not a property of #settings
Comment: 1) mforms use this signature
2) Your right, but this is a debug/demo code
3) thx

Thanks for your efforts.
Answer: Finally i used another concept. Instead of attaching all field with field_attach_form() i used
field_info_field(), field_info_instance() and  field_default_form() to attache field one by one. Here i could override the instance widget settings.
 $rel_field = field_info_field('field_reliability');
 $rel_instance = field_info_instance('node', 'field_reliability', 'review');

 $rel_instance['widget']['settings']['widget']['fivestar_widget'] = drupal_get_path('module', 'fivestar') . 'widgets/flames/flames.css';

 $my_reliability = field_default_form('node', $review, $rel_field, $rel_instance, LANGUAGE_NONE, array(), $form, $form_state);
 $form['field_reliability'] = $my_reliability;

FAPI Fivestar settings in custom form


socket.io vs pusher, which one is better to use with laravel

Question: i am just new into this concepts about sockets and i am so confused.Firstly i found that i can use pusher for realtime messages but it limits concurrent connections 100 and number of  messages to send..then what about socket.io, does it have some kind of limitations? From what i have researched i assume it has no such limitations as pusher but i want to be sure.can anyone explain me how socket.io can do this, i mean if socket.io have no such limitations why would pusher be even used with payment plans?
Comment: Laravel comes with pusher examples, so it is easiest to use... Build your test scenarios with pusher and than try different socket vendors like socket.io...
Comment: thanks yes now i am moving to socket.io but just wanted to know if it had any downsides like no. of concurrent connections...because i couldnot find those info anywhere
Comment: Remember that, there are also, other nice engines, like ably.io for example... Have fun coding...
Answer: You do not get the same limitations with socket.io however it can be a little daunting to set it up, I found this introduction on laracasts really useful when I was looking into it - https://laracasts.com/series/real-time-laravel-with-socket-io/episodes/1


Splitting ethernet to multiple (3+) devices (phones, PCs)

Question: I'm currently troubleshooting an environment where there is a lot of network latency issues, all sporadic and intermittent across workstations. The network uses a mix of calls from on-site dialer and traditional RJ11 phones working off of Vonage gateways. Lots of reports of call quality issues, bridging calls, one-way audio, etc.
I made some tweaks on their firewall which seemed to have helped somewhat, but looking at their cabling, I'm seeing most of the devices share single ethernet cables over split pairs (and not using splitters, just the individual pairs separated and spliced into multiple jacks or plugs). Some of these have a single cable split to x4 RJ11 phones or two pairs to a PC and the other two pairs split to two additional phones. Moreover, the cable sheath is cut back exposing more than 5 inches of unprotected pairs before they hit the jack.
I know bandwidth is diced up, but I'm led to believe this kind of mix of VOIP, POTs, and internet traffic all running over the same cable would lead to issues with crosstalk, latency (when all connections are in use), etc.
Question: does this non-standard approach to splitting ethernet cables have any affect on network communications quality? Would it cause symptom such as those I referenced?
Comment: The whole point of cabling standards is to ensure signal quality at the rated speeds.  Given your described state of that cable plant, I'd walk away from the job until the cabling was corrected.
Comment: I think it's safe to say that yes, that kind of cabling is highly likely to be the source of the issue.
Comment: This almost reads like the result of a do it yourself cabling job.
Comment: You kind of answered your own question. The cabling certainly isn't helping.
Comment: I get the cabling is jacked up, I just wanted to confirm as I don't recall ever running into something like this in a business environment. Figured I'd at least get a second opinion.
Answer: Toner is working sporadically and I'm guessing its because of crosstalk between wire pairs split between two jacks. I ran wire tests and had to replace about 6 jacks. Witnessed bridged audio between to phones which shared a common ethernet cable. Additionally, all the wire trunks were laying directly on top of lighting ballasts. Also found ethernet split and re-spliced with scotch tape! Pretty sure this violates all standards for cabling. Thanks for the assist!


Why don't treadmills offer a manual setting of longer than 60 minutes?

Question: I know I can set a treadmill at the quick start setting and just run. But, why can't I set a program or the manual setting (which calculates calories burned) to longer than 60 minutes?
Comment: Wouldn't this be treadmill-specific?..
Comment: This isn't a sports related question.
Comment: @Marcus I believe it would be. If I was asking about shoulder pads, that would be on topic. A treadmill is a piece of equipment highly related to the sport of running. However, I do agree with Dmitry that this question is too localized. It would only apply to specific brands of treadmills.
Comment: On all the treadmills you can't do a workout longer than 30 minutes. I don't think it's a brand related question.
Comment: @glowcoder you are right, I must have been in a bad mood :)
Answer: The treadmill has a max time limit. Usually it's 60 minutes.
Even if you hit quick start at 60 minutes it will stop the workout.
Read how to change that limit here.


adding disk storage for windows server 2012

Question: Is it possible to add external storage (or any other solution to increase disk storage) to windows server 2012, which is already running on PC. I am running out of space, and I would like the easiest solution so I would be able to store new data without deleting anything I collected yet.
Answer: Yes, you can add external storage just like any other Windows machine.  I would recommend you make sure to format the storage as NTFS and I would only put static data on it; no database or program files.
Comment: thanks man. but I would need to have database there, because I am collecting some data on server. so what do you suggest, how to extend storage which is almost full?
Comment: Databases tend to be very write-intensive, and a USB/eSATA/whatever bus isn't going to be able to handle this as well as an on-board SATA/SAS bus.  If you run a database there, performance is going to be be an issue.  The best thing you can do is back up everything, add more internal storage, and rebuild and restore your data.  If that is not an option, the only other thing I can suggest is to move any non-database files you can onto external storage to make room for the database on internal storage.


Equation of motion including gear ratio

Question: Two-mass rotational system has the following form and is represented in following structural diagram.

where $\tau_e$, $\omega_1$ and $J_m$ - motor torque, angular velocity and moment of inertia
$\tau_s$, $\tau_s$, $\omega_2$ and $J_d$ - shaft torque, load torque, angular velocity and load moment of inertia;
$K_{md}$ - shaft stiffness
Problem: how to include a gear ratio $N=\frac{\omega_1}{\omega_2}$ in equation of motion and in in a block diagram respectively?
$L=V-P=J_m \frac{\omega_1^2}{2}+J_d \frac{\omega_2^2}{2}-\frac{K_{md}(\phi_1-\phi_2)^2}{2}$
$V$ - kinetic, and $P$ - potential energy
Here is the Lagrangian for the entire system. And I don't understand how to insert the gear ratio here?
Comment: Where are the gears located, in-between the shaft and the motor? And the mass of the gears are lumped together with the other masses?
Comment: @KwinvanderVeen All questions - yes!
Comment: What progress have you made up to this point?  Have you reviewed any possibly-similar questions in the physics.SE community?  Is there a book or similar work that has available theorems or statistical information on this topic that you can share?
Comment: @abiessu

1. I wrote Lagrangian for the entire system.
2. Yes, there is no information about it.
3. Yes, there is no information about it. And what does the STATISTICAL information have to do with it?
Comment: @KwinvanderVeen see my edit
Comment: As part of your effort please set the action $V-P$ into Mathjax.
Comment: Statistical information is any available amount of trials having similar initial conditions to the described system.
Comment: @abiessu I don't think it helps, I am trying to develop a mathematical model
Answer: Directly plug in constant ratio between gear rotation angles which is   the same ratio between  their time derivative angular velocities. If
$$N=\dfrac{{\phi_1}}{{\phi_2}}=\dfrac{\dot{\phi_1}}{\dot{\phi_2}}=\dfrac{\omega_1}{\omega_2}$$
then the action is:
$$L=V-P=\frac{\omega_2^2}{2} \left(J_m N^2 +J_d \right)-\frac{K_{md}}{2}\;(N-1)^2\;\phi_2^2.$$
Comment: With same speeds there is no relative twist angle and so *no torsional energy*. A physical property cannot vanish into thin air.
Comment: Please read Hamilton principle $ L= T-V $ etc. It is  energy conservation in different terms.
Comment: I have a question right away. If $N = 1$, then the term with the shaft stiffness is lost? This is very strange, how to explain it?
Comment: Yes, of course, I'm sorry. Could you please supplement the answer with substitutions, i.e. to show more clearly how such a Lagrangian came about?
Comment: Do you know how to derive a simple non-linear pendulum starting with $V-P$ difference of PE,KE energies? If you do such simple examples I am sure you can help yourself. I had down voted and cancelled it.
Comment: Just such a thing confuses me. If we make such substitutions in the Lagrangian, don't we get two Lagrangians? https://ibb.co/820MQKY, that strange
Comment: I need a more serious clue. I understand the meaning, it just doesn't fit in my head how to correct the Lagrangian. Visualization is much more useful for me now than ignorance.
Comment: https://ibb.co/JRBmLgF
Comment: Please formulate non-linear pendulum or at least the linear pendulum at first. Please  postpone the servo block diagram for the time being.
Comment: Linear pendulum https://ibb.co/w7PtSPf

what next ?
Comment: Maybe I'm not expressing my problem clearly enough. Lagrangian takes into account the energies stored in the moving elements of the system. Generalized coordinates are taken that do not "interact" with each other (formally). This relationship in the mechanism is taken into account through the gear ratio. How to include it in the Lagrangian in order to obtain the equation of motion and, based on it, obtain a block diagram for modeling, for example, in simulink.
Comment: https://d2vlcm61l7u1fs.cloudfront.net/media%2Fe3d%2Fe3d8b55d-f905-41d0-b7fa-d53be32fb715%2FphphL0I0P.png

here these things appear, but it is not clear to me how they were obtained ???
Comment: https://math.stackexchange.com/questions/4185010/derive-the-equations-of-motion-including-gear-ratios
Comment: https://math.stackexchange.com/questions/4271830/equations-of-motion-with-gear-ratios-through-the-lagrangian-with-an-unknown-tran
Answer: I dont have enough reputation to comment or downvote the existing (accepted) answer.
Why I think the answer is different
<code>[motor]---)--[GB]---)--===shaft=====--)--[load]
          phi1    phi1'             phi2
</code>
In the presence of a flexible shaft there are 3 angular positions. See the ASCII diagram above. The important point to note is that the definition of N is not $\omega_1/\omega_2$. It is $\omega_1 / \omega_1'$, and $\omega_1' \neq \omega_2$ when the shaft is in twisted condition. The shaft can be in twisted condition at various times while the system is operating.
In fact the OP has asked

I have a question right away. If N=1, then the term with the shaft stiffness is lost? This is very strange, how to explain it?

So I am posting my answer to the duplicate question asked the OP at engineering.se.
My answer at engineering.se
Assuming that the gear box is on the left end of the shaft (i.e. no flexible shaft between motor and gearbox).

The angular velocity on the left end of the gear box is $\omega_1$.
The angular velocity of the shaft side of the gear box is assumed as $\omega_1' = \frac{\omega_1}{N}$.
The angular velocity on the right end of the shaft is $\omega_2$. So the torque on the shaft is $\pm K_m (\frac{\phi_1}{N} - \phi_2)$. (sign to be checked).
Because of the way I described the gearbox, $\omega_1' < \omega_1 $. so the torque on the shaft when acting on the motor through the gearbox is $\frac{1}{N}$. This can be seen in the below derivation.
Since I have assumed that shaft is directly connected to the load, the torque in the shaft is made available 1:1. This can also be seen in below derivation.

(Below derivation to be verified independently by OP)
$$
L = \frac{J_m \omega_1^2}{2}
+ \frac{J_d \omega_2^2}{2}
+ \frac{Km (\frac{1}{N} \phi_1 - \phi_2)^2}{2}
$$
$$
\frac{d}{dt} \frac{\partial L}{\partial \omega_1}
= \frac{d}{dt} J_m \omega_1
= J_m \frac{d \omega_1}{dt}
$$
$$
\frac{\partial L}{\partial \phi_1}
= \frac{K_m}{\color{red}{N}} (\frac{1}{N} \phi_1 - \phi_2)
$$
Similarly for the other body also (exercise left to you).
$$
\frac{\partial L}{\partial \phi_2}
= -K_m (\frac{1}{N} \phi_1 - \phi_2)
$$
I have not considered the input torque. It can be added to this result.
Comment: https://mathematica.stackexchange.com/questions/250286/equations-of-motion-for-two-mass-torsional-oscillator-with-the-gear-train/250291?noredirect=1#comment627297_250291
Comment: https://math.stackexchange.com/questions/4185010/derive-the-equations-of-motion-including-gear-ratios/4185511?noredirect=1#comment8677111_4185511
Comment: "I have not considered the input torque. It can be added to this result." Yes, that we may do very simple
Comment: You have expressed difficulty with EL formulation. That is where I tried helping you out.  The mechanics you did  appeared to me  quite ok.
Comment: https://math.stackexchange.com/questions/4271830/equations-of-motion-with-gear-ratios-through-the-lagrangian-with-an-unknown-tran

Equation of motion including gear ratio


Series Conversion, Jacobsthal Sequence

Question: I can't wrap my head around this exercise:
Show that
$$\sum_{i=0}^\infty \left(- \frac{1}{2}\right)^i = \frac{2}{3}$$
I started by calculating elements of the series:
$$k = 0 \rightarrow \frac{1}{1},\ k = 1 \rightarrow \frac{1}{2},\ k = 2 \rightarrow \frac{3}{4}, \rightarrow k = 3 \rightarrow \frac{5}{8},\ k = 4 \rightarrow \frac{11}{16}$$
and arrived at the conclusion that the formula of the partial sum is the following:
$$S_n = \frac{\text{Jacobsthal sequence}}{2^n} = \frac{a(n) = a(n - 1) + 2a(n - 2)\text{ with }a(0) = 0, a(1) = 1}{2^n} = \frac{\frac{2^n}{3}}{2^n} = \frac{1}{3} ?$$
The approximation used to describe the Jacobsthal sequence, namely to two to the n over 3, is not precise enough, thus I try to use induction to see if the partial sum holds, and then calculate the limit, but here is where I get stuck:
$$S_{n+1} = S_n + \left(-\frac{1}{2}\right)^n = \frac{a(n - 1) + 2a(n - 2)}{2^n} + \left(-\frac{1}{2}\right)^n =\ ...\ ?= \frac{a(n + 1)}{2^{n +1}}$$
any hints if this is on the right track and how can I manipulate the Jacobsthal series?
Thank you.
Comment: Are you familiar with geometric series?
Comment: https://en.wikipedia.org/wiki/Geometric_series
Answer: Hint:
Define $$S_n=\sum_{i=0}^n\left(-\frac{1}{2}\right)^i$$
Then compare $S_n$ and $-\frac{1}{2}S_n$ to find a simpler expression for $S_n$.
You should then find that:

$$\left(1+\frac{1}{2}\right)S_n=1-\left(-\frac{1}{2}\right)^{n+1}$$ What can you then say about $\lim_{n\rightarrow\infty} S_n$?
Answer: Here's another approach. We have:
$$ s_n = \sum_{i = 0}^{\infty} \left( - \frac{1}{2} \right)^i  $$
$$ = 1 - \frac{1}{2} + \frac{1}{4} - \frac{1}{8} + \frac{1}{16} - ... $$
Which we can restate as:
$$ s_n = \sum_{i = 0}^{\infty} \frac{1}{4^i} - \frac{1}{2} \sum_{i = 0}^{\infty} \frac{1}{4^i}  $$
$$ = \frac{1}{2} \sum_{i = 0}^{\infty} \frac{1}{4^i}$$
Computing the geometric series we get:
$$ s_n = \frac{1}{2} \frac{1}{1 - \frac{1}{4}} = \frac{2}{3}$$
Answer: $S_\infty ={a \over1-r} $
$\sum^\infty_{k=0} (-{1 \over 2} )^k = {1 \over 1+ {1\over 2}} = 1*{2\over3} = {2\over3}$

Series Conversion, Jacobsthal Sequence


ERROR: Plugin 'LoggerPlugin' not found, or is not a CDVPlugin. in iPhone 4s

Question: I am using:
Worklight V188.8.131.52
IOS 7.1
iPhone 4s
The application is running fine in iPhone5s but when installing the same app in the iPhone 4s I am getting the following error.
Could anyone let me know what exactly is causing the issue. As fas as I understand, it is saying "LoggerPlugin" not found. If it is so then how could I verify the presence for the same. If I remove it from the config.xml then I get the same error for different plugin. How do I resolve the issue?
ERROR: Plugin 'LoggerPlugin' not found, or is not a CDVPlugin. Check your plugin mapping in config.xml.
2014-08-06 19:09:08.804 xxxxx[350:60b] -[CDVCommandQueue executePending] [Line 158] FAILED pluginJSON = [
  "INVALID",
  "LoggerPlugin",
  "log",
  [
    "DEBUG",
    "",
    "added onPause event handler ",
    {
      "$arguments" : [
        "added onPause event handler "
      ],
      "$src" : "js"
    },
    1407332348664
  ]
]

config.xml
<?xml version="1.0" encoding="UTF-8"?>
<widget>
    <preference name="AllowInlineMediaPlayback" value="false" />
    <preference name="AutoHideSplashScreen" value="true" />
    <preference name="BackupWebStorage" value="cloud" />
    <preference name="DisallowOverscroll" value="false" />
    <preference name="EnableViewportScale" value="false" />
    <preference name="FadeSplashScreen" value="true" />
    <preference name="FadeSplashScreenDuration" value=".25" />
    <preference name="HideKeyboardFormAccessoryBar" value="false" />
    <preference name="KeyboardDisplayRequiresUserAction" value="true" />
    <preference name="KeyboardShrinksView" value="false" />
    <preference name="MediaPlaybackRequiresUserAction" value="false" />
    <preference name="ShowSplashScreenSpinner" value="false" />
    <preference name="SuppressesIncrementalRendering" value="false" />
    <preference name="TopActivityIndicator" value="gray" />
    <preference name="GapBetweenPages" value="0" />
    <preference name="PageLength" value="0" />
    <preference name="PaginationBreakingMode" value="page" />
    <preference name="PaginationMode" value="unpaginated" />
    <preference name="EnableLocation" value="false" />
    <preference name="UIControls" value='{"TabBarSettings": {"position": "bottom", "height": 49}, "ToolBarSettings": {"style": "Default"}}'/>

    <feature name="LocalStorage">
        <param name="ios-package" value="CDVLocalStorage" />
    </feature>
    <feature name="Battery">
        <param name="ios-package" value="CDVBattery" />
    </feature>
    <feature name="Camera">
        <param name="ios-package" value="CDVCamera" />
    </feature>
    <feature name="Console">
        <param name="ios-package" value="CDVLogger" />
    </feature>
    <feature name="Contacts">
        <param name="ios-package" value="CDVContacts" />
    </feature>
    <feature name="Device">
        <param name="ios-package" value="CDVDevice" />
    </feature>
    <feature name="Accelerometer">
        <param name="ios-package" value="CDVAccelerometer" />
    </feature>
    <feature name="Compass">
        <param name="ios-package" value="CDVCompass" />
    </feature>
    <feature name="Notification">
        <param name="ios-package" value="CDVNotification" />
    </feature>
    <feature name="File">
        <param name="ios-package" value="CDVFile" />
    </feature>
    <feature name="FileTransfer">
        <param name="ios-package" value="CDVFileTransfer" />
    </feature>
    <feature name="Geolocation">
        <param name="ios-package" value="CDVLocation" />
    </feature>
    <feature name="Globalization">
        <param name="ios-package" value="CDVGlobalization" />
    </feature>
    <feature name="InAppBrowser">
        <param name="ios-package" value="CDVInAppBrowser" />
    </feature>
    <feature name="Media">
        <param name="ios-package" value="CDVSound" />
    </feature>
    <feature name="Capture">
        <param name="ios-package" value="CDVCapture" />
    </feature>
    <feature name="NetworkStatus">
        <param name="ios-package" value="CDVConnection" />
    </feature>
    <feature name="SplashScreen">
        <param name="ios-package" value="CDVSplashScreen" />
    </feature>
    <feature name="Vibration">
        <param name="ios-package" value="CDVVibration" />
    </feature>

    <feature name="WLSplashScreen">
        <param name="ios-package" value="WLSplashPlugin" />
    </feature>
    <feature name="LoggerPlugin">
        <param name="ios-package" value="LoggerPlugin" />
    </feature>
    <feature name="DeviceAuth">
        <param name="ios-package" value="DeviceAuthPlugin" />
    </feature>
    <feature name="UserAuth">
        <param name="ios-package" value="UserAuthPlugin" />
    </feature>
    <feature name="WebResourcesDownloader">
        <param name="ios-package" value="WebResourcesDownloader" />
    </feature>
    <feature name="WLDirectUpdatePlugin">
        <param name="ios-package" value="WLDirectUpdatePlugin" />
    </feature>
    <feature name="WLNotification">
        <param name="ios-package" value="WLNotification" />
    </feature>
    <feature name="WLApp">
        <param name="ios-package" value="WLApp" />
        <param name="onload" value="true" />
    </feature>
    <feature name="UIControls">
        <param name="ios-package" value="UIControls" />
    </feature>
    <feature name="Push">
        <param name="ios-package" value="Push" />
        <param name="onload" value="true" />
    </feature>
    <feature name="NetworkDetector">
        <param name="ios-package" value="NetworkDetector" />
    </feature>
    <feature name="NativePage">
        <param name="ios-package" value="NativePage" />
    </feature>
    <feature name="SecurityPlugin">
        <param name="ios-package" value="SecurityPlugin" />
    </feature>
    <feature name="StoragePlugin">
        <param name="ios-package" value="StoragePlugin" />
    </feature>
    <feature name="FIPSHttpPlugin">
        <param name="ios-package" value="FIPSHttpPlugin" />
    </feature>
    <feature name="Badge">
        <param name="ios-package" value="Badge" />
    </feature>
    <feature name="NotificationEx">
        <param name="ios-package" value="NotificationEx" />
    </feature>
    <feature name="WifiPlugin">
        <param name="ios-package" value="WifiPlugin" />
    </feature>
    <feature name="CoreLocationGetLocationPlugin">
        <param name="ios-package" value="CoreLocationGetLocationPlugin" />
    </feature>
    <feature name="CoreLocationWatchPlugin">
        <param name="ios-package" value="CoreLocationWatchPlugin" />
    </feature>
    <feature name="SignificantChangeWatchPlugin">
        <param name="ios-package" value="SignificantChangeWatchPlugin" />
    </feature>
    <feature name="SignificantChangeGetLocationPlugin">
        <param name="ios-package" value="SignificantChangeGetLocationPlugin" />
    </feature>
    <feature name="WLNativeXHRPlugin">
        <param name="ios-package" value="WLNativeXHRPlugin" />
    </feature>
    <feature name="WLActionSenderPlugin">
        <param name="ios-package" value="WLActionSenderPlugin" />
    </feature>
    <feature name="WLTrusteer">
        <param name="ios-package" value="WLTrusteerPlugin" />
    </feature>
    <access origin="*" />
</widget>

Comment: You might want to try removing your iPhone environment from the Worklight project and recreating it
Comment: Can you share your sample project on dropbox or something similar so that I can look into it. You could also provide your config.xml
Answer: First, try to first upgrade the Studio installation to the latest available by downloading the latest Worklight 188.8.131.52 iFix from IBM Fix Central.
Next, possible solutions:

Delete the iPhone environment folder and re-add it
Delete only the iphone\native folder and re-build the project

Follow either option with a re-run in Xcode.


How to change the product type of selected Drupal Commerce products (without direct DB updates)?

Question: In order to apply a price calculation rule for certain products only, I have created a new product type. But I am having problems changing the product type for the selected products. Right now it seems to me that the only way to apply the new product type to these products is to delete them and then re-import them (using Feeds) with the new product type selected. This works as expected.
But there are hundreds of products and it seems to me that there should be an easier way. I have read this post How Can I change the machine name of product type but I am a bit wary that I might break something by changing things in the database.
Does anybody have a cleaner solution for this?
Comment: Are you able to create a "view" which contains a list of those hundreds of products, with 1 column for each of the relevant field-values that you'd need for creating equivalent products using that new product type? PS: only a "bit" wary? I'd rather say a "lot", or "terribly" ... So for sure I'd not use change things in the DB.
Comment: Yes, I could clone the existing Products view and add a filter to only show the relevant products. But... how do I apply my price calculation rule to the products in that view? I tried to create a condition, but with no luck...
Comment: I'm thinking of a solution that does the equivalent of "change machine name". That solution requires the views result as input to be processed. So may I assume you can adapt that price calculation rule somehow to also (or only) support that new product type?
Answer: For sure I'd not use the approach of changing things in the Database directly. Instead I would try to use the Rules module to create a clone (using the new product type) of the selected products. A solution that could possibly work is to (also) get the Views Rules module involved. Some details about this module (from its project page):

Provides Views directly as Rules actions and loops to seamlessly use view result data.

If you're not familiar with Rules (yet), the previous quote may seem a bit cryptic (it may make you think like "so what, how can this help me?"). Therefor some more details about how to move forward using these modules:

Create a view (using Views) so that you have 1 Views result (row) for each product of old product type and for which you want to create a similar one with the new product type. This view should have fields (columns) for each of the fields from your old products that you want to use to create your new product (with your new product type). Important: use a Views display type of "Rules".
Create a custom rule in which you use the Views Rules module to iterate over each of these Views results in a Rules action, using the Rules technique known as a "Rules Loop". If you're not familiar with Rules Loops, then have a look at the tutorial titled "Lists and loops".
For each iteration step in your Rules Loop, perform a Rules Action to create an entity which corresponds to your product but with the new product type. At that point you'll have all data from each column of your Views results available as so called Rules Parameters (remember: they are the values used in your products with the old product type). So at that point it's a piece of cake to populate the various fields of your product with the new product type.
The only remaining thing is to decide about the Rules Event to use for this rule to be triggered. But that's up to your own imagination (any Rules Event will do). Optionally, you may also want to add whatever extra Rules Condition(s), also up to your own imagination.

Possibly, you also want to delete the product (of the old product type), e.g using a variation of this rule (to delete those products instead of creating new entities). I would definitely do that in a separate rule (not as an extra Rules Action in the same rule), to be able to verify that the new products are created (correctly) before deleting the products with the old product types (better safe then sorry ...).
Note: Refer to my answer to "How to use Rules to send an E-mail after saving a new comment, to users who checked a boolean in their profile?" (the option 2-part of it) for an example (with screenprints) about how to use the Views Rules module.
Comment: Wow, that was a very detailed answer. I am familiar with Rules but I haven't used the Views Rules modules and I haven't used loops. I will try your suggestion out. Thanks!
Comment: @TBJ : merci for your comment. Let us know how it turned out after trying it. It seems that not a lot of Rules-fans know about the "Views Rules" module, but that's really one of the must-have add-ons if you like using Rules. BTW, using the above approach you could make it somehow similar to using the "node_convert" module also (to convert just any content type instead of just a content type). I might post a self answered question on that some day ...
Comment: Hmmm, I got stuck at the configuration of row variables in the new rules view. I chose Commerce Product as data type for all the fields, but that results in plain text fields in the action part of the rule. As if I wanted all the products with the new product type to have fixed names and prices :-)...
Comment: I have tried several different options.. "text", "list of commerce products" , "rules configuration" etc. But in the "action" I always get a plain text field for fixed values to fill in. Except for "Product type" where I can actually choose the new product type in a list.
Comment: @TBJ : check my updated answer (the "note" I added). If with that you still can't get it to work, how about you post a new question about how to use "Views Rules" in your specific case (with relevant screenprint(s) where appropriate)? After you would get that question answered, you may be able to continue with the approach I suggested here. Just using "comments" around here would be very tough to get it sorted out, no?
Comment: I have managed to get halfway there, but got stuck with the price field. I posted this question: http://drupal.stackexchange.com/questions/228691/what-data-type-to-use-for-commerce-price-field-in-views-loop-views-rules
Comment: @TBJ : merci for the accept! FYI: I'm checking a few things now to help you with the remaining price puzzle (95% sure I think what your issue really is, and how you can resolve it). FYI: I don't like posting "guesses" as real answers ...


Receiver in expresseion is a garbage value

Question: I am developing an iPhone app and are using xCode to do "Build and analyze". I get the message "Receiver in expresseion is a garbage value" pointing to the line of the return-row in my bode below:
-(UIColor*)getLevelColor{
UIColor* tempCol;

if (level==4) {
    tempCol= [[UIColor alloc] initWithRed:0.39f green:0.82f blue:0.32f alpha:1.0f];
}else if (level==5) {
    tempCol= [[UIColor alloc] initWithRed:0.61f green:0.68f blue:0.83f alpha:1.0f];
}else if (level==6) {
    tempCol= [[UIColor alloc] initWithRed:0.90f green:0.68f blue:0.99f alpha:1.0f];
}else if (level==7) {
    tempCol= [[UIColor alloc] initWithRed:0.68f green:0.97f blue:0.99f alpha:1.0f];
}

return [tempCol autorelease];
}

How come I get this and how do I fix it so I don't get the message?
Thanks in advance!
Niklas
Answer: I'd guess that the compiler sees that there is a code path which returns an uninitialized value and gives you the news: tempCol is an uninitialized value unless level is anything else than 4,5,6 or 7. If you are sure that level will never be anything than 4,5,6 or 7 then add a else { return 0; } to the end of your if-ladder.
PS: You should use a switch(){} statement if you have to compare against a series of constant values, this is often faster and easier to maintain (IMHO). Alternatively, you could place the RGBA values in an array which you index with level.
(Disclaimer: I don't do Objective-C. Nobody should do it)
Comment: Objective-C is a wonderful language :) I disagree with your disclaimer.
Comment: Thanks for your answer. I think that creating an array and indexing with levels is a nice solution and it solves the problem if the reason is as you explained, which it should be. P.S. Well, if you want to develop for iPhone, I guess Objective-C is the only option D.S. /Niklas (normally a Java-guy...).


How many distinct triangles with at least one side of length $\sqrt{2}$ units can be drawn using three lattice points for the vertices?

Question:
This is supposed to be a middle school level math problem, I thought it should be ${}_9 C_3 - 8$ where 8 is the number of straight lines, but not sure. Thanks for any help!
Answer: The quantity $\binom93-8$ should give the total number of triangles, but ignores the restriction that one side must have length $\sqrt2$.
If we include that restriction, then:

There are $8$ different segments of length $\sqrt2$ that can be formed using these lattice points, and $7$ ways in each case to choose a third vertex of the triangle, for $8\cdot7 = 56$ triangles.
However, there are $8$ triangles with sides $\sqrt2, \sqrt2, 2$ that are counted twice, because they have two sides of length $\sqrt2$; we should subtract $8$ to account for these.
Additionally, there are $2$ diagonals, which are degenerate triangles with side lengths $\sqrt2, \sqrt2, 2\sqrt2$. These are each counted twice and should not be counted at all, so we should subtract $4$ to account for these.

Altogether, we get $56 - 8 - 4 = 44$ triangles.


Apache webserver - Mod status

Question: Heey all,
I have a question regarding the Mod Status module of Apache.
https://www.apache.org/server-status
As you guys can see there is a line: Total accesses and a value after it.
Is it possible to set restrictions of what to count and what not?
For example I've written a program which get this server-status info every 5 seconds. The program will access the page so total accesses will be +1 extra.
As the program is running on the specific server is it possible to restrict it from counting for calls coming from localhost?
Answer: No, it's not possible via configuration. I'd recommend just having a counter in your program counting the number of requests it has made, and subtract this from the total.
You can see the documentation for mod_status here; https://httpd.apache.org/docs/current/mod/mod_status.html
As you can see, the only extra option you have is turning ExtendedStatus on.
You might be able to do it if you modify the mod, and recompile it.
Comment: Counter will be easy solution then (yet ugly) ah well

Apache webserver - Mod status


custom template loader Django

Question: i am trying to write a custom template loader in django which serves index.html which is present in a s3 bucket. Following is my loader file
from django.conf import settings
from django.template import Origin, Engine
from django.template.loader import TemplateDoesNotExist
from django.template.loaders.base import Loader
from boto3.session import Session

ACCESS_KEY_NAME = getattr(settings, 'AWS_TEMPLATE_LOADING_ACCESS_KEY_ID', getattr(settings, 'AWS_TEMPLATE_LOADING_ACCESS_KEY_ID', None))
SECRET_KEY_NAME = getattr(settings, 'AWS_TEMPLATE_LOADING_SECRET_ACCESS_KEY', getattr(settings, 'AWS_TEMPLATE_LOADING_SECRET_ACCESS_KEY', None))
TEMPLATE_BUCKET = getattr(settings, 'AWS_TEMPLATE_BUCKET_NAME')

class Loader(Loader):
    is_usable = True

    def __init__(self, *args, **kwargs):
        params = args[0]
        options = params.pop('OPTIONS').copy()
        options.setdefault('autoescape', True)
        options.setdefault('debug', settings.DEBUG)
        options.setdefault('file_charset', settings.FILE_CHARSET)
        libraries = options.get('libraries', {})
        session = Session(aws_access_key_id=ACCESS_KEY_NAME,
                          aws_secret_access_key=SECRET_KEY_NAME)
        s3 = session.resource('s3')
        self.bucket = s3.Bucket(TEMPLATE_BUCKET)
        super(Loader, self).__init__(*args, **kwargs)
        self.engine = Engine(dirs=params['DIRS'], context_processors=options, loaders=Loader)

    def getKeys(self):
        keys_objects = []
        for obj in self.bucket.objects.all():
            key = obj.key
            keys_objects.append({
                'key': key,
                'object': obj
            })
        return keys_objects

    def get_contents(self, origin):
        try:
            keys_objects = self.getKeys()
            for key_object in keys_objects:
                if key_object['key'] == origin:
                    return key_object['object'].get()['Body'].read()
        except FileNotFoundError:
            raise TemplateDoesNotExist(origin)

    def get_template_sources(self, template_name, template_dirs=None):
        tried = []
        yield Origin(
            name=template_name,
            template_name=template_name,
            loader=self,
        )
        tried.append('/index.html')
        if tried:
            error_msg = "Tried Keys %s" % tried
        else:
            error_msg = "Your TEMPLATE_DIRS setting is empty. Change it to point to at least one template directory."
        raise TemplateDoesNotExist(error_msg)

    get_template_sources.is_usable = True

and in my settings i have set the template settings in following way.
TEMPLATES = [
    {
        'BACKEND': 'app.s3template_loader.Loader',
        'DIRS': [
            'index.html'
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    }
]

anf following is my view
from django.shortcuts import render
from django.views.generic import TemplateView

# Create your views here.

class AngularAppView(TemplateView):
    template_name = 'index.html'

but when i am trying to acces my end point i am getting

Internal Server Error: / Traceback (most recent call last):   File
  "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py",
  line 41, in inner
      response = get_response(request)   File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py",
  line 217, in _get_response
      response = self.process_exception_by_middleware(e, request)   File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py",
  line 215, in _get_response
      response = response.render()   File "/usr/local/lib/python3.6/site-packages/django/template/response.py",
  line 107, in render
      self.content = self.rendered_content   File "/usr/local/lib/python3.6/site-packages/django/template/response.py",
  line 84, in rendered_content
      content = template.render(context, self._request) TypeError: render() takes 2 positional arguments but 3 were given

i am not able to find what i am doing wrong. any help is appreciated.
Answer: You built a loader, but you are using it as backend/engine. Try this config:
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            'index.html'
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'loaders': ['app.s3template_loader.Loader'],
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    }
]

Note that setting OPTIONS['loaders'] will disable caching. See docs on cached.Loader.
Comment: thanks for your resonse. can you kindly tell mehow can i use more than one engine in my TEMPLATES array?
Comment: Do you want multiple engines (Django, Jinja2, ...) or multiple loaders (your S3 loader, Filesystem Loader, ...)?
Comment: i want multiple engines, Django not multiple loaders
Comment: `TEMPLATES` is a list, just add multiple entries. For further details I suggest asking a new question :)
Comment: i am adding mutilple enteries but i getting **Template engine aliases aren't unique, duplicates: django. Set a unique NAME for each engine in settings.TEMPLATES.**
Comment: You have two entries with `'BACKEND': 'django.template.backends.django.DjangoTemplates'`. You can solve this issue by adding something like `'NAME': 'django2'` to the second entry, but maybe there is a better solution. Ask a new question with your configuration and what you want to accomplish.

custom template loader Django


Find the flaw in this proof that $1$ is the greatest natural number

Question:
I think the flaw is in assuming that $N^{2} \in \mathbb{N}$, but I don't know.
Comment: The flaw is in assuming that there is a largest positive integer.
Comment: @MattiP.: this follows from the hypothesis.
Comment: Since when is $N \geq N^2$ for $N \in \mathbb{N}$ ?
Comment: Where would $N+1$ fit into all of this? If $N \ge N+1$ then $0 \ge 1$ would be simpler contradiction.
Comment: @copper.hat: that's right. I guess that the goal is to make the proof cumbersome and divert attention so that the flaw is no immediately apparent.
Comment: Please edit your question tot property typeset the mathematics.  You may want to refer to the [MathJax guide](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) on meta.
Comment: You have proven "if a largest natural number exists, then it is 1". This is because your first line says "let N be the largest natural number", but you have not shown its existence! Indeed, as one answerer says, you can use your (entirely correct) logic to contradict, thus showing there is no largest natural number
Answer: The proof is logically correct, and leads to a contradiction (we know that $1<2$). Thus it is a valid proof that there is no greatest natural number.
Answer: The flaw is in assuming there is a largest natural number. Assuming that, one can also show that number is $2$, or $17$, or $-3.5$, all at the same time. Ex falso quodlibet.


Let's review our guidelines for "off topic"

Question: I've seen a rather high number number of off-topic flags that I have then marked as on-topic. In many cases I see close votes pile on in what could be interpreted as brigading.
On topic?
This question caught my eye in particular: Image alt not showing at magento product page
The question asks "how can I add an alt tag to an image in a Magento product page"... and has been marked by 3 separate site users as off-topic. However, at the time of this writing there are two answers.
According to our help document for the on-topic guidelines this matches the top three points:

It does not involve custom code
It does not involve a third-party vendor
No 3rd party developer can be contacted for support.

So it looks to me like it is actually on-topic. Perhaps the close votes are trying to signify that the "fix" is not Magento-centric and this is a gray area? At what point do we stop helping locate where to place a change because the change itself is "simplistic"?
Off Topic?
Let's review a type of question which I believe, by our guidelines, is likely off-topic.
Questions about Varnish aren't too rare around Magento.SE - but questions specifically about Turpentine (an OSS 3rd party module by Nexcess) are very very rare.
However, they do have their own tag but they break the community guidelines:

It involves custom code
It involves a third-party vendor
A 3rd party developer can be contacted for support

A question just posted referenced it in the title:
https://magento.stackexchange.com/questions/82490/magento-turpentine-excluded-parameters-in-vcl-produce-incorrect-redirect
There are no answers at the time of this writing, and no off-topic votes at the time of this writing.
Getting to the point
Which leads me to my point:

Have our "on-topic" guidelines changed?
If so, do we need to update that document?
Is the document sparse for a reason? Should we be more explicit?

and lastly:

Is this question in fact off-topic? Why?

(I submit that this question is on-topic and have voted accordingly. But I would like the community to weigh in here.)
I realize that Q to A ratio is important for the overall health of the site, but let's be careful not to appear to be unhelpful in the process.
Answer: I've been moderating these kind of flag+close vote pileups since day one without stopping think that people might be blindly "agreeing" with the flag. Thanks for giving voice to this.
Nothing has been formally decided, and I suppose now is as good a time as any to remind people to keep the site fundamentals in mind when they are curating. The guidelines use the following language [emphasis mine]:

Questions which involve custom code or extensions should include relevant code

I don't recall if I drafted this or not, but I agree with it in the RFC sense of "should". It's not a requirement, but it's probably a good idea. At the very least we need context to provide good responses efficiently. This doesn't necessarily require the custom/third party code. Newbies should read this and err on the side of verbosity, and veterans might do to remind themselves of this focus.
Comment: At any rate those guidelines were drafted at the inception of the site. I would like to propose that we review them every so often.
Comment: Does the post in question conform to our guidelines? Are our guidelines purposely vague? Can we do anything to make it clearer what is or is not on-topic? I agree with RFC language, though I wonder if this was intentional or just a current interpretation.
Answer: Thanks for raising this issue, I agree that the on topic guidelines are open to interpretation and obviously interpreted in different ways. Also the way this site evolved, the rules in practice might have diverged from the original intent.
Both are reasons to rephrase the guidelines.
I don't have a ready suggestion but will add my 2 cents to keep the discussion alive:

Perhaps the close votes are trying to signify that the "fix" is not Magento-centric and this is a gray area? At what point do we stop helping locate where to place a change because the change itself is "simplistic"?

Many questions are not really Magento specific, for example those that could be asked on StackOverflow or ServerFault as well and often don't need Magento knowledge at all to be answered. I find it hard to draw the line in these cases and in doubt, would rather not close them (at least not for being off topic):

if there is a good chance that it is relevant for other Magento developers or merchants
if it's possible to give the topic a Magento specific spin

Examples for those borderline questions can often be found in css and htaccess.

Questions about Varnish aren't too rare around Magento.SE - but questions specifically about Turpentine (an OSS 3rd party module by Nexcess) are very very rare.

That's a good example of questions about third party extensions that I would not close blindly.
Generally spoken: Questions on popular open source modules can be useful and often get enough positive votes and answers to justify them. Of course some should have been GitHub issues or are too special to get answers here.
More on third party extensions, I'll quote myself:

I will continue to close quesions that boil down to "recommend me extensions for X" (opinion based, attracts low quality answers and spam), questions like "I installed extension Y and get an error" (better suited for vendor support or as GitHub issues), and delete low quality answers that are obviously spammed by extension vendors to sell their products (recommending extensions is okay in general, but it should be reasoned, and any affiliation should be disclosed).
Other questions related to third party extensions must be handled case by case. Good examples are questions about modules that are targeted at developers, like the questions in avs-fastsimpleimport and ecomdev-phpunit tags.
Answer: I have seen quite a few questionable close pileups (nice one, @benmarks) as well, usually involving a third-party module. I think that can be a trigger for a quick close, even if the question is in regard to valid Magento code that just happens to be in a third-party module.
Since integrating third party modules is a common point of entry for new users to Magento development, I think as long as the question isn't specifically about that module's functionality it should be left alone. This is an example - I happened to see when this question was posted, and it was quickly flagged for close. While the author's point could be easier to understand, I think the answer that he was after is valuable information for future users.
Just my 2 cents. Thanks for posing the question, @philwinkle
Comment: The issue has been on my mind for a bit, but I wasn't sure how to approach the subject. Luckily, I voted for conscientious moderators! ; )
Comment: Great point. I've reopened that question; great example of what I'm talking about.
Comment: Always feel free to reach out to me on twitter - @philwinkle
Comment: Will do, thanks for putting in the time to mod.
Answer: Regarding the first one, even if it is a simple question, and not magento specific, it is a Question a lot of people working with magento would probably like to get answered. But it depends, if we only want to target developers, or also "users" of magento.
From a developer it may be to expect, he knows such simple html/php basics, but for a user its a possibly hard task to do.
My personal opinion is, to also support the users.
Comment: +1 for not only support developers


Failed to instantiate [org.springframework.web.servlet.HandlerExceptionResolver];Ambiguous @ExceptionHandler method mapped

Question: My GlobalExceptionHandlerController class:
<code>@ControllerAdvice
public class GlobalExceptionHandlerController {

    @ExceptionHandler
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public String handleError404(HttpServletRequest request, Exception e) {
        return "404";
    }

    @ExceptionHandler
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public String handleError400(HttpServletRequest request, Exception e) {
        return "errors1";
    }

    @ExceptionHandler
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public String handleError403(HttpServletRequest request, Exception e) {
        return "errors2";
    }

    @ExceptionHandler
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public String handleError500(HttpServletRequest request, Exception e) {
        return "errors3";
    }

    @ExceptionHandler
    @ResponseStatus(HttpStatus.TOO_MANY_REQUESTS)
    public String handleError429(HttpServletRequest request, Exception e) {
        return "errors4";
    }

}
</code>
I'm getting this error:
<code>Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerExceptionResolver]: Factory method 'handlerExceptionResolver' threw exception; nested exception is java.lang.IllegalStateException: Ambiguous @ExceptionHandler method mapped for [class java.lang.Exception]: {public java.lang.String com.fussa.fyby.configuration.GlobalExceptionHandlerController.handleError403(javax.servlet.http.HttpServletRequest,java.lang.Exception), public java.lang.String com.fussa.fyby.configuration.GlobalExceptionHandlerController.handleError400(javax.servlet.http.HttpServletRequest,java.lang.Exception)}
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
    ... 24 more
Caused by: java.lang.IllegalStateException: Ambiguous @ExceptionHandler method mapped for [class java.lang.Exception]: {public java.lang.String com.fussa.fyby.configuration.GlobalExceptionHandlerController.handleError403(javax.servlet.http.HttpServletRequest,java.lang.Exception), public java.lang.String com.fussa.fyby.configuration.GlobalExceptionHandlerController.handleError400(javax.servlet.http.HttpServletRequest,java.lang.Exception)}
    at org.springframework.web.method.annotation.ExceptionHandlerMethodResolver.addExceptionMapping(ExceptionHandlerMethodResolver.java:109)
    at org.springframework.web.method.annotation.ExceptionHandlerMethodResolver.<init>(ExceptionHandlerMethodResolver.java:76)
    at org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver.initExceptionHandlerAdviceCache(ExceptionHandlerExceptionResolver.java:265)
    at org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver.afterPropertiesSet(ExceptionHandlerExceptionResolver.java:241)
    at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.addDefaultHandlerExceptionResolvers(WebMvcConfigurationSupport.java:879)
    at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.handlerExceptionResolver(WebMvcConfigurationSupport.java:822)
    at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerBySpringCGLIB$$400a1941.CGLIB$handlerExceptionResolver$41(<generated>)
    at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerBySpringCGLIB$$400a1941$$FastClassBySpringCGLIB$$2aaff7a.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:356)
    at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerBySpringCGLIB$$400a1941.handlerExceptionResolver(<generated>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
    ... 25 more
</code>
Thanks for any advices..
Answer: Spring can not guess which handler method it should use for which exception. Since you don't define them.
Set the value for the ExceptionHandler annotation for each method appropriate and make sure there are no duplicates.
Answer: As mh-dev suggest, i defined exception for each ExceptionHandler annotation:
<code>@ControllerAdvice
public class GlobalExceptionHandlerController {

    @ExceptionHandler
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public String handleError404(HttpServletRequest request, Exception e) {
        return "404";
    }

    @ExceptionHandler({ HttpClientErrorException.class,Throwable.class  })
    @ResponseStatus
    public String handleError4xx(HttpServletRequest request, Exception e) {
        return "errors4";
    }

    @ExceptionHandler(HttpServerErrorException.class)
    @ResponseStatus
    public String handleError5xx(HttpServletRequest request, Exception e) {
        return "errors5";
    }

}
</code>