struggling with Jquery ui accordion plugin

Question: I have built this accordion using the jquery ui accordion plugin, I sort of understand how it works but I am stuggling to find the correct way for the accordion to close on mouse out. I would also like for my own arrow icons to swap for a down arrow when an accordion section  is open. Here is the fiddle:jquery accordion plugin
Any help appreciated even if it sjust pointing in the right direction. The most important thing is to collapse on mouseout
Comment: On a side note, `id` is designed to be a unique identifier on a DOM element, therefore if you've got a common `id` amongst elements, you're better off using a `class` as the selector. :)
Comment: I understand there us a lot of questions on this but I can't find the answers I am looking for
Answer: Here you go: fiddle
$(function() {
    $( "#accordion" ).accordion({
        event: 'click',
        collapsible: true,
        active: false,
        icons: {
            "header": "yourIconClassClosed",
            "headerSelected": "yourIconClassOpen"
        }
    }).on('mouseleave', function() {
        $(this).accordion( "option", "active", false );
    }).children('li').on('mouseenter', function() {
        $(this).find('h3').trigger('click');
    });
});

EDIT: You have to consider my reconstructed HTML:

About us

List item one

List item two

List item three

Section 1

List item one

List item two

List item three

Section 2

List item one

List item two

List item three

Section 3

List item one

List item two

List item three

Section 4

List item one

List item two

List item three

Comment: Is there a hover version of this?
Comment: It is hover, isn't it? I just bind accordion to click and then trigger it so you can use both mouseover and click functionality...
Comment: Did you use the same HTML as I? I don't think so because you see that it works in the fiddle ;)
Comment: I did, the site I have entered this into only has jquery 1.4.2 (can't change it) would this make a difference it has UI 1.8.9 too
Comment: Erm well, you set up your fiddle with jQuery 1.7, it seems like the latest UI version for 1.4.4 (on jsfiddle) doesn't even have accordion...
Comment: sorry I have UI 1.8.9 and Jquery 1.4.2
Comment: I just changed it on the fiddle and Its the version that's causing the problem my bad, I will try and get our libraries updated
Answer: This may answer part of your question
http://jsfiddle.net/Z6LWH/1/
Comment: thank you Donlad that works but when you mouse out from the sub menu its doesn't, how do I get it to collapse when mouseout from the whole accordion
Comment: Move the About us inside the accordion div. Might be an oversight
Answer: Another part to the solution: set icon classes
$( "#accordion" ).accordion({
    event: "mouseover",
    collapsible: true,
    active: false,
    alwaysOpen: false,
    icons: {
        "header": "yourIconClassClosed",
        "headerSelected": "yourIconClassOpen"
    }
});

And then set styles on those classes.


i am not able to put this inside loop to shorten my code. It giver error of node type

Question: I am trying to add this code in for-loop but it is giving me below error

"Failed to execute 'appendChild' on 'Node': parameter 1 is not of type
  'Node'"

let tableBody = document.querySelector('#table tbody');

let row1 = document.createElement('tr');
let row2 = row1.cloneNode(true);
let row3 = row1.cloneNode(true);
let row4 = row1.cloneNode(true);
let row5 = row1.cloneNode(true);

tableBody.appendChild(row1);
tableBody.appendChild(row2);
tableBody.appendChild(row3);
tableBody.appendChild(row4);
tableBody.appendChild(row5);

I am trying like this
for(i = 1; i <=5; i++){
  tableBody.appendChild('row' + i);
}

Comment: because you are trying to append the string 'row1', 'row2' and not the row1, row2, etc node itself.
Comment: You can create an array and push each new node to an array and then you can run for loop directly on the array. eg:  const arr = []; arr.push(row1.cloneNode(true))
Comment: Why not `tableBody.appendChild(document.createElement('tr'));` or `tableBody.appendChild(row1.cloneNode(true));` inside the loop?
Answer: You are not appending the actual object. You are appending a string.
Try it like that:
let tableBody = document.querySelector('#table tbody');

let rows = []
rows.push(document.createElement('tr'));
rows.push(rows[0].cloneNode(true));
rows.push(rows[0].cloneNode(true));
rows.push(rows[0].cloneNode(true));
rows.push(rows[0].cloneNode(true));

rows.forEach(row => {
  tableBody.appendChild(row);
})

Answer: The reason you code  tableBody.appendChild('row' + i); is not working 'row' + i is nothing but a sting , which is not a variable holding a node,
put all the rows in array and add it from there
try this
let tableBody = document.querySelector('#table tbody');

let rows=[];
rows.push(document.createElement('tr'));
rows.push(row1.cloneNode(true));
rows.push(row1.cloneNode(true));
rows.push(row1.cloneNode(true));
rows.push(row1.cloneNode(true));

for(i = 0 ; i <rows.length; i++){
  tableBody.appendChild(row[i]);
}

Suggesting reading : Array, variables, function
Answer: appendChild takes DOM node object (https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild), As mentioned by others you are providing a string.
It looks as though you want to create a table with 5 rows, if so, this is how you could go about it:
for(i = 1; i <=5; i++){
  tableBody.appendChild(document.createElement('tr'));
}


What's the difference between "con brio" and "con fuoco"?

Question: Do they just have different names but are meant to be played the same?  Also, it seems like if "con fuoco" never appears in major keys, except for Beethoven's Piano Sonata No. 18.
Comment: I've asked a question on [meta] about retagging this question: [What is the proper tag name for tempo indications/directions/instructions?](https://music.meta.stackexchange.com/q/3157/2257)
Answer: There's not much (if any) difference in the tempo they imply, but there's a difference in character.
Literally, con brio means with spirit, while con fuoco means with fire.
Regarding tempo, both are traditionally taken to mean that it should be a little faster than it otherwise would be — allegro con brio/fuoco a bit faster than a typical allegro, and similarly for presto con brio/fuoco. There's not much difference (in my experience) between the tempos they suggest; perhaps con fuoco tends to be taken as slightly faster than con brio, but there's certainly a large overlap between the ranges they can cover.
In terms of character, though, there's definitely a difference difference.  Con brio is more light-hearted, suggesting an enthusiastic, spirited kind of speed — fast because you're enjoying going fast.  Con fuoco is more serious and urgent — going fast because there's a fire at your heels, or a passion inside you that you can't restrain.
Answer: 'Brio' = vigour, spirit, fire.
'Fuoco' = fire, a combination of force and speed.
Both from Italian, meaning pretty well the same, one composer may use one, another the other. I doubt whether one would use both. No doubt someone will let us know!
Comment: Not much to do with actual musical practice, but in Italian *brio* means *vivacity, merriment, exuberance*, not really *fire*
Comment: "Brio" does not mean *fire,* except perhaps metaphorically.  I certainly see that meaning in no dictionary entry for the word.  "Fuoco," on the other hand, literally does mean *fire,* to the extent that Italian firefighters are the *vigili del fuoco.*
Comment: I've seen "Allegro con brio" more often than "Presto con fuoco". "Allegro con fuoco" is even rarer, and then I don't think I've ever seen "Presto con brio".
Comment: "Presto con brio" - I've seen them.
Comment: I am speaking of depicting a the literal concept of fire (i.e., paintings of fire are not literally aflame, yet they do depict literal fire) versus using a word that means "liveliness" and describing it as "fire."  Perhaps it is analogous to the difference between a dictionary and a thesaurus, where the latter will also include words that are related, but not necessarily synonyms.  Music that is "con fuoco" *should* evoke fire, but music that is "con brio" may or may not.
Comment: Although you are formally right, Tim, there is a little **theory** over character: "brio" is spirited like when you debate over the new president, while "fuoco" is like when you are desperate to use the restroom but it is locked.  In fact, "con fuoco" is more closely related to minor keys.
Answer: "Fuoco," meaning fire, implies heat and combustion, and therefore turbulence or, as noted by guidot, urgency.  "Brio," meaning liveliness or vigor, does not.  This is consistent with your observation that the direction con fuoco is more closely associated with minor keys, which also tend to portray more complex or indeed turbulent emotions.
Comment: What direction does **this** situation fit to the best:  When you are desperate to pee but there are no restrooms available.
Answer: Italian here, with a little background in music theory.
The words have very different meanings; especially the word "brio" I see being misinterpreted.
"Brio" means light-headed happiness. Think more of an elegant version of "allegro". I would play it by letting the fingers fly on the keyboard. (Note that allegro may also indicate how fast to play it: lentissimo < lento < allegro < presto < veloce < velocissimo)
"Fuoco" literally may mean fire, but in this case it is intended as "with passion". I would play it by smashing the notes, especially in long note and main passages.
While I'm here I also want to answer some comments:
"Allegro con brio" means happy, but the brio part focuses on the distracted nature of happiness, like you are casually playing the music just because you like it.
"Presto con fuoco" means fast with passion; like you are going to your crush and she is home alone.
"Allegro con fuoco" means happy with passion; like your crush told you to come over tomorrow as she will be home alone.
Comment: "Note that allegro may also indicate how fast to play it": many native speakers of English are probably unaware that allegro can mean anything other than an indication of speed.
Answer: It is somewhat misleading, that both may be translated to with fire.
If I remember correctly con brio mostly means lively. Its mostly used to supplement Allegro to give a sort of tempo indication, see related question.
Con fuoco is the real with fire, meaning a sort of urgency, as if the coat were on fire. Summarized: Con brio is considerably more harmless, which as Dekkadeci comments, makes it a useless addition to Presto.
Comment: @RailroadHill: While my first example, Dvroaks symphony #9, 4th movement is in e minor, I don't recognize, why speed should strictly map to major or minor.
Comment: Do you have any support to the assertion that "brio" may be translated as "fire"?  I do not see that sense in any dictionary, so to the extent that it may be translated thus, it is metaphorical.
Comment: WHen I see "brio," I think toy train sets :-)
Comment: Does this mean that "con fuoco" is NEVER used in major keys, but only in minor keys?
Comment: @CarlWitthoft - I only think Hornby double O, or Triang. Please explain!
Comment: @Tim For example [Article from Wikipedia](https://en.wikipedia.org/wiki/Brio_(company)) - it's a swedish wood toy company which is best known for their wooden toy trains.
Comment: @CarlWitthoft - well, that pretty well proves that 'brio' won't mean 'fire'..! Unless they were steam trains?
Answer: Con Fuoco would be hard, fast and loud. Con Brio would be with spirit but this can be at a relaxed tempo as well, Con Brio, spirited like when you debate something that is very important to you, Con Fuoco, losing your temper at someone who has madden you to the point you want to slap him.
Comment: Beethoven's Symphony 5 1st mvt, in C minor, is marked "Allegro con **brio**", while it is very raging and stormy.
Comment: Beethoven Piano sonata No.18 in E flat major, fourth movement


Bridge pickup with no sound. Testing with multimeter and trying to find where the failure is

Question: I installed a new bridge pickup on my Telecaster. It worked briefly, but then no sound came out of it.  The neck pickup still works. I tried installing the old pickup back into the bridge as well, but it also does not work now.
The setup is a 3-way selector, 1 Volume and no tone. In place of the Tone is a switch that reversed polarity. (This is a Ritchie Kotzen Telephone)
What I have done so far with my multimeter on 20K Ohm.

Desoldered the pickup and tested wires. It reads 12.37, which is correct.
Resoldered and tested the wires this way, it reads the same 12.37
Tested the output jack by touching the tip and sleeve. The results in 0L.
Switched to the neck pickup on the selector and tested output jack the same way. It reads 6.4, which is about right for the neck pickup.
Still on the neck pickup, I tested by putting the black needle from the multimeter on the grounded lug and the red needle on the hot wire. It reads - 0.00.
Still on the neck pickup, I change the red needle to the hot wire of the bridge pickup, it reads 12.37.
Switched selector back to bridge. Needles on neck pickup, reads 0L. Bridge pickup reads 12.37

There are some weird inconsistencies going on here.  The neck pickup works great, the bridge isn't making and output.
Any tips on what I should look for?
Answer: If you are getting zero ohms across the bridge pickup then that's your problem: there is a short circuit somewhere.
Your testing indicates it isn't in the pickup, as you still get an appropriate resistance across it when not installed, so the most likely causes are:

a short you caused when soldering: check for accidental shorts between adjacent wires and connectors at the pickup and switch.
you soldered the wires incorrectly, probably at the switch, but also possible at the pickup. Check wiring diagrams. This pickup may have different connections or colours to your other one.

An example Fender wiring diagram (from David Allen)
Answer: This ended up being a bad switch. Somehow, the post that connected the bridge pickup failed during the last time I desoldered the wire. When testing it with a multimeter, I would get the correct readout on every post except the bridge post.  I bought a new switch, wired it up and it worked as expected.


Query on the performance standard deviation and relates to server performance

Question: I would like to know more about standard deviation and how it actually relates the performance of the server.
I ran a test where response time of the server is below - 280 ms(approx for all API)
Where i can see the std. dev as apprx 140 ms( all API falls into this)
from the above can u please help me to understand is the server perf is good ?
Also let we know if we can tell the server performance is consistant or not.
Thanks
Answer: As per Standard Deviation wikipedia article:

the standard deviation is a measure of the amount of variation or dispersion of a set of values.1 A low standard deviation indicates that the values tend to be close to the mean (also called the expected value) of the set, while a high standard deviation indicates that the values are spread out over a wider range.

In ideal world you should have absolutely the same response time no matter how much load do you conduct and this response time is very low so everyone is happy. So

if standard deviation is close to 0 - it is very good and means that response times distribution is minimal
if standard deviation is close to arithmetic mean is not very good and means that there is a lot of dispersion in the measured values, like instead of getting 248 all the time you're getting between 124 496.

You can use chart like Response Times Over Time (can be installed using JMeter Plugins Manager) to see how does the trend look like, i.e. it might be the case response times are more or less stable during ramp-up phase and start to grow as more and more virtual users are onboarding.
Other option is that the server is behaving absolutely normally and the dispersion is due to Connect Time/Latency fluctuation


Unexpected Entity Reference Autocomplete behaviour

Question: I'm using Entity API, Form API and Entity Reference Autocomplete in Drupal.
I have a relationship between two types, clubs and courses, each club can have many courses so basically the table course contains a column called goclid which references the club id number like so:
// hook_schema()

$schema['course'] = array(
    // other fields...
'goclid' => array(
    'description' => 'Reference to the club',
    'type' => 'int',
    'unsigned' => TRUE,
    'not null' => TRUE,
  ),

// ... a few lines later...
'foreign key' => array(
  'related_club' => array( // join alias
    'table' => 'club',
    'columns' => array('goclid' => 'id'),
  ),
),
// etc.
);

Then I include a field like so in the course form:
$form['goclid'] = array(
    '#title' => t('Reference to the club'),
    '#type' => 'entityreference',
    '#era_entity_type' => 'club',
    '#default_value' => isset($course->goclid) ? $course->goclid : '',
    '#required' => FALSE,
);

Now, the autocomplete gives suggestions only when I type an id number, and then populates the field value with the label (name of the golf club).
What I want is exactly the opposite: I want to get suggestions by typing the name of the club, and then when I choose one, the form field should be populated with the id number of that object.
Why is Entity Reference Autocomplete behaving in an unexpected way? What can I do to obtain the desired behaviour?
EDIT: to understand the solution look not only at the answer but also at the comments that I left below the answer; the answer itself only explains how to get the suggestions working but does not explain how to build and save the entity object in your submit function.
Answer: I think you might have not specified the "label" column in the entity definition. That goes within the 'entity keys' array, like the 'id' key.
$entity_info = array(
   .....
  'entity keys' array(
    'id' => 'primary key column...',
    'label' =>  'column holding the label'
  ),
)

Otherwise entityreference will not know which column to use for searching in the DB. That still makes it possible to show the label  (as you're experiencing) after you reference the entity, because 'label' key is not mandatory, and you may have specified a "label callback" instead, which the Entity API will use when entity_label() is called to get the label of a specific entity.
If adding the 'label' column and flushing all caches doesn't solve your problem, I think I'd need the entity definition to be able to help!
Comment: Thank you Salvador, this helps a lot, as you say I had specified a `label callback` so the auto-suggestion was showing the labels but I did not include  `label` in the `entity keys` array and that's way it wasn't searching by label. Now my last problem is that the database field which contains the foreign key is an integer but Entity Reference Autocomplete populates the field with something like `club label (id)`, is there a "canonical" way to get only the id from `$form_state`?
Comment: Actually, I have tested further and found out that `$form_state['values']['goclid']` is always being populated with `1`, regardless of the id of the referenced entity selected by the user. So I made some more research and found your article: https://www.codeenigma.com/community/blog/entity-reference-autocomplete-module which basically says to get the value from `$form_state['values']['entity_id']`, however for some reason I get undefined when I try to access it within the submit handler of the form. Any idea about why it is undefined?
Comment: update: the correct way of getting the id is in this case `$form_state['values']['goclid']['entity_id']` i.e. I was missing the field name `goclid` as array key.
Comment: Also, to allow the module to do the validation (check if the referenced entity exists) you have to wait until after the object is built (e.g. after using `entity_ui_form_submit_build_entity()`) and only at that point you can modify the value before saving, such as `$course->club_id = $form_state['values']['goclid']['entity_id'];`, this way the value saved will be only the numerical id as expected.


How should I sample data from my dataset to be manually labeled for a SVM?

Question: Assume I have a $2$-dimensional dataset $X=(x_1, x_2)$ where both features are not uniformly distributed over their respective ranges.
I now need to select $100$ datapoints from this dataset to be manually labeled, which will be used to train a 2-class SVM.
Should I choose these datapoints randomly or s.t. $x_1$ and $x_2$ are uniformly distributed?
Intuitively the latter makes more sense and should give a more accurate model, right? Unfortunately I can't find any source for that, even though I think it should be a common question. Probably just not googling right.
Answer: Well, if you can't assume randomness of data points in the set i.e. you assume the values are correlated with the order of the points in the set - you could make sample by uniformly taking the points (every n-th, where n = |P| / |s|; P is population, s is sample), but I would use the k-fold cross-validation technique (because I had the same dilemma as you and solved it by adopting this highly regarded validation technique):

The k-fold cross-validation provides fair accuracy estimation,
  using entire data set - when data insufficiency prevents separation of
  training and test data sets. The data is partitioned into k folds
  (exclusive, no data points shared among the folds), equal in size.
  Then, the validation is performed in k iterations, having different
  combination of k-1 training subsets and one test subset. Once all
  iterations are finished, the average values of the effectiveness
  measures (F1-score) are computed. Data points are distributed among folds randomly.

Btw. the Support Vector Machine is designed for binary (2-class) classification, it is not an option.
[1] C. Cortes, V. Vapnik, Support-Vector Networks, Mach. Learn. 20 (1995) 273–297. doi:10.1023/A:1022627411411.
Comment: I don't think this answers my question. What I meant was that, if my dataset contains $x_1=1$ 3 times as often as $x_1=2$, should my sample contain $x_1=1$ as often as $x_1=2$ (*uniformly sampled over the value range*) or should I sample randomly (in which case my sample would also approximately contain  $x_1=1$ 3 times as often as $x_1=2$).
Comment: From method standpoint: **no**, your sampling method should be agnostic on distribution of measured/collected values in the training dataset - because, you are proposing a method that should be generally applicable and not efficient only with  this particular dataset.
From technical/ML standpoint: the ML algorithms in general should learn quicker (i.e. become more precise, after less learning examples) if you provide more diverse training set. But, in case of SVM, I don't think you'll have that issue.
Overall: think about k-fold cross-validation, it will boost cred. of reported results.
Comment: Think about it like this: the point of your research is not to achieve good results but to propose a good method (algorithm/approach). Hence,  your method shouldn't be designed to reflect that closely the features of dataset, being available during research. Sampling of the training subset is part of the method too, not something you do for yourself. (If) you can't know what will be features of input dataset, when someone else tries to use the method proposed by your research.
Comment: (sorry, I forgot to give an answer :) ): in essence, if your dataset is collected by measuring independent variables: it doesn't meter if you take every n-th, first n-th or random n reads. If you ask me for simple answer: sample it randomly.
If you ask me for what I would do: use the k-fold cross-validation as it will clear you from such worries and provide you realistic* insights on performances of your method.(btw. I recon k=5 for debug/dev phase, and k=10 for the reported validation results)
* the F1-scores, measured with different datasets, will be within tighter range, if not ~the same
Comment: Thanks, I like the argumentation that the point of my research is not to achieve good results but to propose a good method.


Probability Need help understanding how to work problem out

Question: What number would complete this probability distribution?  And could you explain how, I am new to this and my textbook isn't helping.
x     3    7    11

P(X)0.38  0.29  ?
Answer: Hint: There are three possible outcomes, $3$, $7$, and $11$. The sum of the probabilities of these three outcomes is $1$.
Comment: I still don't get it if the 3 is 0.38, and the 7 is 0.29 the how did they get these numbers so I can find the missing number for 11 which is ?.  Hope this makes since I am just lost.
Comment: How they got the numbers is not important, maybe it was by doing a certain experiment many times. The point is that if you have a list of all the possible outcomes, their probabilities must add up to $1$. So if $p$ is the unknown probability that the result is $11$, then $0.38+0.29+p=1$. From this you can easily find $p$.
Comment: Thank you I see now. Was trying to hard.
Comment: You are welcome. There was nothing special about the numbers $0.38$ and $0.29$.


Discount for Roles

Question: I am using Drupal Commerce and I would like to know if it is possible to have discounted prices for registered users and much better for roles.
For example, the nomral price is $100 but when a user logs in that belongs to Role1 for example, he will see different prices with the percentage discount that I will have assigned to that role.  How can I accomplish such a feature?
Answer: You can set this up with Rules. Using the calculate sell price of a product, you can create different conditions (The users role) and add discount depending on the role the user have.
Note if you do this for several roles, you need to take care about the weight of the Rules and how you set discount, as you otherwise might end up with cumulative discounts or wrong discounts if you have users with multiple roles.
Comment: How would you explain your customer how to add/change the discount for a specific role?
Answer: Steps for Applying Discounts by Role in Drupal Commerce

Create a new role
Go to admin/commerce/config/product-pricing and Add a Pricing Rule
Call this new rule: Apply [role] Discount. Save
Conditions:

Add condition - user has role(s), value [your new role]. Save
Optional condition - Order contains products of particular product types -

Data Selector: commerce-line-item:order
Product Type: whatever ones you want.

Add action - Commerce Line Item: Multiple the unit price by some amount.
Data selector: commerce-line-item (use hyphenated, not the one with underscores)
Amount: Value: 0.85 (for 15% discount, so 85% of the price).
Price Component Type: Value: Discount. Save

Now when logged in as a user that has the role to allow for a discount, the discounted price will show for the item and on checkout it will show that a discount was applied.
Answer: I got this problem right now, googling around i found Og and Profile2 modules that could be configured to accomplish this need, but my customer need a really easy-to-manage solution, so i took another way:

I created a node content-type called "Discount"
Added a integer field "Discount percentage" to the "Discount" node type
Created a simply module that add a "Discount" node every time a new Role is created
Added 2 fields to the user profile (admin/config/people/accounts/fields), one for manual discount and another that gets calculated with roles.
In the Store Pricing rules, I created a rule for the event Calculating the sell price of a product with action Subtract an amount from the unit price and a custom PHP code.

This is the pricing rule amount code:
global $user;
$user_load = user_load($user->uid);
$discount_value = 0;
// Give precedence to an optional manual discount
if(isset($user_load->field_discount_manual['und'][0]['value']) AND (int)$user_load->field_discount_manual['und'][0]['value'] > 0)
{
    $discount_value = (int)$user_load->field_discount_manual['und'][0]['value'];
}
else if(isset($user_load->field_discount_role['und'][0]['value']))
{
    $discount_value = (int)$user_load->field_discount_role['und'][0]['value'];
}

if($discount_value > 0)
{
    return ($value * $discount_value) / 100;
}
// no discount
return 0;

This way let my customer to assign a discount to every role, managing them easly as other types of nodes (just play with Views to semplify the process).
EDIT
Indeed, was a bit insane all that discount calculations every time a product's price get displayed.
So i edited the module to make the calculations only when the user log in, and update the field_discount_role (that you have to add too) on the user profile, so the whole gear should be a bit less haevy.
The new module can be found here, but please note that you will need the Field Permission module too, or your customers can change they're own discount! (what a dream!)
OLD POST
Just in case the log-in behavior doesnt fit your needs, this is the first-approach.
Pricing rule amount code:
global $user;
$user_load = user_load($user->uid);
$discount_value = 0;
// Give precedence to an optional manual discount
if(isset($user_load->field_manual_discount['und'][0]['value']) AND (int)$user_load->field_manual_discount['und'][0]['value'] > 0)
{
    $discount_value = (int)$user_load->field_manual_discount['und'][0]['value'];
}
else
{
    // Get the discount nodes.
    // If user has multiple roles (usually _authenticated user_ and the discount role) i take the one with
    // higher discount. Depending on your customer neds, is up to you to sum, avg or do whatever you want.
    foreach($user->roles AS $role_name)
    {
        // using an IN() clause?
        $query = db_select('node', 'n');
        $record = $query->fields('n', array('nid'))
            ->condition('n.type', 'discount')
            ->condition('n.title', $role_name)
            ->execute()
            ->fetchObject();
        if($record !== false)
        {
            $discount = node_load($record->nid);
            if(isset($discount->nid))
            {
                if(isset($discount->field_discount['und'][0]['value']))
                {
                    $discount_value = (int)$discount->field_discount['und'][0]['value'] > $discount_value ? (int)$discount->field_discount['und'][0]['value'] : $discount_value;
                }
            }
        }
    }
}
if($discount_value > 0)
{
    return ($value * $discount_value) / 100;
}
// no discount
return 0;

Here you can find my module (please note is a quick'n'dirty module, you'll have to edit few settings in the .module file) and here the pricing rule I used (my customer asked to apply discounts only if the user has 3 or more items in the cart, so you'll find this condition in the rule).
Now im looking on how to do that calculation when the user login, put the user discount in the session or somewhere else and use this value instead of recalculate all every time, but this is a (needed) optimization.
Hope it helps.

Discount for Roles


How can I OOM all BestEffort Pods in Kubernetes?

Question: To demonstrate the kubelet's eviction behaviour, I am trying to deploy a Kubernetes workload that will consume memory to the point that the kubelet evicts all BestEffort Pods due to memory pressure but does not kill my workload (or at least not before the BestEffort Pods).
My best attempt is below. It writes to two tmpfs volumes (since, by default, the limit of a tmpfs volume is half of the Node's total memory). The 100 comes from the fact that --eviction-hard=memory.available<100Mi is set on the kubelet:
apiVersion: apps/v1
kind: DaemonSet
metadata:
  name: fallocate
  namespace: developer
spec:
  selector:
    matchLabels:
      app: fallocate
  template:
    metadata:
      labels:
        app: fallocate
    spec:
      containers:
      - name: alpine
        image: alpine
        command:
        - /bin/sh
        - -c
        - |
          count=1
          while true
          do

            AVAILABLE_DISK_KB=$(df /cache-1 | grep /cache-1 | awk '{print $4}')
            AVAILABLE_DISK_MB=$(( $AVAILABLE_DISK_KB / 1000 ))
            AVAILABLE_MEMORY_MB=$(free -m | grep Mem | awk '{print $4}')
            MINIMUM=$(( $AVAILABLE_DISK_MB > $AVAILABLE_MEMORY_MB ?  $AVAILABLE_MEMORY_MB : $AVAILABLE_DISK_MB ))
            fallocate -l $(( $MINIMUM - 100 ))MB /cache-1/$count

            AVAILABLE_DISK_KB=$(df /cache-2 | grep /cache-2 | awk '{print $4}')
            AVAILABLE_DISK_MB=$(( $AVAILABLE_DISK_KB / 1000 ))
            AVAILABLE_MEMORY_MB=$(free -m | grep Mem | awk '{print $4}')
            MINIMUM=$(( $AVAILABLE_DISK_MB > $AVAILABLE_MEMORY_MB ?  $AVAILABLE_MEMORY_MB : $AVAILABLE_DISK_MB ))
            fallocate -l $(( $MINIMUM - 100 ))MB /cache-2/$count

            count=$(( $count+1 ))
            sleep 1

          done
        resources:
          requests:
            memory: 2Gi
            cpu: 100m
          limits:
            cpu: 100m
        volumeMounts:
        - name: cache-1
          mountPath: /cache-1
        - name: cache-2
          mountPath: /cache-2
      volumes:
      - name: cache-1
        emptyDir:
          medium: Memory
      - name: cache-2
        emptyDir:
          medium: Memory

The intention of this script is to use up memory to the point that Node memory usage is in the hard eviction threshhold boundary to cause the kubelet to start to evict. It evicts some BestEfforts Pods, but in most cases the workload is killed before all BestEffort Pods are evicted. Is there a better way of doing this?
I am running on GKE with cluster version 1.9.3-gke.0.
EDIT:
I also tried using simmemleak:
apiVersion: apps/v1
kind: DaemonSet
metadata:
  name: simmemleak
  namespace: developer
spec:
  selector:
    matchLabels:
      app: simmemleak
  template:
    metadata:
      labels:
        app: simmemleak
    spec:
      containers:
      - name: simmemleak
        image: saadali/simmemleak
        resources:
          requests:
            memory: 1Gi
            cpu: 1m
          limits:
            cpu: 1m

But this workload keeps dying before any evictions. I think the issue is that it is being killed by the kernel before the kubelet has time to react.
Comment: Did you change the eviction policy in any way? By the way the question is really interesting, I follow.
Comment: @GalloCedrone no it's a normal GKE cluster and I'm not using any PriorityClasses - yeah I thought it would be easier to make it work that I'm finding
Answer: To avoid system OOM taking effect prior to the kubelet eviction, you could configure kubepods memory limits --system-reserved and --enforce-node-allocatable Read more.
For example, Node has 32Gi of memory, configure to limit kubepods memory up to 20Gi
--eviction-hard=memory.available<500Mi

Answer: I found this on the Kubernetes docs, I hope it helps:
kubelet may not observe memory pressure right away
The kubelet currently polls cAdvisor to collect memory usage stats at a regular interval.
If memory usage increases within that window rapidly, the kubelet may not observe MemoryPressure fast enough, and the OOMKiller will still be invoked.
We intend to integrate with the memcg notification API in a future release to reduce this latency, and instead have the kernel tell us when a threshold has been crossed immediately.
If you are not trying to achieve extreme utilization, but a sensible measure of overcommit, a viable workaround for this issue is to set eviction thresholds at approximately 75% capacity.
This increases the ability of this feature to prevent system OOMs, and promote eviction of workloads so cluster state can rebalance.
==EDIT== : As there seems to be a race between OOM and kubelet, and the memory allocated by your script grows quicker than the time Kubelet takes to realise that the pods need to be evicted, it might be wise to try to allocate memory more slowly inside your script.
Comment: Yeah I've read this and this is the problem I think I've encountered as described at the end of the edit - I'm looking for an example that stays within the eviction threshold long enough for the kubelet to take notice without the kernel's OOM killer taking action
Comment: sorry but it doesn't really help, I've tried lots of variations including slowing down memory allocation. I'm aware of the high level goal, it's coming up with an actual example that works that I'm struggling with


Prove $\sum_{k=0}^\infty\frac{\sin(\frac{\pi k}4)}{k!\sqrt{2^k}}\pi^k=\sqrt{e^\pi}$

Question: $$\sum_{k=0}^\infty\frac{\sin(\frac{\pi k}4)}{k!\sqrt{2^k}}\pi^k=\sqrt{e^\pi}$$
Prove that the value of lhs is equal to given value of rhs side. Help me with this doubt I am unable to find out what to do in this question
Comment: Welcome to MathSE! Please see [how to ask a good question](https://math.meta.stackexchange.com/questions/9959/how-to-ask-a-good-question). It's better to show your attempt in the post. What progress did you achieve? Where were you "stuck"? Please refrain from using pictures. There are [different reasons](https://math.meta.stackexchange.com/a/34123/1273570) for that, for example, the search function doesn't see them. Use [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) instead.
Comment: Please don't use pictures of text or formulas. See
[here](https://math.meta.stackexchange.com/questions/34121/why-image-cannot-be-used-for-explaining-my-maths-problem),
why. Use MathJax. Here is a
[tutorial](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference).
Furthermore, try to avoid expressions like "doubt", "urgent help", "I am unable" etc. Use mathematical terms instead.
Answer: The $k!$ and the $k$th power terms should remind you of Taylor series of $e^x$. The only obstacle is the $\sin(\frac{\pi k}{4})$ term, but it can be easily written as a power function. $e^{i\theta}=\cos\theta+i\sin\theta$, so we can simply write it as $\text{Im} (e^{i\frac{\pi k}{4}})$.
So the sum becomes $$lhs=\text{Im} \sum\frac{e^{i\frac{\pi k}{4}}\left(\frac{\pi}{\sqrt 2}\right)^k}{k!}=\text{Im}\sum\frac{\left(e^{i\frac{\pi}{4}}\frac{\pi}{\sqrt 2}\right)^k}{k!}$$
$e^{i\frac{\pi}{4}}=\cos\frac{\pi}{4}+i\sin\frac{\pi}{4}=\frac{1}{\sqrt 2}+\frac{i}{\sqrt 2}$, so
$$lhs=\text{Im}\sum\frac{\left(\frac{\pi}{2}+\frac{i\pi}{2}\right)^k}{k!}=\text{Im}(e^{\frac{\pi}{2}+\frac{i\pi}{2}})=\text{Im}(ie^\frac{\pi}{2})=e^\frac{\pi}{2}=\sqrt{e^\pi}=rhs.$$
Comment: Correct - but I and others in the community would rather you did not rush to answer pure "do this" questions where the OP shows no work of their own. See the comments on the question.
Comment: @EthanBolker Umm, I never thought about that. Sure, I'll take that into consideration in the future! Thanks.


Differences between .NET network tracing levels

Question: I'm trying to understand what the different output is for the various .NET Network tracing levels documented here:
http://msdn.microsoft.com/en-us/library/ty48b824.aspx
It states only what the possible values are, and not what the differences are.

Required  String attribute. Sets the
  verbosity of the output. Legitimate
  values are Critical, Error, Verbose,
  Warning, and Information.
This attribute must be set on the  element of the
  element as shown in the example. An
  exception is thrown if this attribute
  is set on the  element.

I would like to basically log all events to my log.
Answer: I understand this to be heirarchical. Meaning Critical logs only critical, Error logs Critical and Error, Verbose logs verbose and critical and Error, etc.
so Informational would log everything.


How to license an application developed in C#

Question: I am developing a software using C Sharp 2008 Express Edition and i am almost done with it.
Now I need to license the software (commercial use) I am very new to licensing softwares.
Can u suggest me a good licensing tool ?
Thanks in advance.
Comment: What are your goals with this license?
Comment: I'm voting to close this question as off-topic because licensing and legal issues
Comment: What kind of license? Commercial only? Personal use and commercial?
Comment: A slight language nitpick: "software" is not a countable noun.
Comment: Explain your question if you want a good answer...
Comment: @reinierpost - it seems that "software" is being increasingly used as a synonym for "program". In which case "softwares" and "a software" would be acceptable usages.
Comment: @ChrisF: I see this a lot from French speakers, presumably "software" is countable in French
Answer: There are many good licensing libraries (for example, http://ellipter.com/) available for generally low prices, most of which implement the standard try/buy features: limited trial periods, limited number of trial uses, license keys with encoded information, etc.
Answer: You don't need a license to be able to distribute any software you write, but you should have something that says what rights your users have.
Are you asking about how your users install your software?. If that's the case you can use the built in ClickOnce mechanism to build the installation program, or use one of the many other installation systems out there. Each has advantages and disadvantages - you need to decide what you want the installer to do and choose one that meets these requirements.
Or are you asking about a mechanism to track who has your software installed or a way to prevent unauthorised users installing your software? If that's the case then building your own is probably a bad idea as you'll hit problems that others have already solved. Again there are many systems out there that will help you with this, though as before each has plus and minus points which you need to be aware of. Without knowing what you want it's not really possible to advise you.
Comment: F
Thnks for your response.

I need to find a suitable method to track who has my software and also a way to prevent unauthorised users installing my software

Thanks in advance
Answer: The language that you wrote your software in has no bearing on the license you would choose.
If you want others to be able to modify and distribute the code as well as the license, choose something from the Open Source Initiative:
http://www.opensource.org/licenses/category
Read through a couple of them to get an idea of the kinds of things you should consider when licensing software (commercial or otherwise).
If you want to force others to share any modifications back with you, the standard license is the GPL.
If you do want your users to have a maximum of freedom (my words--maybe controversial) then choose something like Apache 2.0 or BSD.
Here is a link to the Microsoft Word license to give you an idea of the other side of the fence (definitely no sharing):
http://www.microsoft.com/downloads/details.aspx?FamilyId=4285D6F7-DFDD-44A6-A21D-8E9899082B15&displaylang=en


I.V.P $y'=\sin(e^{y}), y(0)=a$

Question: Is the I.V.P:
$$\begin{cases}
\dfrac{dy}{dx}=\sin(e^{y})\\[8pt]
y(0)=a
\end{cases}
\text{ where } a\in \mathbb{R}$$
a) Find the values of $a$ for which $y(x, a)=0$
b) Prove that if $a=0$ then $0<y(x,a)<\ln(\pi)$,  (for $x>0$)

I try this:
$$y(x,a)=0=a+\int_{0}^{x}f(t,y(t))dt$$
$$a=-\int_{0}^{x}f(t,y(t))dt$$
Is this correct?
Comment: [Help with P.V.I](http://math.stackexchange.com/questions/598467/help-with-p-v-i), and btw, it's IVP.
Comment: sorry, already corrected
Answer: Hint for (a): if $y$ is constant, $\dfrac{dy}{dx} = 0$.
EDIT: Now that you have (a), you know that one of the constant solutions is $y=\ln(\pi)$.
Use the fact that two different solutions can't meet (because of the Existence and Uniqueness Theorem) to get one of the inequalities.  For the other one: what is the sign of $dy/dx$ at $x=0$?  How could $dy/dx$ ever change signs?
Comment: ok, I try this: $$sin(e^y)=0$$
$$e^{y}=n\pi$$ evaluate in x=0:
$$e^{y(0)}=n\pi$$
$$y(0)=Ln(n\pi)$$
$$a=Ln(n\pi)$$ is correct?
Comment: Yes, that is correct.
Comment: to subsection b as could start?
Comment: dy / dx would be positive? and $2n\pi<e^y<(2n+1)\pi$ ?
Comment: in this way you find only the trivial solutions (the constant solution) with the initial condition $y(0)=a$ (trivial) and not the values $a$ for which $y(x,a)=0$.
Comment: @RobertIsrael I don't understand you answer...can you explain?
Answer: The problem describes an autonomous system $y'=f(y)$ with $y(0)=a$ and $f(y(x))=\sin(e^y)$.
The trivial solutions are immediately known because they are the constant solutions:
$$
y_k(x)=\ln(k\pi)\qquad k=1,2,\ldots
$$
To find the nonconstant solutions we may separate the variable and integrate:
$$
\int \frac{\operatorname{d}y}{f(y)}=\int \operatorname{d}x
$$
that is
$$
\int_{y_0}^y \frac{\operatorname{d}u}{\sin(e^u)}=x-x_0
$$
Note that the integration may be hard if not impossible to carry out. So it may not be possible to use the analytical technique.
So we have to use other techniques to study the behaviour of the solutions.
The equilibria or constant solutions of this differential equation are the roots of the equation $f(y)=\sin(e^y)=0$ that is
$$
y(x)=\ln(k\pi)\qquad \forall x\in\Bbb{R},\;k=1,2,\ldots
$$
Using the existence and uniqueness theorem, these constant solutions will cut the entire plane (where the solutions live) into independent regions. This means, if an initial condition belongs to one of the regions, then the solution satisfying the initial condition will stay in that region all the time.
The graph of $f(y)=\sin(e^y)$ is given below

We see that

if $y(x)$ is a solution satisfying $-\infty < y(0) < \ln(\pi)$, then $y(x)$ is always increasing;
if $y(x)$ is a solution satisfying $\ln(\pi) < y(0) < \ln(2\pi)$, then $y(x)$ is always decreasing;
and so on.

Using the above results, we know that for the given initial condition, $y(x)$ is increasing if $-\infty < y(0) < \ln(\pi)$ and for every $x$ we have
$$
-\infty < y(x) < \ln(\pi).
$$
Oberving that $\lim_{x\to-\infty}y(x)=-\infty$ and $\lim_{x\to +\infty}y(x)=\ln(\pi)$ and that $y(x)$ is increasing forall $x$, then $y(x,a)$ will have a unique root $y(x,a)=0$, for all $x$, if $a=y(0)$ is such that $-\infty < a< \ln(\pi)$. And if $a=y(0)=0$ obviously $0<y(x)<\ln(\pi)$ for $x\ge 0$.
If $y(x)$ is a solution satisfying $\ln(\pi) < y(0) < \ln(2\pi)$, then $y(x)$ is always decreasing and $\lim_{x\to-\infty}y(x)=\ln(2\pi)$ and $\lim_{x\to +\infty}y(x)=\ln(\pi)$, that is $\forall x\in\Bbb{R},\;\ln(\pi) < y(x) < \ln(2\pi)$.
And so on you can proceed for all the intervals determined by the critical points.
In the graph below you can see the behaviour of $y(x)$ for $x\ge0$ and for different values of $a=y(0)$.
Answer: This IVP enjoys existence and uniqueness of solutions. Also, its solution is global (i.e., defined in the whole of $\mathbb R$) as the flux function $f(y)=\sin(\mathrm{e}^y)$ is bounded.
The solutions $\varphi=\varphi(x)$ of IVP of scalar autonomous ODEs (i.e., of the form $y'=f(y)$, $\,y(0)=y_0$) with smooth flux have the following properties:
a. If $f(y_0)=0$, then $\varphi(x)=y_0$, for all $x$. This is due to the fact that indeed that constant function is a solution, and the IVP enjoys uniqueness.
b. If $f(y_0)>0$ (corresp. $\,f(y_0)<0$), then $\varphi$ is everywhere strictly increasing (corresp. strictly decreasing), and in particularly $\varphi'(x)>0$ (corresp. $\,\,\varphi'(x)<0$ ) for all $x$, otherwise the derivative of $\varphi$ would vanish, say at $x_0$, which means that $f(\varphi(x_0))=0$, and hence $\varphi$ would also be a solution of the IVP
$$
y'=f(y), \quad y(x_0)=\varphi(x_0),
$$
which is satisfied by the constant function $\psi(x)=\varphi(x_0)$. Contradiction.
c. If $a<y_0<b$ and $f(a)=f(b)=0$, then $a<\varphi(x)<b$, for all $x$. Otherwise $\varphi$ would cross $a$ or $b$ and its derivative would vanish there.
In our case $f(y)=\sin(\mathrm{e}^y)$, the IVP with initial condition $y(0)=a$, has a constant solution iff $\sin(\mathrm{e}^a)=0$, equivalently $a=\log k\pi$, for some positive integer $k$. Otherwise the solution $\varphi$ satisfies the inequalities $y_1<\varphi(x)<y_2$, where $y_1$ and $y_2$ are consecutive roots of $f$, and $a$ lies in $(y_1,y_2)$.

I.V.P $y'=\sin(e^{y}), y(0)=a$


How do I remove the ellipsis button in the pager?

Question: I have a view with video and have replaced the links to different pages with a button. However, when there are many videos, an ellipsis (...) appears floating, and I want to remove it. I have the View with full pager but I don't see how to control this to hide it. Thanks!
Comment: This question has already been answered:
[http://drupal.stackexchange.com/questions/9825/in-drupal-7-how-to-override-theme-pager][1]

  [1]: http://drupal.stackexchange.com/questions/9825/in-drupal-7-how-to-override-theme-pager
Answer: GO to the menu /admin/config/user-interface/pagerer and edit your pagerer
and in Separators -> Configure separators text. remove the (...)
Answer: Create a theme_pager override in your theme's template.php
function MYTHEME_pager($variables) {
  $tags = $variables['tags'];
  $element = $variables['element'];
  $parameters = $variables['parameters'];
  $quantity = $variables['quantity'];
  global $pager_page_array, $pager_total;

  // Calculate various markers within this pager piece:
  // Middle is used to "center" pages around the current page.
  $pager_middle = ceil($quantity / 2);
  // current is the page we are currently paged to
  $pager_current = $pager_page_array[$element] + 1;
  // first is the first page listed by this pager piece (re quantity)
  $pager_first = $pager_current - $pager_middle + 1;
  // last is the last page listed by this pager piece (re quantity)
  $pager_last = $pager_current + $quantity - $pager_middle;
  // max is the maximum page number
  $pager_max = $pager_total[$element];
  // End of marker calculations.

  // Prepare for generation loop.
  $i = $pager_first;
  if ($pager_last > $pager_max) {
    // Adjust "center" if at end of query.
    $i = $i + ($pager_max - $pager_last);
    $pager_last = $pager_max;
  }
  if ($i <= 0) {
    // Adjust "center" if at start of query.
    $pager_last = $pager_last + (1 - $i);
    $i = 1;
  }
  // End of generation loop preparation.

  $li_first = theme('pager_first', array('text' => (isset($tags[0]) ? $tags[0] : t('« first')), 'element' => $element, 'parameters' => $parameters));
  $li_previous = theme('pager_previous', array('text' => (isset($tags[1]) ? $tags[1] : t('‹ previous')), 'element' => $element, 'interval' => 1, 'parameters' => $parameters));
  $li_next = theme('pager_next', array('text' => (isset($tags[3]) ? $tags[3] : t('next ›')), 'element' => $element, 'interval' => 1, 'parameters' => $parameters));
  $li_last = theme('pager_last', array('text' => (isset($tags[4]) ? $tags[4] : t('last »')), 'element' => $element, 'parameters' => $parameters));

  if ($pager_total[$element] > 1) {
    if ($li_first) {
      $items[] = array(
        'class' => array('pager-first'),
        'data' => $li_first,
      );
    }
    if ($li_previous) {
      $items[] = array(
        'class' => array('pager-previous'),
        'data' => $li_previous,
      );
    }

    // When there is more than one page, create the pager list.
    if ($i != $pager_max) {
      if ($i > 1) {
        $items[] = array(
          'class' => array('pager-ellipsis'),
          'data' => '…',
        );
      }
      // Now generate the actual pager piece.
      for (; $i <= $pager_last && $i <= $pager_max; $i++) {
        if ($i < $pager_current) {
          $items[] = array(
            'class' => array('pager-item'),
            'data' => theme('pager_previous', array('text' => $i, 'element' => $element, 'interval' => ($pager_current - $i), 'parameters' => $parameters)),
          );
        }
        if ($i == $pager_current) {
          $items[] = array(
            'class' => array('pager-current'),
            'data' => $i,
          );
        }
        if ($i > $pager_current) {
          $items[] = array(
            'class' => array('pager-item'),
            'data' => theme('pager_next', array('text' => $i, 'element' => $element, 'interval' => ($i - $pager_current), 'parameters' => $parameters)),
          );
        }
      }
      if ($i < $pager_max) {
        $items[] = array(
          'class' => array('pager-ellipsis'),
          'data' => '…',
        );
      }
    }
    // End generation.
    if ($li_next) {
      $items[] = array(
        'class' => array('pager-next'),
        'data' => $li_next,
      );
    }
    if ($li_last) {
      $items[] = array(
        'class' => array('pager-last'),
        'data' => $li_last,
      );
    }
    return '
' . t('Pages') . '
' . theme('item_list', array(
      'items' => $items,
      'attributes' => array('class' => array('pager')),
    ));
  }
}

There are two chunks you can remove:
if ($i > 1) {
  $items[] = array(
    'class' => array('pager-ellipsis'),
    'data' => '…',
  );
}

and
if ($i < $pager_max) {
   $items[] = array(
     'class' => array('pager-ellipsis'),
     'data' => '…',
   );
}


derivative of sqrt(5/(x+7))

Question: Why is it that:
$$\frac{d}{dx}\sqrt{\frac{5}{x+7}} = -\frac{\sqrt{5}}2\frac{1}{(x+7)^{3/2}}$$ (image)
???
My attempt:

It seems that somehow you end up adding 1 to 1/2 to get 3/2 in the exponent.
But why?
Comment: http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference
Answer: You may write
$$
\begin{align}
\left(\sqrt{\frac{5}{x+7}}\: \right)'&=\sqrt{5}\left(\frac{1}{\sqrt{{x+7}}}\: \right)'\\\\&=\sqrt{5}\left((x+7)^{\large-\frac12}\right)'\\\\
&=\sqrt{5}\:\left(-\frac12\right)(x+7)^{\large-\frac12-1}\\\\
&=-\frac{\sqrt{5}}2\frac{1}{(x+7)^{3/2}}.
\end{align}
$$

derivative of sqrt(5/(x+7))


How to align several assignments in vim

Question: I have this piece of C code:
options->file_extension = DEFAULT_FILE_EXTENSION;
options->config = "";
options->max_file_bytes = DEFAULT_MAX_FILE_BYTES;
options->msg_sort_type = SORT_TYPE_NONE;
options->msg_sort_buffer_max_size = DEFAULT_SORT_BUFFER_MAX_SIZE;
options->msg_sort_buffer_flush_time = DEFAULT_SORT_BUFFER_FLUSH_TIME;

Is there any easy way in vim to align this so it becomes e.g. ?
options->file_extension             = DEFAULT_FILE_EXTENSION;
options->config                     = "";
options->max_file_bytes             = DEFAULT_MAX_FILE_BYTES;
options->msg_sort_type              = SORT_TYPE_NONE;
options->msg_sort_buffer_max_size   = DEFAULT_SORT_BUFFER_MAX_SIZE;
options->msg_sort_buffer_flush_time = DEFAULT_SORT_BUFFER_FLUSH_TIME;

Or even if I wrote the first line here as
options->file_extension             = DEFAULT_FILE_EXTENSION;
options->config|<--cursor her now

Would there be a quick way to jump the cursor on the 2. line up to the = of the previous line?
Answer: I use Align and I think it does the job:

Whole file: :Align =
Visual line: <leader>t= or :'<,'>Align = (i.e. : from visual line).

There's also Tabular:

Whole file: :Tab /=
Visual line: <leader>a=

PS: Tabular seems to be the most popular choice, but I can't tell why. Is there something with it that Align doesn't do?
Comment: I personally use Tabular. I find that Align provides too many mappings. I would much prefer a ex-command approach with named alignments. That way I could map only what I want/need.
Answer: there are alignment plugins. I use the "old?" Align
for your example, you can visual select your lines, and press <leader>t= You will get your expected output.
Answer: For a quick, non-robust, vimmy, non-plugin way to accomplish this task, consider the following command
.,+6s/\(\S*\)\s*=/\=submatch(1) . repeat(' ', 15 - len(submatch(1))) . '='

Analysis by component:
.,+6s

substitute command over the appropriate range
/\(\S*\)\s*=/

Pattern (regular expression) designed to match LHS of assignment (as many non-space characters as possible followed by as many space characters as possible followed by an assignment operator (=))
\=

Starts the "sub-replace-expression" context.  Vim will "evaluate" the expression and use it to replace the matched text.
submatch(1) .

In the "sub-replace-expression" context, submatch(1) will be replaced with the first submatch (similar to \1).  The . is the concatenation operator.
repeat(' ', 15 - len(submatch(1)))

This expression does the "heavy lifting" of alignment.  repeat will create a list or string depending on the first argument, the ' ' says "repeat a single space", and 15-len(submatch(1)) says "repeat it that many times."  Of course, 15 could be replaced with whatever column + initial nonspace character the assignments should be aligned at.
. '='

Puts the assignment operator back on.  Note that we can't just type =, because this is an expression, so to add it we must "concatenate it" with . '='.
I say this is "non-robust," because as is it won't work with definitions (declarations with assignments), which is probably desirable.  However, by changing the initial regular expression, a great deal of flexibility can be obtained.  It's also worth knowing, because it exposes a pretty powerful tool within vim, and can probably do a lot of good work without having to depend on a plugin.
Further reading:
:help :sub-replace-expression
:help :repeat()

Comment: Also, there may be a more elegant way to do this with printf or 'comments' or 'format-expression', but this is for me the most direct way...

How to align several assignments in vim


Dúvida em como selecionar um registro via linq

Question: Tenho uma tabela, onde eu gravo apenas scripts. Há um campo, onde eu separo se é script técnico ou script central. Há um campo TipoScript que char e é "C" ou "T". Essa tabela não foi bem feita, sem pensar no futuro, de forma que temos o campo NomeScript, que sempre tem o mesmo nome para script Técnico e o mesmo nome para script Central.
A minha consulta deverá retornar os dois scripts, mas terei que fazer a diferenciação entre ambos. Confesso não saber fazer isso. Poderia colocar assim: tecnico = sc.scripttecnico, mas a única forma de saber é pelo campo TipoScript e nomear campo como eu fiz acima, tem dado pau.
Alguém poderia me sugerir como fazer isso? Pode ser em lambda também.
Esse é meu LINQ:
public TPDV getCnpjParceiro(string cnpj)
        {
            WEBEntities db = new WEBEntities();
            TPDV pdv = new TPDV();
            List<string> lista = new List<string>();

            var resultado = (from _lista in db.T_PDV
                             where _lista.CNPJ == cnpj
                             join _st in db.T_CRM_StatusPDV on _lista.CNPJ equals(_st.DE_Cnpj)
                             join _sc in db.T_Script on _st.IT_Status equals((int)_sc.TipoStatus)
                             select new
                             {
                                 _lista.CNPJ,
                                 _lista.RazaoSocial,
                                 _lista.Endereco,
                                 _lista.CaminhoLogo,
                                 _lista.Bairro,
                                 _lista.Cidade,
                                 _st.IT_Status,
                                 _st.DT_TransacaoV,
                                 _sc.Script
                             }).ToList();

            foreach (var lis in resultado)
            {
                pdv.CNPJ = lis.CNPJ;
                pdv.RazaoSocial = lis.RazaoSocial;
                pdv.Endereco = lis.Endereco;
                pdv.CaminhoLogo = lis.CaminhoLogo;
                pdv.Bairro = lis.Bairro;
                pdv.Cidade = lis.Cidade;
            }

            return pdv;

        }

Tentei fazer assim, mas dá erro em tecnico e central
var resultado = (from _lista in db.T_PDV
                             where _lista.CNPJ == cnpj
                             join _st in db.T_CRM_StatusPDV on _lista.CNPJ equals(_st.DE_Cnpj)
                             join _sc in db.T_Script on _st.IT_Status equals((int)_sc.TipoStatus)
                             select new
                             {
                                 _lista.CNPJ,
                                 _lista.RazaoSocial,
                                 _lista.Endereco,
                                 _lista.CaminhoLogo,
                                 _lista.Bairro,
                                 _lista.Cidade,
                                 _st.IT_Status,
                                 _st.DT_TransacaoV,
                                 tecnico = _sc.TipoScript == "T" ? _sc.Script : null,
                                 central = _sc.TipoScript == "C" ? _sc.Script : null
                             }).ToList();

Comment: Está dando algum erro ?
Answer: Use models e retorne-os na sua consulta LINQ.
Model
public class Script
{
    public string TipoScript { get; set; }
    public string Script { get; set; }
}

Consulta LINQ
var resultado = from s in db.Script select s;

resultado será um IQueryable


PostgreSQL log_min_messages not working?

Question: I would like to debug my SQL code and therefore I need some logging messages. However, setting log_min_messages and client_min_messages to level NOTICE does not work as expected:
SET log_min_messages = 'NOTICE';
SET client_min_messages = 'NOTICE';

The function I am using:
CREATE FUNCTION on_insert_or_update_shop_offer()
RETURNS trigger AS $$
BEGIN
    RAISE NOTICE 'Test trigger';
    RETURN new;
END
$$ LANGUAGE plpgsql;

CREATE TRIGGER shop_offer_insert_or_update_trigger
BEFORE INSERT ON shop_offer
FOR EACH ROW
    EXECUTE PROCEDURE on_insert_or_update_shop_offer();

I have tested it by calling RAISE EXCEPTION 'Test trigger'; which appears as intended, but I am not getting NOTICE level messages.
Comment: What are you using to run the insert? Where are you looking for the messages?
Comment: @NickBarnes Not sure about the first question but I am using jOOQ, a Java library, to access the database. The insert works though. I am looking for the messages in my Eclipse Console (stdout). I assumed that those messages will be displayed there since `EXCEPTION` gets displayed there.
Comment: stdout/stderr is probably showing you the corresponding Java exception, and for a `NOTICE` or `WARNING`, there isn't one. You should be able to retrieve the messages yourself via `Statement.getWarnings()`. If you set `log_min_messages`, they'll also be in the server log.
Answer: ALTER DATABASE dbname SET log_min_messages TO notice;


Bayesian inference from "extra" information - Beta-binomial case

Question: Say we have two coins with unknown success probabilities $p_1$ and $p_2$. To know more about the probabilities, say that we use Bayesian approach.
To do so, we first set our prior: $P_1\sim Beta(1,1)$ and $P_2\sim Beta(1,1)$.
Tossing both of the coins together, we update each of the prior as usual.
For example, we ran 10 rounds of tossing, 4 Heads on coin 1 and 8 Heads on coin 2.
The posterior should be $P_1\sim Beta(5,7)$ and $P_2\sim Beta(9,3)$.
My question is that what happens if we receive an "extra" piece of information that says "$p_1$ is greater than $p_2$"
Is there any systematic way to accommodate this extra piece of information into the posterior?
Comment: You could simply constrain the support of the joint prior over $(P_1, P_2)$ to the set $\{ P_1 > P_2\}$.
Comment: The joint density for $(p_1,p_2)$ would be proportional to $p_1^4(1-p_1)^6\,p_2^8(1-p_2)^2\,\mathbf I_{[0 \le p_2 < p_1 \le 1]}$ but the marginal densities would be more difficult to express
Answer: What you're referring to in the first part of the question, is the beta-binomial model. where binomial distribution is assumed as the likelihood and beta as a prior, hence by conjugacy posterior is also a beta distribution.
Your problem description in the second part describes a different scenario because it is multivariate. If you know that $p_1 > p_2$, this means that the parameters are dependent and you are talking about some multivariate distribution for the parameters (vs two univariate beta distributions). In such a case, you cannot use two (independent) beta-binomial models. The constraint can be imposed by choosing a multivariate prior for the parameters. For such a model you won't have a closed-form solution, so you would need to use MCMC or some other kind of approximate inference.
Comment: Thank you for the answer. I got your point. So, the new information correlates the two separate inference problems and it makes the problem more complicated.. Then, alternatively, if we think about only one coin $p_1$ and if the new information is $p_1\geq 1/2$. If this is the case, what would be the resulting inference?
Comment: In our example, do we simply have $P_1\sim Beta(5,7)$ and $P_1\geq 1/2$ as the posterior? or we cannot have some thing like $P_1\sim Beta(5,7)$ as $Beta(5,7)$ has its mean lower than 1/2?
Comment: @Andeanlll I believe this thread answers your question https://stats.stackexchange.com/questions/538935/what-happens-if-i-change-the-range-of-a-flat-prior-for-bayesian-inference
Answer: For the case where you want to use the restriction $p_{1}, \geq 1/2$ your prior will be of the following form
$$\pi(p_{1})=\left\{\begin{matrix}
Beta(a,b), & p_{1}\geq 1/2 \\
0, & otherwise
\end{matrix}\right. = Trunc-Beta(a,b)$$
Hence, your posterior can be derived as
$$\pi(p_{1}|x) \propto L(p;x)*Beta(p_{1};a,b)*\mathbb{I}(p_{1}\geq 1/2) = L(p;x)*Trunc-Beta(a,b)$$
The truncated Beta distribution can be calculated in the following way restricted to the interval $[1/2,1]$
$$Trunc-Beta(a,b) = \frac{Beta(a,b)}{F(1)-F(1/2)}$$
for exact calculations you can check here https://en.wikipedia.org/wiki/Beta_distribution.
Essentially what will happen to your posterior by adding this extra information $p_{1}\geq 1/2$, is that even though your likelihood might give importance to values of $p_{1}$ less than $1/2$ your prior will make them zero, because it gives zero mass to those values less than $1/2$.
In the case where you have $p_{1}\geq p_{2}$, then your prior will be of the form
$$\pi(p_{1},p_{2}) = \left\{\begin{matrix}
f(p_{1},p_{2}), & p_{1}\geq p_{2} \\
 0,& otherwise
\end{matrix}\right.$$
and the posterior
$$\pi(p_{1},p_{2}|x)\propto L_{1}(p_{1};x_{1})*L_{2}(p_{2};x_{2})*f(p_{1},p_{2})*\mathbb{I}(p_{1}>p_{2})$$
similarly, the product of the likelihoods $L_{1}(p_{1};x_{1})*L_{2}(p_{2};x_{2})$ might give importance to cases where $p_{1}<p_{2}$ but your prior will give again zero mass to those choices.


For $x \in [0,1]$, find $F(x) = \int_0^xf(t)dt$ for each of the following functions $f$ defined on $[0,1]$.

Question: For $x \in [0,1]$, find $F(x) = \int_0^xf(t)dt$ for each of the following functions $f$ defined on $[0,1]$. In each case verify that F is continuous on $[0,1]$, and that $F'(x) = f(x)$ at all points where $f$ is continuous.
A) $f(x) = x^2 - 3x + 5$
B) $f(x) = x - \lfloor3x\rfloor$
C) $f(x) = x\lfloor3x\rfloor$
For A) I have
$\int_0^xt^2 - 3t + 5 = \frac{x^3}{3} - \frac{3x^2}{2} + 5x = F(x)$
From looking at it I just said that it's continuous everywhere and for $F'(x) = f(x)$ I just showed that $\frac{d}{dx}F(x) = F'(x) = f(x)$
 Would that be sufficient?
As for B) and C) I don't know what to do.
Answer: Hints:
$$\begin{align*}\bullet&\;\;\;x\in [0,1]\;\implies\;\lfloor3x\rfloor=\begin{cases}0&,\;\;0\le x<\frac13\\{}\\1&,\;\;\frac13\le x<\frac23\\{}\\2&,\;\;\frac23\le x<1\end{cases}\\{}\\\bullet&\;\;\;\int\limits_0^1=\int\limits_1^{1/3}+\int\limits_{1/3}^{2/3}+\int\limits_{2/3}^1\;\;\end{align*}$$
Comment: Then for B) Would I have $\frac{x^2}{2} - 2x + 1$ and for C) $x^2 - 5/18$?


Vertically center elements with a responsive way

Question: Learning about Responsive Web Design, I was wondering if there is a standard procedure to center an element(div, image, or whatever) vertically in a responsive way. Not with margin's and padding's pixels, but with a percentage way or something like that in order to have a responsive alingment result. Like horizontal align with bootstrap's center-block or centered rows and cols.
Comment: Is using flex boxes a possibility? https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes
Comment: I Searching in google a posibility?
Comment: Don't use google use bing. Here's a bunch of different techniques on how to center: http://vanseodesign.com/blog/demo/vertical-centering/padding.php this is meant to support ancient browsers too like ie8.
Answer: CSS support for display:table.

Blah


How to address HasAuthentication error in Selenium

Question: I wanted to create a test via Intellij. I have also integrated the jar files. However, when I perform the operation, I encounter a hasAuthentication error. If anyone has faced similar problem before, can you help me?
Selenium Has Authentication Error Image:
Comment: Does this answer your question? [selenium-4 - Not able to handle HasAuthentication popup with Remote driver](https://stackoverflow.com/questions/73290245/selenium-4-not-able-to-handle-hasauthentication-popup-with-remote-driver)
Answer: As per the documentation in Interface HasAuthentication if website requires any authentication through URL then the following error occurs:

Solution
To get rid of this error you need to download and integrate the selenium-api jar in your project.


Improving my descending tapping technique

Question: I find that it's very easy for me to get a clean phrase when tapping in an ascending pattern like the following:
<code>$1 7h9h12
</code>
Reversing that pattern, however, becomes hard for me:
<code>$1 12p9p7
</code>
I attribute this to two main reasons:

Often times even with a dimed high gain amp and a compressor I cannot get the first note of the reversed tap to sound out enough such that the subsequent pull offs have enough volume. I know that a compressor can help me out a little here, but I also know good clean tapping is still not 100% gadgets.
For some reason going backwards is just harder. I can descend at about 30% of the speed that I can ascend. This is true not just in tapping for me, but playing solo phrases with more than three descending notes in a line as well.

When performing an ascending phrase I make sure to bring my finger down on the strings with a little force than normal resulting in a little more volume from the note. This is just the standard hammer on technique that everyone learns. But, during a descending phrase I don't have that ability and my riffs often sound weak.
What's the trick? Should I be slightly plucking the string at that first tapped note as I come off it? I can't really discern anything additional when I watch the guitar masters tap speedy phrases.
As, a supplementary question: Is there any way to clean up the harmonics during a tap solo? You can hear what I'm talking about if you tap fretted notes on an electric guitar that isn't plugged in.
Comment: As for the cleaning up the harmonics/string noise; check out my/and the other answers to this question http://music.stackexchange.com/questions/1787/is-it-possible-to-mute-some-of-my-strings/1789#1789
Comment: Ref Above: this isn't something i do myself, but i know that some people find it useful.  Obviously not a good idea if you intend to play open strings in the solo.
Answer: Your right in your first point - in my opinion, gadgets and effects are to enhance your playing, not to provide the basis of it.
Right, back to the question. Let me make it plain that I am possibly the world's worst tapper, having only made an effort to start learning it myself recently. I have already learnt that practice is what you need to get any sort of proficiency, and am therefore practising little phrases as often as I can. By default, one of the phrases I often jump to is the one you show here.
In order to tackle the 'reverse' one, and actually make it sound decent, I do what the guy in this video (skip to 1:00) demonstrates.
Basically, after I hammer down on the 12th fret, I pull off to the side, so that I gently pluck the note as I do so. I then pull off from the 9th to 7th fret as normal, and that sounds OK.

Hammer Down on 12th Fret
Pull of to the side
Pull of the 9th fret

I just do that cycle a load of times, and then gradually speed it up.
Other people may disagree, but it works well for me anyway :)
Hope this helps!
Comment: "I pull off to the side, so that I gently pluck the note as I do so" was exactly what I was going to recommend to get the second note to sound with a little more amplitude.
Comment: Yep pulling off to the side is what will do it; i generally do this with every tapped note unless the tempo is too high for it.
Comment: @DRL What do you do in cases where the tempo is too high?
Comment: @Jduv: I cheat in those cases and I'll either switch to two hand tapping and use my left hand to start the run with a powerful hammer on, or I'll pick the first note of the run.
Comment: @Jduv - pretty much cheat as Ian says, I'm not the greatest tapper in the world
Answer: Depends what your guitar is:
On an acoustic or heavy strung electric pulling off to the side is essential, and is what I usually use.
Many of our songs have fast hammer-ons, pull-offs and tapped runs and for some of them I use an Ibanez set up really lightly, and when using a high gain amp just releasing a finger quickly is often enough.
I usually find it is easier to get a good tone the faster you go with pull-offs - ymmv.


Can different threads insert into a map if they always use different keys?

Question: I'm trying to design a message queue for an object. There is a set of X threads that can all send message (to be processed later) to this object. If I have a std::map<thread_id_t, message>, is this thread safe, assuming thread one only adds messages with a key of 1, thread 2 to key 2, etc..?
Comment: No, it is not thread-safe.
Comment: No, you need to sync access. The map is a shared resource, each call from different threads alters its state.
Comment: Do you have a link to the standard stating that? This answer: http://stackoverflow.com/a/15067564/649140 mentions that "implementations are required to avoid data races when the contents of the contained object in different elements in the same sequence, excepting vector" -- does this not apply here?
Comment: @SamKellett: That's different. What you're modifying concurrently here (by inserting new key-value pairs) is the data structure itself, not the individual elements contained in it :)
Answer: std::map is not thread safe for multiple simultaneous writers.
One of the many reasons why STL maps are not thread safe is that the underlying implementation of an STL map is an AVL tree that needs to be rebalanced every once in a while after a number of insertions. Rebalancing the map affects multiple nodes and is definitely not thread safe.
Refer to the excellent Dr. Dobb's article on lock-free data structures if any of this sounds interesting to you.
Comment: Separate vectors can be modified concurrently, yes. That said, you need to make sure that these vectors are inserted in the outer vector sequentially and linearly. If "on thread creation" means in the parent (spawning) thread, then that might be fine.
Comment: @SamKellett: actually, even that might not be advisable, unless all threads are created before any thread starts running, since any insertion might move the vectors contained in the outer vector. If you know the maximum number of threads you have, just have an array of vectors, or array of pointers to vectors-- not resizable, and perfectly accessible in parallel.
Comment: I know how many threads, but at runtime not compile time so will need to use a vector. But can guarantee that the outer vector is populated and 'frozen' before any of the inner vectors will ever be used.
Comment: Ah ok, so would something like: `std::vector>` where each thread id is mapped 1-1 to an index in the outer vector be a better idea?
Comment: You will still need to make sure that each thread ID exists in the outer vector 'a priori'. Multiple insertions in a vector are also not thread safe as they can lead to a resizing of the underlying array.
Comment: @DietmarKühl: my statement was it is "not thread safe for multiple simultaneous writers". I think that's fairly accurate, right?
Comment: @EyasSH, ok that can be done on thread-creation. So they'd be allowed to modify their own inner vector's concurrently?
Comment: If you can guarantee that-- i.e. only use `const` methods of the outer vector at any given point in time after creation, and having creation not overlap at all with thread access, then you should be all set.
Comment: That said, heap allocated arrays can also have runtime constant (and compile-time unknown) sizes :)
Answer: The general rule for classes in the standard C++ library is this: if you call a non-const method on an object (with the exception of some methods like std::vector<T>::operator[]()) you cannot have any other thread accessing this object in any way concurrently. If you need to use the operations you need to make synchronize the accesses between the different threads somehow. The relevant clauses in the standard are 188.8.131.52 [res.on.objects] paragraph 1:

The behavior of a program is undefined if calls to standard library functions from different threads may
  introduce a data race. The conditions under which this may occur are specified in 22.214.171.124.

... and 184.108.40.206 [res.on.data.races] which describes that the standard C++ library isn't allowed to do mutate objects except when a non-const member function is called on them.
Since inserting an object into a std::map<...> is clearly a non-const operations, you cannot do it concurrently from multiple threads without synchronization.


Visual Studio code formatting

Question: I've been using Visual Studio as my main IDE for a while now (I still use Emacs for some personal projects, though).
I like the way Emacs formats C/C++ code and I'd like to convince Visual Studio use similar conventions for C# code. For instance, in Emacs, a C function call looks like:
functionName(argument1,
             argument2,
             argument3);

while in the C# code formatted by Visual Studio a function call looks like:
functionName(argument1,
    argument2,
    argument3);

which seems worse to me.
Is there a way to tweak Visual Studio code formatting rules? Any plugins that can handle that?
Many thanks,
Answer: Tools > Options > Text Editor > C# > Formatting
and
http://www.jetbrains.com/resharper/features/code_formatting.html#Code_Formatting
Comment: Thanks, but while that allows many customizations, I can't see a way to solve the problem in my example. It's just a minor nuissance, though.
Comment: Thanks for the suggestion, that's what I do sometimes, but it 'wastes' a line.

However I'm a bit annoyed because I consider the Emacs default formatting better (I bet I would feel the other way around if I had used Visual Studio before Emacs :-) )
Comment: One man's 'waste' is another man's clear code.  Sorry I don't have other ideas except maybe writing a VS macro for this particular bugbear.
Comment: You could also drop the first argument to the next line which would make all arguments align.
Answer: Resharper (above) is good.  CodeRush is now free from DevExpress.  I've enjoyed using their products over the years.
http://www.devexpress.com/Products/Visual_Studio_Add-in/CodeRushX/
Answer: See also this extension that will automate the process each time a file is saved : https://visualstudiogallery.msdn.microsoft.com/3ea1c920-69c4-441f-9979-ccc2752dac56

Visual Studio code formatting


Is composition of analytic function with invertible function analytic?

Question: The Cayley transform $\psi(z)=i\frac{1-z}{1+z}$ maps the unit disk $\mathbb{D}=\{z\in \mathbb{C}\colon |z|<1\}$ conformally onto the upper half plane $\mathbb{U}=\{z\in \mathbb{C}\colon \textrm{Im}(z)>0\}$. The map $\psi$ is invertible.
On the other hand if we consider a function $f\colon \mathbb{U}\to \mathbb{C}$ which is analytic. My question is: Will $f\circ \psi$ be an analytic function?
Comment: Take any invertible nonanalytic function and compose it with the identity.
Answer: Edit: in an edit, OP substantially changed the question so my answer below no longer answers the question. To answer the new question: $\psi$ is conformal, so in particular it is holomorphic and analytic.  Hence the composition $f\circ \psi$ is a composition of two analytic functions, and therefore again analytic. This however has everything to do with $\psi$ being analytic, and nothing to do with it being invertible.
Original answer:
On $\mathbb{C}$ the map $z\mapsto \bar{z}$ is invertible. If $f\colon\Omega\to\mathbb{C}$ is analytic on $\Omega$ it is holomorphic, but the composition with $z\mapsto \bar{z}$ will not be holomorphic, and hence not analytic.
Answer: Take the following invertible function $f_w:\Bbb R\to\Bbb R$ with $w\in\Bbb Q\!\setminus\!\{0\}$:
$$f_w(x) = \begin{cases}
x, & x\in\Bbb R\setminus\Bbb Q \\
x+w, & x\in\Bbb Q
\end{cases}$$
then $f_1$ is invertible with $f_1^{-1} = f_{-1}$, and $f_1$ is not analytic. Take $g(x)=x$ as analytic function, then neither $f_1\circ g$ nor $g\circ f_1$ are analytic.
This works actually for any such $w$.


Definition of monotonic function

Question: By monotonic function, we refer to an increasing function over $X \subseteq \mathbb{R}$. Why is the definition of monotonic function always $f(x) \geq f(y) \implies x \geq y$ instead of $x \geq y \implies f(x) \geq f(y)$?
Let's say $f$ is increasing according to the definition: $f(x) \geq f(y) \implies x \geq y$. Suppose, for the sake of contradiction, there's some $x, y \in X \ (x \geq y)$ such that $f(x) < f(y)$. From the definition, we have $f(x) < f(y) \implies x \leq y$. This can only mean that $x = y$ but then, we can't have $f(x) < f(y)$, and hence we arrive at a contradiction. Thus, the first definition implies the second.
Comment: Is a  constant function montonic according to your defintion?
Comment: Classic definition of increasing function is exactly second case https://en.wikipedia.org/wiki/Monotonic_function.
Comment: @zkutch I don't think you read the question correctly.
Comment: The two are definitions equivalent  for bijective functions but the second one is  a bad definition in general.
Comment: @geetha290krm Yes, a constant function is monotonic according to my definition.
Comment: No. $f(x) \ge f(y)$ **for all $x$ and $y$** if $f$ is a constant function. So it is not monotonic according to the second definition.
Comment: @geetha290krm A constant function still satisfies the second definition, right? So why do you say that it is not monotonic according to the second definition?
Comment: $f(1)\ge f(2)$ if $f$ is a constant function. But $1 \ge 2$ is false. Think before posting comments.
Comment: @geetha290krm Thank you. I now see what you mean.
Comment: @geetha290krm, I had in view second sentence i.e. first one where word definition appears.
Answer: $$f(x)\ge f(y) \Rightarrow x\ge y$$
is equalivalent to
$$x<y\Rightarrow f(x)<f(y)$$

Definition of monotonic function


regression - does R2 only apply to measure linear regression performance?

Question: Background
According to Wiki: https://en.wikipedia.org/wiki/Coefficient_of_determination, $R^2$ is coefficient of determinant. The definition is
$$
R^2 = 1 - \dfrac{SSE}{SST}
$$
Since $SSE$ is simply sum of square of residuals, it does not hurt to be used for nonlinear regression. And I have seen a lot of people doing so, although the adjusted version might be difficult to justify in the nonlinear regression case.
Where is the different voices
So the only trick thing is that, for nonlinear regression in general,
$$
SST \neq SSR + SSE
$$
so one can say well, the coefficient of determination might be out of the bound of [0,1]. So there is no such definitino. However, I would say does adjusted $R^2$ in linear regression really guarantee the boundness?
So the key part that ensures the above variance equality is that one would need the following
$$\sum_{i}(y_i - \hat{y}_i) (\hat{y}_i - \overline{y})^\top  = 0$$,
where $y$-ish follows the linear regression style so it is a row vector.
It can be decomposed into two parts
$$
\sum_i (y_i - \hat{y}_i) \hat{y}_i = 0
$$
$$
\sum_i (y_i - \hat{y}_i) \overline{y} = 0
$$
The second one is always true if $\hat{y} = \alpha  + g(x;\beta)$, where $g$ is a function parameterized by $\beta$. Then any extreme point along $\alpha$ would satisfy the second one.
The first one is a bit tricky.
However, its meaning is quite simple: simply have error residual uncorrelated in the linear sense with prediction over the training distribution. Careful readers might notice that I miss an expectation, however, remember the second one holds, so it naturally absorbs.
This makes sense for some cases. Imagine if residual is correlated with prediction in the linear sense, then it means there is still space for improvement for a more complicated nonlinear model. Indeed, see equation 21 of the God of SI: Billings's paper. In that sense, a well trained nonlinear model should approximately have the $$SST  \approx SSR + SSE$$
Another voices
There is some research paper showing that only looking at $R^2$ for nonlinear models does not always let you pick the best model, which is certainly acceptable. It depends on what you think is true and I don't think unless, for obvious comparison, it is often difficult to discern two models that performs similarly. Personally, I also have some experiences that finding in nonlinear models $R^2$ around 0.90 does not give me much good results due to data imbalance. So I use other metrics to tell the difference jointly.
Question:
Does it make sense? Can $R^2$ be used for nonlinear regression? My preference is yes we can use it but with caution and better have the scatter plot
Comment: I calculate R-squared as "1.0 - (absolute_error_variance / dependent_data_variance)" and use it to tell me what fraction of the dependent data variance is explained by the model. If the R-squared is 0.95, I interpret this to mean that the model explains 95% of the variance in the dependent data. I understand that R-squared is exact for straight line models and approximate for other models, and with this caveat in mind I understand it to be a widely used fit statistic for both linear and nonlinear modeling.
Comment: @JamesPhillips Yes. There is a choice to be made since $SST \neq SSR + SSE$. Your choice is the same made by Scikit-learn Python Packages.
Answer: In my experience $R^{2}$ is not suited to assess non-linear regression models.
The fact that $SST \neq SSR + SSE$ can lead to a number of problems, some of which you have already pointed out and are contained in the research paper you referenced.
While I was working on my thesis, I also tried to evaluate non-linear regression models using $R^{2}$. This resulted in many deeply negative values. Initially, I attributed this to my models being misspecified. However, even as I managed to improve some of the models (according to some other metrics) the $R^{2}$ value did not indicate this. Therefore I could not rely on $R^{2}$ to distinguish models that performed well from ones that were horrid. The paper you referenced goes further than to state that you do not always pick the right model, it goes on to state you will pick the wrong model more often than not.
To answer your question: "Can we use it?". Of course you can use it, many statistical packages will allow you to compute it with ease. However, I think that it will not be very useful.
Comment: Unlike RMSE and MSE, the R-squared value has no units. This is one of the reasons it is both widely used and widely understood, giving the same understanding of model performance whether the units are micro-liters or light-years with the caveat that it is approximate for models other than straight lines.
Comment: I have a hard time accepting the initial statement about "not suited," because when the loss function is quadratic, then SSE or (equivalently) $R^2$ is *exactly* the right measure to be evaluating!  Thus, my interpretation of the rest of your post is that your experience comprises situations with non-quadratic loss functions.  In other words, you are stating $R^2$ is not suited because of how you implicitly measure model performance.  That looks like a key point to emphasize.
Comment: I don't have much metrics to add to that:                                                    This [source](http://statisticsbyjim.com/regression/standard-error-regression-vs-r-squared/) advises to use the standard error of the regression. Although using RMSE or MSE should do as well, as the idea is similar. Better models should lead to smaller errors.
Comment: If we take $R^2=1-\frac{SSE}{SST}$, as usual, I have to believe that minimizing $SSE$ is the same as maximizing this$R^2$. Maximizing the proportion of variance explained by the model, though, would be a different story.
Comment: Thank you for your comment. Can you share the other metrics that you are using? Say standard error of regression? RMSE?
Comment: I agree that SSE is what should be evaluated in such a case, but computing $R^{2}$ does not only rely on SSE to my understanding. Do you think that it does not matter that $SST \neq SSR + SSE$ ? As far as I understand, this can lead to issues. By "not suited", I don't wish to imply that it is utterly useless, but rather that in the case of non-linear models some of the underlying assumptions do not hold.
Comment: @FelixvanDoorn I wonder if it is the case that maximizing $R^2$ and minimizing $SSE$ are equivalent, even for nonlinear regression, but that $R^2$ simply lacks the "proportion of variance explained" in the nonlinear case.
Comment: @Dave On an intuitive level, this explanation resonates with me.
That being said, I'm not sure about maximizing $R^{2}$ and minimizing $SSE$ being equivalent in a non-linear setting.
Given that $SST \neq SSR + SSE$, I'm not sure we can guarantee equivalence here. Or do you think this need not be an issue for proving this?
Comment: I see what you mean! Yes, that does make sense.


Por que o "this" é necessário na função construtora

Question: Gostaria de entender o motivo de o "this" ser necessário dentro de uma função construtora. Ele não deveria ser necessário somente após criar o objeto?
Exemplo abaixo:
function Data(dia = 1, mes = 1, ano = 1) {
  this.dia = dia;
  this.mes = mes;
  this.ano = ano;

  this.exibir = function() {
      return `${this.dia}/${this.mes}/${this.ano}`;
  }
}

Comment: Não é necessário para o "construtor", é "necessário" para  a sua necessidade especifica de passar os valores dos parâmetros para serem acessadas pelos métodos. Apesar que da forma que você criou o método `exibir()`, nem precisaria, já que `dia`, `mes` e `ano` (sem o `this.`) são acessíveis por ele. Resumindo, this é só necessário no construtor conforme a sua necessidade. Rodrigo e @AugustoVasques, talvez amanhã, isso se ninguém tiver feito uma resposta explicando de fato isso.
Comment: O valor do `this` dentro de uma função varia de acordo com a forma como a função é chamada. Se ela é chamada como um construtor (ou seja, com `new`), o `this` passa a ser a instância sendo construída. Então não é que "precisa" ser assim, na verdade vc avalia como a função vai ser usada e o que precisa fazer, e vê se usar `this` é o mais adequado para cada caso. Ver mais [aqui](https://pt.stackoverflow.com/q/445939/112052) e [aqui](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this#this_in_function_contexts)
Comment: Quando a função é usada com um construtor sua propriedade [`this`](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Operators/this#como_um_construtor_(constructor)) é vinculada ao novo objeto sendo construído.
Answer: O this faz referencia ao próprio objeto.
Quando você digita:
this.dia = dia;

você está criando um atributo dia para seu objeto e esta salvando o valor de dia neste atributo.
Apos o objeto criado, você não usará mais o "this" e sim a instancia do Objeto, exemplos:
function Data(dia = 1, mes = 1, ano = 1) {
    this.dia = dia;
    this.mes = mes;
    this.ano = ano;

    this.exibir = function() {
        return `${this.dia}/${this.mes}/${this.ano}`;
    }
}

var isntancia = new Data()
console.log(isntancia.dia)


Symfony Form Field Valid Even With Errors?

Question: I have applied a form error to a form collection field (custom fieldset).
if ($this->isFieldset($form, $field) && !empty($error)) {
    $form->get($field)->addError(
        new FormError(
            ucfirst(str_replace('_', ' ', $field)) . ' is invalid.')
        );
}

The form has an error applied to it but is still marked as valid?

As you see in the controller the form has the errors on the about_you child before isValid is called?

Any suggestions why?
Comment: Did you add your array before or after calling `$form->isValid()`?
Comment: Have you tried writing a test for the custom fieldset or just created a form from that and then call getErrors()/isValid() in a controller?
Comment: Yes I add them when the form is first created (in an overridden form factor class which pull out the erros from Redis and adds them back to the form).
Answer: I dug through the code and found this snippet:
public function buildView(FormView $view, FormInterface $form, array $options)
{
   //...

    $view->vars = array_replace($view->vars, array(
        'errors' => $form->getErrors(),
        'valid' => $form->isSubmitted() ? $form->isValid() : true,  //<=== HERE
        'value' => $form->getViewData(),
        'data' => $form->getNormData(),
        'required' => $form->isRequired(),
        'size' => null,
        'label_attr' => $options['label_attr'],
        'compound' => $form->getConfig()->getCompound(),
        'method' => $form->getConfig()->getMethod(),
        'action' => $form->getConfig()->getAction(),
        'submitted' => $form->isSubmitted(),
    ));
}

This seems to be the only place where valid is set. Note that it happens during buildView! Everything afterwards will not effect the value of valid.
However, not everything is in vain as you can simply use $form->isValid() to check, if the form is currently valid, as we can see in the following snippet:
public function isValid()
{
    if (!$this->submitted) {
        return false;
    }

    if ($this->isDisabled()) {
        return true;
    }

    return 0 === count($this->getErrors(true));
}

Comment: I think this answer is misleading. The problem is definitely not in the FormView as can be seen on the attached image in question. The breakpoint is set before `createView()` is called and shows the Element\Form (not FormView) with the error. At that line a call to `isValid()` is made. When stepping to the next line the if block should be skipped. @Kal can you confirm this happens?
Comment: To be honest I don't know.. I just saw your updated question and it seems to me, that you actually *do* call `createView()` at the very end. Is your output from before that?
Comment: So I could override buildView in my form and manually set it? I am doing something weird which is why I am getting unexpected behavior.
Comment: You actually got me on the righ trackt. I overridden the buildView method and checked the form field for errors so thanks :)


SwiftUI & iOS 13.3 TupleView initializer stop working. what happens to it?

Question: I have such inits with ViewBuilders with TupleView
 // MARK: TupleView support
    public init(@ViewBuilder content: () -> TupleView<(A, B)>) {

        let views = content().value

        self.childs = [AnyView(views.0), AnyView(views.1)]

    }

Code works great, but starting from new Xcode 11.3 update (iOS 13.3) this code stopped working, and constructor with TupleView is not executed.
Here is how I use MenuView with such initializer:
MenuView {
        DashboardView()
        .withTag(0)
        .tabBarItem {
            TabItemView(imageName: "Dashboard", title: "Home")
        },

        ContactsView(companyId: self.getCompanyId())
        .withTag(1)
        .tabBarItem {
            TabItemView(imageName: "Contacts", title: "Contacts")
        }

}
But now it doesn't work this @ViewBuilder and do not I think call ViewBuilder.buildBlock() correctly and this argument is recognized as call to
public init<Content: View>(@ViewBuilder content: () -> Content>) { }

I found the workaround, but it is very ugly code and it is far away how we can use native TabView for instance.
 MenuView {

            ViewBuilder.buildBlock(
            DashboardView()
            .withTag(0)
            .tabBarItem {
                TabItemView(imageName: "Dashboard", title: "Home")
            },

            ContactsView(companyId: self.getCompanyId())
            .withTag(1)
            .tabBarItem {
                TabItemView(imageName: "Contacts", title: "Contacts")
            }
  )
}

Comment: show your application examples please.
Comment: Ok I do this later. I found solution but it is far from ideal it is rather hack. But if I be in front of my macbook I provide more details and samples
Comment: I've added more explanations and code examples. To the problem. I think that for some reasons ViewBuilder.buildBlock is not correctly executed implicitly and I need to do this explicitly.
Answer: When you use MenuView, you have to add a TupleView?
  MenuView {

         TupleView((
        DashboardView()
        .withTag(0)
        .tabBarItem {
            TabItemView(imageName: "Dashboard", title: "Home")
        },

        ContactsView(companyId: self.getCompanyId())
        .withTag(1)
        .tabBarItem {
            TabItemView(imageName: "Contacts", title: "Contacts")
        }))

    }


Outlook 2013 displaying "We removed extra line breaks from this message" while is sent in unix using "."

Question: Just want an explanation about an issue (that is already resolved) about sending an email in unix and outlook is displaying in the email "We removed extra line breaks from this message"
I send an email with file names using a loop from an array and those are enumerated as follow:
subject="test"
file_index=0
while [ ${file_index} -lt ${#FILES[@]} ]
   do
      body_message=${body_message}"$(( ${file_index} + 1 )). ${FILES[${file_index}]}\n"
      file_index=$(( ${file_index} + 1 ))
   done

EMAIL OUTPUT:
1. File1.txt 2.file.txt file3.txt

the output is not doing the breakline and is putting it all together and outlook display the message ""We removed extra line breaks from this message"
the issue that cause that message in outlook is the line in $(( ${file_index} + 1 )). to be exactly is the "." dot.
I tried the same way but changing it to ".-" and that way is working without any issues, you can see it below.
subject="test"
file_index=0
while [ ${file_index} -lt ${#FILES[@]} ]
   do
      body_message=${body_message}"$(( ${file_index} + 1 )).- ${FILES[${file_index}]}\n"
      file_index=$(( ${file_index} + 1 ))
   done

EMAIL OUTPUT:
1.- File1.txt
2.- File2.txt
3.- File3.txt

using just ".-" not affect that, I would like to understand why if I use a single dot it display bad the email in outlook.
Thanks.
Answer: Send the message in the HTML format - this way Outlook won't mangle the message body.
As for your question, the exact algorithm Outlook uses to remove line breaks is not documented and most likely is subject to change.