Creating a custom field/widget

Question: I'm trying to create a field that is a combination of two fields. The first field needs to a reference to another entity (just like in the entityreference module). The second field is just a text field (using the textarea widget).
Here's the code I have so far.
sample.install:
function sample_field_schema($field) {
    $schema = array(
        'columns' => array(
            'place_id' => array(
                'type' => 'int',
                'unsigned' => true,
                'not null' => true
            ),
            'quote' => array(
                'type' => 'text',
                'size' => 'big',
                'not null' => false
            )
        ),
        'indexes' => array(
            'place_id' => array('place_id')
        ),
        'foreign keys' => array()
    );

    $entity_type = 'place';
    $bundles = field_info_bundles('node');
    if (!empty($bundles['place'])) {
        $schema['foreign keys']['place'] = array(
            'table' => 'place',
            'columns' => array('place_id' => 'nid')
        );
    }

    return $schema;
}

sample.module:
function sample_field_info() {
    return array(
        'sample_field' => array(
            'label' => t('Label'),
            'description' => t('description.'),
            'default_widget' => 'sample_field_widget',
            'default_formatter' => 'sample_field_formatter',
            'settings' => array(),
            'instance_settings' => array(),
        )
    );
}

function sample_field_formatter_info() {
    return array(
        'sample_field_formatter' => array(
            'label' => t('sample formatter'),
            'field types' => array('sample_field')
        )
    );
}

function sample_field_formatter_view($entity_type, $entity, $field, $instance, $lang, $items, $display) {
    $element = array();

    switch ($display['type']) {
        case 'sample_field_formatter':
            // I'm not really familiar with these bits ... this is just to output *something*
            $element[]['#markup'] = var_export($items, true);
            break;
    }

    return $element;
}

function sample_field_widget_form(&$form, &$form_state, $field, $instance, $lang, $items, $delta, $element) {
    switch ($instance['widget']['type']) {
        case 'sample_field_widget':
            $element['place_id'] = array(
                '#type' => 'textfield',
                '#maxlength' => 1024,
                '#title' => t('Place'),
                '#default_value' => isset($items[$delta]['place_id']) ? $items[$delta]['place_id'] : null,
                '#required' => $element['#required'],
                '#weight' => (int)$element['#weight'],
                '#delta' => $delta,
                '#size' => 'big',
                '#autocomplete_path' => 'api/find/places'
            );

            $element['quote'] = array(
                '#type' => 'textarea',
                '#title' => t('Quote'),
                            '#default_value' => isset($items[$delta]['quote']) ? $items[$delta]['quote'] : null,
            );
            break;
    }

    return $element;
}

function sample_widget_error($element, $error, $form, &$form_state) {
    switch ($error['error']) {
        case 'sample_field_invalid':
            form_error($element, $error['message']);
            break;
    }
}

function sample_field_is_empty($item, $field) {
    if (empty($item['sample_field'])) {
        return true;
    }
}

function sample_field_widget_info() {
    return array(
        'sample_field_widget' => array(
            'label' => t('Sample Field Widget'),
            'field types' => array('sample_field'),
            'settings' => array(),
            'behaviors' => array(
                'default value' => FIELD_BEHAVIOR_NONE
            )
        )
    );
}

So this all gives me a new field type and a new widget for that field. When I edit/create new content that has this field type, the widget shows up properly with both fields but when I submit to insert/update the content, the fields are not saved. How can I get the form to save the field data for this custom field and how can I get that data to be loaded again when the content is edited?
Answer: You're missing hook_field_validate() which apparently is required for this to work. See this blog post (which you may have already -- I'm just comparing what he did to your code) ... http://www.agileapproach.com/blog-entry/compound-fields-drupal-7
Comment: ah, thanks for that. that seems like an important hook ... but that didn't fix this issue. Turns out that my hook_field_is_empty was not properly checking for empty (getting false trues).
Answer: It was my hook_field_is_empty() implementation. It was returning true in cases where it shouldn't have. Just make sure hook_field_is_empty() is properly checking for empty values.

Creating a custom field/widget


Visual Studio does not display .NET Core 2.2 in Target Framework dropdown

Question: I just cloned into an already existing project for work, and have found that for some reason, Visual Studio refuses to show .NET Core 2.2 in the "Target Framework" dropdown menu in the Properties -> Application menu.
I have installed .NET Core 2.2 (by clicking "install other frameworks" and downloading/running the 2.2 SDK file. I have originally installed the x64 version as that's what my boss uses, but I later also installed the x84 version to see if that worked. Neither works.), and confirmed that this is correctly installed. I did this by running the command "dotnet --info" in the shell, which outputs the following:
.NET Core SDK (reflecting any global.json):
 Version:   2.2.101
 Commit:    236713b0b7

Runtime Environment:
 OS Name:     Windows
 OS Version:  10.0.16299
 OS Platform: Windows
 RID:         win10-x64
 Base Path:   C:\Program Files\dotnet\sdk\2.2.101\

Host (useful for support):
  Version: 2.2.0
  Commit:  1249f08fed

.NET Core SDKs installed:
  1.1.11 [C:\Program Files\dotnet\sdk]
  2.2.101 [C:\Program Files\dotnet\sdk]

.NET Core runtimes installed:
  Microsoft.AspNetCore.All 2.2.0 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All]
  Microsoft.AspNetCore.App 2.2.0 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
  Microsoft.NETCore.App 1.0.13 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 1.1.10 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 2.2.0 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]

Still, there are no .NET Core 2.2 in the Target Framework dropdown. There are only two options currently: .NETCoreApp 1.0 and .NETCoreApp 1.1
I've got Visual Studio 2017, and as far as I can tell from the About page, version 15.0.0
Answer: I was having the same issue after downloading the latest dotnet-SDK-2.2.202 (at the moment). Tried everything on this thread and nothing worked.
I also recently updated to the latest VStudio 2017 - 15.9.11
Then I downloaded and installed the previous dotnet-SDK-2.2.105 available and it fixed the issue.
Find it here: https://dotnet.microsoft.com/download/dotnet-core/2.2
Comment: This worked for me as well. It sounds like Visual studio 2017 can recognize .net core 2.2.105 but not 2.2.202 (at least in my case). Another thing I didn't try is that update my visual studio to 2018 from 2017.
Comment: Did this the trick for me even though I have 2 later versions installed!
Comment: This works for me too. Installed the latest version then installed the version before it.
Comment: It's ridiculous you have to do this but it works, thank you for sharing. I guess we all should move to using VS2019.
Comment: Installing 2.2.105vdidnt help me at all .I am using VS 2017 15.9 .Any Idea folks?
Comment: On the link provided, it actually states which version of Visual Studio 2017 these SDKs support. At the time of comment -> 2.2.207 (VS 16.0), 2.2.110 (VS 15.9)
Comment: Seems you also need to select x86/x64 that matches the install of Visual Studio you have. I.e. I'm running x86 VS on my x64 machine, and needed x86 SDK.
Answer: .net core SDK 2.2.202 requires MS build 16 to work. So you would need to install Visual Studio 2019.
See 2.2.202-SDK not available in Visual Studio 2017 #2542
Comment: thanks - I was dealing with this exact problem today. Looks like .net core developers are all using 2019 and forgot to update 2017
Comment: This worked for me... :(
Comment: This is the correct answer for those who .NET Core 2.2 didn't show up in the drop-down on the latest VS 2017 (version 5.9)
Comment: Not true any more  see https://dotnet.microsoft.com/download - there is a special download for VS 2017. I needed this even though I could see 2.2 sdk option in visual studio project dropdown. VS 15.9.12
Answer: Your Visual Studio Version is not up to date. You need to update it.

Visual Studio 2017 15.9 uses .NET Core 2.1 SDK by default after the workload is installed.
To update Visual Studio to use .NET Core 2.2 SDK:
Install the .NET Core 2.2 SDK.

Reference
PS: You need to restart visual studio. After you the installation of .Net Core 2.2 SDK.
Comment: To be more exact,at the time of this writing, 15.9 is the current visual studio. 2.2 support was added some time back - but NOT in 15.0. Run the installer and it will SCREAM for you to install a big update.
Comment: This worked! I thought I had the latest stable version of Visual Studio, but apparantly assuming that was incorrect. After I updated to 15.9, all the SDKs showed correctly (even ones I didn't know were installed, such as 2.0 and 2.1)
Comment: Check the CORRECT answer below by Javier Alvarez
Answer: I had the same issue, and the Core 2.2 did not show up on the Visual Studio in the Target platforms dropdown. I did everything answered above and still had the same issue.
Finally I ended up creating a new global json config using

dotnet new globaljson --sdk-version 2.2.101 --force

Restarting Visual Studio after the above step worked for me.
Comment: When I do this I am getting an error that "one or more projects in the solution were not loaded correctly". The output says (for the project that is targeting 2.2: : `error  : Project file is incomplete. Expected imports are missing.`
Answer: Check to see if there is a global.json file in the same folder as your solution file. I removed it and everything is working again.
Comment: This was the issue for me! Thank you! Ref: https://learn.microsoft.com/en-us/dotnet/core/tools/global-json?tabs=netcore3x
Answer: I was having the same problem in my VS 2017 -version 15.8
I tried by update the vs2017 to the latest version 15.9.11 and installed the latest .net core 2.2.203 SDK, but still not getting the desired target framework 2.2
When I installed the .net core 2.2.105 SDK and after restarting the VS, I got the target framework 2.2
Comment: This may be correct for some cases, but what SDK version is on the global.json would be the right culprit, when you upgrade to newer versions of Visual Studio, it needs a specific supported version.


How do I alter prices?

Question: This is a follow up to Ubercart alter product price when product added to cart.
I have an attribute called "Billing Term". It has options: 6 months, 12 months and 24 months. If 6 months is selected, 0% discount must be applied. 6 months, 5% discount must be applied. and 24 months, 10% discount must be applied.
I set up the attributes to make no change to the price, because I can't find a way to make attributes adjust a price by percentage.
The best solution to my problem would be to find a way to specify attribute discounts in %. But I couldn't find a way to do that. If you know of a way, please do tell, as that is for sure better than my other options below.
So, with all attribute adjustments to be 0, I figured I could something similar to what was done here (but this post is for Drupal 7). So I tried this:
function comply_advantage_uc_cart_alter(&$items)
{
  print '
'; print_r($items); die(); <--- this makes apache run out of memory
  print '
'; print_r(arrray_key($items)); die(); <--- this prints out "2", and then "3" and then "5" etc.
  $items[45]->price = 29393; <--- this doesnt adjust the price

}
I was hoping to do something like this:
$items[5]->price = $items[5]->price * 0.95; // to apply 5% discount

How can I accomplish this?
I found out that $items[5] type is CartItem.
Answer: Figured it out:
function comply_advantage_uc_cart_alter(&$items)
{
    $item->price->setValue($item->price->value * 0.95);
}

Hope it helps someone!
** IMPORTANT **
It looks like if you use
$item->price->setValue($item->price->value * 0.95);

Yo might end up altering the price several times. So I had to actual recalculate the price completely, without using $item->price->value, or it would deduct 5% multiple times.

How do I alter prices?


Split array of arguments into individual arguments and pass them into PHPUnit ->with()

Question: I'm trying to use @dataProvider to refactor my horrendous-looking unit tests, however I am unsure how I can pass arguments to my PHPunit mockbuilder ->with() block without it thinking that I'm trying to pass an array...
$myArgs = array('arg1', 'arg2', 3);

$myStub->expects($this-once())
    ->method('myFunction')
    ->with($myArgs)

I would like ->with($myArgs) to be interpreted as ->with('arg1', 'arg2', 3)
Is this possible?
Answer: You can use argument unpacking:
$myStub->expects($this-once())
    ->method('myFunction')
    ->with(...$myArgs);


How can I test the date in puppet to implement a temporary rule?

Question: What's a good way to test the current date/time in puppet in order to implement a temporary change?
e.g. we've just had a security issue with NTP, and it took a while for Debian to come out with an update.  It seemed simplest to just turn ntp off for a while.
service { 'ntp':
  # remember to re-enable this after ntp is secured.  CVE-XXXXXXXXXX
  ensure => "stopped",
  ...
}

So that requires remembering to come back and change it back.  What I'd like to have done would be to have made the value of the ensure attribute dependent on a selector which tested the date at run time.
Can anyone suggest a nice way to do that?
I can imagine making a function available through the puppet parser to do it, and it'd be nice to know if someone has written that already, but bonus points if you have a way to do it without an extra module.
service { 'ntp':
  ensure => date_is_after("23 Dec 2014"): {
     true => "running",
     false => "stopped"
  }
  ...
}

It occurs to me also that a test based on the current version of the ntp package would be quite elegant, but I'm also not sure how you'd do that in puppet.
Answer: To be able to get the current version of the NTP package you would need to write a custom fact that gets pushed to each managed host via pluginsync and discerns the value by querying the local package manager. See https://docs.puppetlabs.com/facter/2.3/custom_facts.html for writing custom facts.
You can then use the versioncmp() function in your manifest to conditionally enable or disable the NTP daemon using the value of that fact and comparing it with the known good version of NTP that contains your fix.
Answer: To use the date on the master, you can write a simple shell wrapper for date and invoke it from the manifest using the generate function.
$ echo -e '#!/bin/bash\n/bin/date -I\n' >/tmp/dater
$ chmod 755 /tmp/dater
$ bundle exec puppet apply -e 'notice(generate("/tmp/dater"))'
Notice: Scope(Class[main]): 2014-12-23

You can fetch the result into a variable and go crazy.
$now = generate("/tmp/dater")

Since Puppet will not compare strings using < and > like bash or awk do, you will probably want to use date +%s instead, so that you can numerically compare the timestamp to whatever target date you defined.
As an aside, I would personally refrain from implementing this kind of thing. It comes with a high risk of falling onto your foot pretty heavily. Consider defining a global Hiera key instead, which you can flip manually after your calendar reminded you to do that. Don't build your friendly surprises into Puppet.
Comment: The generate function works as well as anything I can think of.  This can be done without the script though.  `puppet apply -e 'notice(generate("/bin/date","-I"))'`.
Answer: You can write an external fact like that:
#!/bin/bash
echo "date=$(date '+%Y-%m-%d')"

To distribute it you can put it into a new module (for example modules/date/facts.d/date).
And then you can do
if $::date > "2016-05-15" {
  ...
}

Comment: That works, but it seems pretty crazy to be generating a date as a fact about the system running the agent when the server already knows the date.
Comment: There are server facts but I don't know if you can add custom ones.


Find the function $y(x)$ with the property that $y(x)$ has a horizontal tangent line

Question: This is a calculus problem I've been struggling on:
"Find the function $y(x)$ with the property that $y(x)$ has a horizontal tangent line at the point $(1,-2)$ and $\frac{d^2y}{dx^2}=2x+5$.
So, I somewhat understand it. I think I need to do:
$y'(x) = x^2 + 5x + c_1$
and then
$y = \frac{1}{3}x^3 + \frac{5}{2}x^2 + c_1x + c_2$
The problem I have is, how do I find $c_1$? I think $c_2$ would be $-2$, from looking at my notes, but I'm still not sure.
Edit:
Ah, thanks, I think I figured it out!
Comment: @Kaster You might want to read the question again.
Answer: $$y'(1)=0$$
That's what a horizontal line means... It's slope is $0$. Derivative represents slope.
$$y(1)=-2$$
The curve passes through it.


How to add CSS classes to a Views-generated block? (NOT to its generated content, the block itself!)

Question: I don't know why, but Views doesn't add "human-readable" CSS class names (like e.g. the machine name of the view) to the blocks it creates (it only adds its classes to the generated "content" part when adding classes to the "CSS class" part in the view editor (see the screenshots below!)).
It only adds the usual block block-views, and possibly contextual-links-region CSS classes to the block(s), and generates a unique id (not class) like this: block-views-3d8f7966168beeec655c8ead69336789 (because its delta is this generated hash code).
It doesn't make sense to write CSS rules for these classes and ids (like .block-views-3d8f7966168beeec655c8ead69336789 { /* ... */ }), because these classes/ids might change when altering the Views block.
How can I add some custom CSS classes in an implementation of hook_block_view_alter(), if I cannot even identify these blocks because of their generated hash delta?

I do not want to use Block Class, because I feel it's like an overkill for just adding some classes to one or two Views-generated blocks (BTW I checked the module, and I feel SELECT css_class, module, delta FROM {block_class} query in block_class_preprocess_block() like an overkill, because it checks ALL the added classes, even if the block is hidden...).
So I would like to solve it from my own module.

EDIT
An example:
My view with the machine name and the added CSS classes:

The generated block's HTML code in the inspector:
Answer: First. You have "hash" - because you view machine name is too long.
Second - you can add your own classes to view
Comment: _"You have "hash" - because you view machine name is too long."_ - and why does it matter? I can add rules in CSS stylesheets to REALLY long class names too without any problems... The _"CSS class"_ part you marked is NOT correct, because these classes are only generated into the "content" part - this is what I started my question with! So I have to add classes to the **wrapper** of the contents. See the screenshots I just pasted in the original question.
Comment: That screenshot you have regards view blocks, right?
Comment: no - it is on view editing page  - admin/structure/views/view/[youviewname]
Comment: ok. in this case the simpliest way is to create custom templates for block - you want change.

this link can be useful http://drupal.org/node/1089656 - it explains Template name suggestions
Comment: But this way I had to use a `block--views--3d8f7966168beeec655c8ead69336789.tpl.php` file, and in this case, I'm at the same point as if I used an `if($variables['block']->delta == '3d8f7966168beeec655c8ead69336789')` condition in `hook_preprocess_block()`. This is what I wanted to avoid, because I thought I can use a more human-readable name in my hook. For example, what if I want to move the view into another with the same parameters, I delete the previous one, but use the same machine name and CSS classes, but the generated unique hash changes? In this case, I lose my modifications.
Comment: try this block--views--view_machine_name.tpl.php
Comment: Tried that, unfortunately it doesn't work. (Yes, I even cleared cache.)
Comment: @cherouvim: yes, the screenshot that Gaydabura showed, regards Views blocks.
Answer: That's a old question, but there is no proper answer. I came across the same problem. The solutions I could think of was CSS parent selector (which doesn't exists yet) OR some Drupal manipulation.
I added a hook_preprocess_block to add a wrapper CSS class to all view blocks that define a CSS class. That's not trivial so I will put my code here. It may not work with all view blocks, if you have an issue with this code, feel free to update it and post your own version.
Example: View with CSS class "test" will be contained in a block with the CSS class "test-wrapper".
function <MY_THEME>_preprocess_block(&$variables) {
    $default_display_id = 'default';
    // Trying to access the field:
    //     $display_id =      $variables['elements']['#views_contextual_links_info']['views_ui']['view_display_id']
    //     $default_display = $variables['elements']['#views_contextual_links_info']['views_ui']['view']->display['default']->display_options['css_class']
    //     $display =         $variables['elements']['#views_contextual_links_info']['views_ui']['view']->display[$display_id]->display_options['css_class']
    if (isset($variables['elements']['#views_contextual_links_info']['views_ui'])) {
        $view_ui = $variables['elements']['#views_contextual_links_info']['views_ui'];
        if (isset($view_ui['view_display_id'])) {
            $display_id = $view_ui['view_display_id'];
            if (isset($view_ui['view']) && property_exists($view_ui['view'], 'display') && isset($view_ui['view']->display[$display_id])) {

                $default_css_class = NULL;
                if (isset($view_ui['view']->display[$default_display_id])) {
                    $default_display = $view_ui['view']->display[$default_display_id];
                    if (property_exists($default_display, 'display_options') && isset($default_display->display_options['css_class'])) {
                        $default_css_class = $default_display->display_options['css_class'];
                    }
                }

                $view_css_class = NULL;
                $display = $view_ui['view']->display[$display_id];
                if (property_exists($display, 'display_options') && isset($display->display_options['css_class'])) {
                    $view_css_class = $display->display_options['css_class'];
                }

                $css_class = $view_css_class ? $view_css_class : $default_css_class;
                if ($css_class) {
                    $variables['classes_array'][] = "$css_class-wrapper";
                }
            }
        }
    }
}

Answer: There is a module for this purpose.
View block top class
Answer: For me hook_preprocess_block() didn't work. (Maybe because I had to add the block directly from a template file via views_embed_view().)
However, hook_preprocess_views_view() with a simple check for $vars['view']->current_display did work:
function MYMODULE_preprocess_views_view(&$vars) {
  // 'MYBLOCK' usually comes as 'block' if this view only has one
  if ($vars['view']->name == 'MYVIEW' && $vars['view']->current_display == 'MYBLOCK') {
    // here I add a class that contains the current theme's name
    global $theme;
    $theme_name = array_pop(explode('/', (drupal_get_path('theme', $theme))));
    $vars['classes_array'][] = $theme_name.'-theme';
    // but you can simply do the following as well
    $vars['classes_array'][] = 'MYSTRING';
  }
}

Answer: The easiest way for me was to duplicate the file block.tpl.php, rename it to block--myregion.tpl.php and then add my classes inside it.
See: Theming blocks page.


Principal component analysis and statistical significance

Question: I've been drawn into a discussion at work on interpretation of principal component analyses. My "adversary" claims that the PCA score plot shows "statistically significant" differences (separation) and/or similarities (clustering).
From my understanding, statistical sigificance is something that can be inferred from statistical tests. PCA is not a statistical test and tells us nothing about statistical significance. It really only tells us how our samples/points may correlate to each other. Am I wrong?
Comment: You are basically correct -- but one can almost always convert any procedure into a hypothesis test by means of a bootstrap or permutation approach.  That is particularly simple to do (at least conceptually) with PCA.  However, one point is incontrovertible: the score plot *by itself* cannot yield any measure of statistical significance.  You need to know how that plot might vary under some kind of null hypothesis.  Thus, one way to respond in this discussion is to ask your interlocutors for a *precise, quantitative, specific* statement of their null hypothesis.
Answer: I think you are right. PCA can be thought as a rotation of the axes done in such way that the first axis captures more variation than the second axis, the second more than the third etc and all axes are orthogonal to each other and the origin is centered on the mean of the datapoints. Here variation is the sum of square distances between the points projected on an axis and the origin.
There is no statistics involved since you are not trying to infer anything about the population that generated the given data. (I'm pretty sure I'm not getting things 100% right myself).


Como fazer no código acender onde esta em laranjado

Question:
não sei como e nem como procurar para fazer esse esquema de deixar em laranja quando eu passo o mouse.
Comment: Seria o efeito hover ? http://jsfiddle.net/filadown/m55xqrkb/
Comment: Você tem o código destas trilhas ? poste na sua pergunta, ajuda bastante na elaboração de uma resposta!
Comment: Tem várias maneiras de se fazer isso. Pode ser com SVG, apenas com DIVs bem posicionadas, com imagem, entre outros métodos. Só depende de como são estruturadas as trilhas. Tem algo pronto pra servir de referência? E o melhor é que dá pra fazer tranquilamente sem JavaScript (e muito menos jQuery, que o pessoal abusa).
Comment: Exatamente amigo, é com :hover só não sei de que maneira terei que fazer pra acender essas trilhas.
Comment: Pois bem amigos eu ainda preciso fazer essa trilhazinha mas não sei como se alguém poder me ajudar agradeço de coração.
Answer: Você pode fazer este efeito com o hover.
Exemplo:

li {
  width: 70px;
  list-style-type: none;
  text-align: center;
}
li:hover {
  background-color: orange;
  color: white;
}

Hover

Focus

Active


How do I add a css class to body from a page callback function?

Question: I have a module that produces a lot of pages. A set of these are handled by a particular part of my application, and I would like all these to have a class added to either html or body. I'd settle for #block-system-main.
The existing answers point to a template preprocess hooks e.g. hook_preprocess_html() but this feels wrong.
I'd have to create that hook and then tell it to go somewhere else to determine which page call back was used and which class to apply - it's all backwards. Drupal's already selected the right callback, so a 2nd lookup is another thing to maintain and an inefficiency.
I could of course do something like set a global $extra_page_classes variable and then implement the hook to add these classes to the page, which is more efficient but it's still messy. Or I could add (yet another) wrapping
 to my callback output, but that's not going to give a themer chance to adapt the rest of the page elements outside of the main content.
Seems odd that a page callback, responsible for the substantial content of the page, can't set page-level attributes. A page callback can, for example, choose to call drupal_add_css(), but it (apparently) can't do something as simple as add a class to the page.
As it seems odd and Drupal usually has some (often hidden) elegance, I thought I'd ask specifically if there was a better way.
Answer: Well, I think your confusion comes from the D7/D6 fact that a "page" has little clue whats going on around it. As you've said the page callback function tells drupal "what goes in the $content" but not what adornments happen on the page HTML DOM around $content.
To my knowledge unless your using Panels, Context or something else to share "page state" through components of your site -- this is simply how D7 simply works.
Without using context, panels, etc. I usually end up looking for url paths or NIDs or custom content array attributes #project-add-body-classes in hook functions to fire off my logic.
For what you describe I would use hook_html_alter() and look for a page path to alter the body_classes array as needed.
Comment: Have edited your Q as I presume you meant `template_preprocess_html()`. I've done this but searching the array for the '#myappclass' key requires recursive loop (page.content.content.content...system_main.#myappclass) which is inefficient. I might change code to just use a global instead; at least that's easily identifiable. Thanks for your time, anyway.
Comment: Thanks for your answer. Are you meaning to add to 'classes_array' from within `hook_page_alter()`? Can't get that working - tried on $page, $page[content] $page[content][system_main], but nothing.
Comment: I have edited my answer. hook_page_alter only lets you muck with the `$content` type stuff in a page. I guess `hook_html_alter` is the only think that lets you change body_classes easily in a hook.
Answer: You could simply do it from within a page callback with inline JS.
drupal_add_js('jQuery(document).ready(function () {
  jQuery("body").addClass("foobar");
});', 'inline');

Alternatively use template_preprocess_html to add a body classes depending on the current path.
/**
 * Implements hook_menu().
 */
function MYMOUDLE_menu() {

  $items = [];

  $items['foo/bar'] = [
    'title'            => 'Foobar',
    'description'      => 'Lorem ipsum.',
    'access arguments' => ['access content'],
    'page callback'    => '_MYMODULE_mycallback',
    'type'             => MENU_CALLBACK,
  ];

  return $items;
}

Now add the body class dynamically by comparing the URL arguments from above.
/**
 * Implements template_preprocess_html().
 */
function MYMODULE_preprocess_html(&$variables) {

  // Add HTML  class.
  if (arg(0) === 'foo' && arg(1) === 'bar') {
    $variables['classes_array'][] = 'foobar';
  }
}


how to set flag or indicator through ajax in php?

Question: I am creating a join now page.I am taking login name,password, confirm password and email to be register. these inputs I am validating through javascript and I am checking that login name does exist already or not through ajax.If it exists I am simply displaying a msg that this id exists already please chose another one.
Problem: is that if a user typed a login id that already exists, ajax will show that is exists already but still user can click on submit because this time JavaScript will pass it because login id field is not empty.even I can check this on server side db process but I want to set one indicator or flag kind of, until and unless user enters such login id that does not exist he wont be able to submit form. my ajax code-
...
xmlhttp.onreadystatechange=function()
          {
          if (xmlhttp.readyState==4 && xmlhttp.status==200)
            {
            document.getElementById("loginName").innerHTML=xmlhttp.responseText;
            }
          }
...

db file -
//check in user table
if($num_rows == 0)
{
    echo "Ok, you can chose $logid as Login name.";
}
elseif($num_rows >= 1)
{
echo "$logid Ligin name has already been taken, Please chose another Login name.";
}

Or how can I set login Id text box to empty string along with the error msg from ajax?something like-
elseif($num_rows >= 1)
{
?>

<?php
echo "$logid Ligin name has already been taken, Please  chose another Login name.";
}

Answer: You could do something like setting the form to disabled and then enabling it when they've selected a login that is available:
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
    document.getElementById("loginName").innerHTML=xmlhttp.responseText;
    document.getElementById('id-of-form').disabled = false;
}

I personally wouldn't worry about it too much because you must recheck it on form submission anyway, because if a) they have JS turned off or b) select the same login as someone else who is also about to join now in the same instant (race condition), you need to make sure they don't both succeed.  Checking a login name is a useability feature to help people not hate you and your web site for making them resubmit a form dozens of times to find a good login.
Answer: I think this should do
create a form like this
<form name="name1" method="post" action="url" onsubmit="return checkForm(this)">

    <input type="hidden" id="hidden1" name="hiddenf" value="0" />
</form>

Then in the ajax callback function
...
          xmlhttp.onreadystatechange=function()
          {
             if (xmlhttp.readyState==4 && xmlhttp.status==200)
             {
                 document.getElementById("loginName").innerHTML=xmlhttp.responseText;
                 if(xmlhttp.responseText == 'not found') //your exist-id-message here
                    document.getElementById('hidden1').value = 0;
                 else
                    document.getElementById('hidden1').value = 1;
          }
...


Function does not give value of variables

Question: The following function gives me the next error afterwards when I tried to echo $oplossing after the function:

Undefined variable: oplossing

I've tried multiple things but somehow it does not take the valua of the variables from inside the function to the rest of the php document. I'm quite new to programming so this might be obvious but I don't know how to do this. How do I fix this?
 $moeilijkheidsgraad = $_POST["moeilijkheidsgraad"];
$waarde = $_POST["waarde"];

function WaardeGetal ($moeilijkheidsgraad, $waarde)
{
if ( $moeilijkheidsgraad == "makkelijk" ){      //makkelijk
    if ( $waarde == "dechex" ){                 //van decimaal naar hexadecimaal
        $getal = rand(0,32);                    //willekeurig getal tussen 0 en 50
        $oplossing = dechex($getal);
        $oplossing = strtoupper($oplossing);    //omzetten van decimale getal naar hexadecimaal getal
    }

    elseif ( $waarde == "hexdec") {             //hexadecimaal naar decimaal
        $oplossing = rand(0,32);                //willekeurig getal tussen 0 en 50
        $getal = dechex($oplossing);
        $getal = strtoupper($getal);            //omzetten van decimale getal naar hexadecimaal getal
    }

    elseif ($waarde == "decbin") {
        $getal = rand(0,16);
        $oplossing = decbin($getal);
    }

    elseif ($waarde == "hexbin"){
        $getal = rand(0,16);
        $getal = dechex($getal);
        $oplossing = base_convert($getal,16,2);
        $getal = strtoupper($getal);
        }

    elseif ($waarde == "binhex" ) {
        $oplossing = rand(0,16);
        $oplossing = dechex($oplossing);
        $getal = base_convert($oplossing,16,2);
        $oplossing = strtoupper($oplossing);
        $aantal = 0;
        }

    else {
        $oplossing = rand(0,16);
        $getal = decbin($oplossing);
    }
    }

else {                                          //moeilijk
    if ( $waarde == "dechex" ){                 //van decimaal naar hexadecimaal
        $getal = rand(32,256);                  //willekeurig getal tussen 0 en 50
        $oplossing = dechex($getal);            //omzetten van decimale getal naar hexadecimaal getal
        $oplossing = strtoupper($oplossing);
        }

  elseif  ( $waarde =="hexdec" ){               //hexadecimaal naar decimaal
        $oplossing = rand(32,256);              //willekeurig getal tussen 0 en 50
        $getal = dechex($oplossing);            //omzetten van decimale getal naar hexadecimaal getal
        $getal = strtoupper($getal);
    }

    elseif ($waarde == "decbin") {
        $getal = rand(16,256);
        $oplossing = decbin($getal);
    }

    elseif ($waarde == "hexbin"){
        $getal = rand(16,256);
        $getal = dechex($getal);
        $oplossing = base_convert($getal,16,2);
        $getal = strtoupper($getal);
        }

    elseif ($waarde == "binhex" ) {
        $oplossing = rand(16,256);
        $oplossing = dechex($oplossing);
        $getal = base_convert($oplossing,16,2);
        $oplossing = strtoupper($oplossing);
        }

    else {
        $oplossing = rand(16,256);
        $getal = decbin(oplossing);
    }
 }
 return
 }

WaardeGetal($moeilijkheidsgraad, $waarde);

Answer: If you declare both $waarde and $oplossing before your function and then call global $waarde, $oplossing inside your function.
This occured as the varibles inside your function had a local scope and not a global one
Comment: It fixed the errors I had, but how do I take the new values of $oplossing and $getal outside the function again?
Comment: You should be fine to just call them as you normally would after the function. Any variables you want to access outside the function you should declare outside and then make it global inside.
Comment: just return them : return ['oplossing' => $oplossing, 'getal' => $getal];


Autodesk Forge messed up view

Question: We are using the Autodesk Forge model derivative and viewer API's for sharing Revit models with our customers.
This works very well for almost all our Revit models. But currently we have 2 Revit models which use the same template, and with those 2 models the Forge viewer does not render these correct. It looks like we get some kind of exploded view, materials are not on the correct place etc (see images).
We assume it has something to do with the Revit template, but we cannot find it. Any suggestions?
Revit

Forge
Comment: a quick question: is this model linking with some other models, or standalone? From the snapshot, it looks the the missing elements should belong to one model, but it is weird they are gone. If you could provided a small demo model, we can diagnose what happened with the case. Please email us at email@example.com with private data.
Comment: The model is not linked to any other model. It looks like the elements are not missing, but placed on another location. Just like an exploded view. I will try to send the project by email.
Answer: As a suggestion, on Revit, go to publish settings and confirm the names of the 3D selected to be extracted. On Viewer, ensure you're showing the same view, you can see the name where you load a specific viewable.
Comment: Renamed my 3d view and uploaded again, but unfortunately the view is still messed up.
Comment: If this 3d view is not chosen in the "set" of the publish setting, despite renaming, Forge Revit extractor will still use the default `{3D}` view while translating. So, please check if this view is in your publish setting sets.
Answer: I have found a workaround, it looks like the problem was the cars which I was using in the model. These were Revit families where a DWG import was used.
When removing the cars from the model all other materials where rendering fine in the Forge Viewer. I sended the model also to Forge support and hoping for a solution so I can use the cars again.

Autodesk Forge messed up view


How to change the user profile edit page?

Question: What is the best way to change the user profile edit page? I need to add a new field alongside the password.
Comment: Possible duplicate of [How to add extra fields to user profile?](http://drupal.stackexchange.com/questions/8253/how-to-add-extra-fields-to-user-profile)
Answer: You can add new fields to the users profile page at admin/config/people/accounts/fields
You can also manipulate the form by implementing hook_form_user_profile_form_alter(&$form, &$form_state, $form_id) and hook_form_user_register_form_alter(&$form, &$form_state, $form_id)
To add new profile pages you can use the Profile 2 module.
You can also edit the user edit template by implementing hook_theme().
Answer: In drupal 7     /admin/config/people/accounts/fields
Here you can add and change certain fields for the user profile.
You may want to check out the module profile2 as well: https://drupal.org/project/profile2


Is this function Injective/surjective? $f: \mathbb{Z} \to \mathbb{Z}, \ f(x) = x^2+x+1$

Question: $$f: \mathbb{Z} \to \mathbb{Z}, \ f(x)  = x^2+x+1$$
Injective: I think this is injective because $\forall x_1 \ne x_2 \in f: \mathbb{Z} \implies f(x_1) \ne f(x_2)$ for example taking the numbers $\{0,1,2,3,4\}$
$$0 \to 1 \\ 1 \to 3 \\2 \to 7 \\ 3 \to 13 \\4 \to 21$$
Surjective: I think this is not surjective because the zero of the second set it will never be reached by any arrow.
I'm right?
Comment: Well, @DietrichBurde, testing a few numbers may be a proof. Testing $0$ and $-1$ proves non-injectivity of this function :P
Comment: Well, @Martund, testing a few numbers also may not be a proof. See above.
Answer: Expanding on what @Marcus wrote, consider any $n,m$ such that $n+m= - 1$ (of which there are infinitely many examples). Each such pair will have $f(n) =f(m)$.
Comment: Nope. What we can actually say is that $$f(x_1) = f(x_2) \Leftrightarrow {x_1}^2 + x_1 + 1 = {x_2}^2 + x_2 + 1\\ \Leftrightarrow ({x_1}^2 +x_1) - ({x_2}^2 +x_2) =0\\ \Leftrightarrow (x_1 - x_2) (x_1 + x_2 +1 ) = 0$$ If $x_1\neq x_2$, we will have $x_1 + x_2 +1 =0$.
Comment: Thank you!  :-).
Comment: Can I say that is not injective because $x_1^2+x_1+1 = x_2^2+x_2+1 \iff x_1^2 = x_2^2 \iff x_1 = \pm x_2 $? since $f(x_1) \ne f(x_2)$
Answer: Note that $f(1)=f(-2),$ so this is NOT injective.
Comment: In fact, $f(x)=f(y)$ iff $y=x$ or $y=-x-1$; the latter transformation preserves integers
Answer: It is not surjective since $f(x)=x(x+1)+1$ is always ODD (observe that $x(x-1)$ is always even since it is the product of two consecutive integers).
It is not injective since $f(0)=f(-1)=1$-


Get specific column header names from DataTable

Question: I need to get a specific column header name based on value.
For ex: I am using the below query to get list of column headers and it works fine and on top of this can I get column names which has specific name like Department alone.
LINQ
string[] columnNames = dt.Columns.Cast<DataColumn>()
                         .Select(x => x.ColumnName)
                         .ToArray();

How can I add contains or exists to this query to get specific columns.
Comment: You mean like adding `.Where(x => x == "Department")`?
Comment: @S.Akbari Not if you put that line after the `Select`. I didn't answer this question because it's unclear and rather pointless to select a single string from a list of strings when you already have the string. I wish other people had thought the same...
Comment: @DavidG `x` is `DataColumn`. How is that possible? Probably you mean `.Where(x => x.ColumnName == "Name")`. Check my answer.
Comment: @DavidG Yes by putting `Where` after `Select` it works and I also have pointed this. I thought you said replace `Select` with `Where`.
Comment: @S.Akbari And nothing to say about the second part of my comment?
Answer: Simply add a filter, like this:
string[] columnNames = dt.Columns.Cast<DataColumn>()
                             .Select(x => x.ColumnName)
                             .Where(x => x == "Department")
                             .ToArray();

Answer: List<string> containsKeys = new List<string>();
containsKeys.Add("SomeWildCard");

DataTable dt = new DataTable();
string[] columnNames = dt.Columns.Cast<DataColumn>()
                             .Select(x => x.ColumnName)
                             .ToArray().Where(t => containsKeys.Contains(t)).ToArray();

Answer: You can either select then filter the result:
.Select(x => x.ColumnName).Where(c => c == "Department")

Or first filter then select:
.Where(x => x.ColumnName == "Department").Select(c => c.ColumnName)

Answer: Columns property is of type DataColumnCollection, which has an indexer public DataColumn this[string name] to get DataColumn by name:
DataColumn dc = dt.Columns["Department"];

to get multiple columns by name use Select() with indexer:
List<string> names = new List<string> { "Department", "Something" };
DataColumn[] columns = names.Select(name => dt.Columns[name]).ToArray();


Are these conditions sufficient to guarantee positive definiteness?

Question: Let $f: \mathbb{C}^2 \to \mathbb{C}^n$ be the map
$$ f(u, v) = (u^{n-1}, u^{n-2}v, \ldots, u^{n-k} v^{k-1}, \ldots, v^{n-1})^T$$
so that $f$ is the rational normal curve in homogeneous coordinates.
Note that the image of $f$ can be described as:
$$ \operatorname{Im}(f) = \{ c (1, z, z^2, \ldots, z^{n-1})^T; c, z \in \mathbb{C} \} \cup \{ d (0, 0, \ldots, 0, 1)^T ; d \in \mathbb{C} \}. $$
Let $H$ be an hermitian $n \times n$ matrix such that
$$ (v, Hv) > 0, $$
for any $0 \neq v \in \operatorname{Im}(f)$, where $(-, -)$ is the standard hermitian inner product on $\mathbb{C}^n$.
Are these conditions sufficient to guarantee that $H$ is positive definite? This question just popped in my head. Part of me thinks it would be too good to be true, in which case it should be easy to construct a counterexample, numerically. Another part of me thinks that the rational normal curve "twists" enough to guarantee that $H$ is positive definite.
I will think about it during the day, but I think it is an interesting question.
Answer: There is a counter example.
For $n=3\,,$
$$
f(u,v)=(u^2,uv,v^2)\,.
$$
Let $H$ be the Hermitian matrix
$$
H=\begin{pmatrix}1&0&0\\0&0&0\\0&0&1\end{pmatrix}\,.
$$
which is only nonnegative semidefinite. Then, for $x\in{\rm Im}(f)\setminus\{0\}\,,$
$$
(x,Hx)=|u^2|^2+|v^2|^2>0\,.
$$


Erro envio JSON por Socket

Question: Quando a String do JSON é muito grande, há perda de parte da String no envio. Estou enviando assim:
private void btComunicarActionPerformed(java.awt.event.ActionEvent evt) {
        List<PessoaMOD> pessoas = new ArrayList<PessoaMOD>();

        for (int i = 1; i <= 2000; i++) {
            pessoas.add(new PessoaMOD(i, "Pessoa " + i));
        }

        try {
            Socket cliente = new Socket("127.0.0.1", 12345);
            enviarMensagem(codificarListarDiretorio(pessoas), cliente);
        } catch (Exception e) {
            System.out.println("Erro: " + e.getMessage());
        } finally {
        }
    }

public ByteArrayOutputStream codificarListarDiretorio(List<PessoaMOD> pessoas) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(bos);

        Gson gson = new GsonBuilder().create();
        dos.write(gson.toJson(pessoas).getBytes());
        return bos;
    }

public void enviarMensagem(ByteArrayOutputStream mensagem, Socket socket) throws IOException {
        byte[] msg = mensagem.toByteArray();
        DataOutputStream out = new DataOutputStream(socket.getOutputStream());
        out.writeInt(msg.length); //O tamanho da mensagem
        out.write(msg); //Os dados
        out.flush();
    }

e recebo no servidor assim:
int tamanhoMsg = entrada.readInt();
byte[] bufferJson = new byte[tamanhoMsg];
entrada.read(bufferJson, 0, bufferJson.length);
String json = new String(bufferJson);

Só que a String do Json não chega completa quando é muito grande.
O que acontece é que o numero de bytes é maior do que o lenght suporta, então o tamanho da mensagem não envia completo.
Também tentei enviar pelo método writeUTF();
Mas como a String é grande, gera esse erro: encoded string too long: 677789 bytes
Comment: como é instanciado out ?
Comment: não é "out", é "dos", tinha colocado errado. Você teria uma luz pra me dar neste problema? rsrs
Answer: Tenta mudar a parte da leitura do JSON no seu código no servidor de DataInputStream para BufferedReader:
// ...
long tamanhoMsg = entrada.readLong();

BufferedReader reader = new BufferedReader(
        new InputStreamReader(
            // guava library - limita a leitura de um input stream
            ByteStreams.limit(
                inputStream,                // input stream do socket
                tamanhoMsg                  // tamanho máximo a ser lido do input stream
            ),
        )
    );

JsonObject data = JsonParser.parse(reader)  // le o reader convertendo para  json
        getAsJsonObject();                  // retorna como JsonObject

// ...

Você também poderia mudar a informação de tamanho da mensagem de int para long.
Comment: Então, o problema é que a variável tamanhoMsg não está vindo certa, pois no cliente eu faço o seguinte para pegar o tamanho: "msg.length". Lenght é int, e como a String é grande, está estourando o tamanho máximo de inteiro, e assim, não está vindo o tamanho correto.
Comment: Então tenta mudar a delimitação de uma mensagem pelo próprio protocolo JSON.

Erro envio JSON por Socket


Reducible matrices and strongly connected graphs

Question: The incidence matrix below is primitive (the graph is strongly connected) thus it is irreducible. However, this matrix looks reducible (using $P = I_n$) ?!  What am I missing?
[A is called reducible if, subject to some permutation of the rows and the same permutation of the columns, A can be written in upper triangular block form, i.e. $$PAP^{-1} =\begin{bmatrix} B &C \\0 &D\end{bmatrix}$$]
Answer: Indeed, the given matrix is irreducible. Your claim is correct that if a matrix is reducible, then it can be written in the form (after some reordering of the states):
$$A' = \begin{pmatrix} B & C\\ \color{blue}{\mathbf{0}} & D \end{pmatrix}.$$
But notice that $B$ and $D$ must be square blocks! Apparently, you think that the blue block represents the zero block above:
$$\begin{pmatrix}
0 & 1 &  * & * & * \\
0 & 0  &  * & * & *\\
  1 & 0 & * & * & *\\
\color{blue} 0 & \color{blue} 0 & * & * & *\\
\color{blue} 0 & \color{blue} 0 & * & * & *
\end{pmatrix}
$$
But the block above the blue block is not square!


postfix master.cf configuration from database

Question: I am wondering if it is possible to configure postfix master.cf file from database.
Same as, for example, in main.cf one can set
alias_maps = pgsql:/etc/postfix/pgsql-aliases.cf

What I'm specifically trying to do is to have several SSL certificates.
It can be done fairly easily by modifying master.cf as shown here.
However, I am trying to avoid having to restart the server. I though that the cleanest way to do that would be to configure the master.cf from a database.
If this is not possible, is there any way around restarting the server, or in the worst case, making sure that no mail is lost?
Thank you.
Comment: Do you want to have several main.cf configurations and activate one or the other? what about just copying or soft linking the right one? And for getting the new configuration you don't need to restart, you can just `reload` postfix. Also even if you restart you wouldn't be losing email since messages tend to be re-sent if something went wrong (also you want to have a backup mail server)
Comment: So if I am reloading postfix, is still able to receive and save mail? I'm ok with having several `main.cf` files.
Comment: Yes, reload just re-reads configuration files, postfix still runs. Even if you restart it it's very unlikely that you'll lose any email.
Comment: Sweet. That, in my books is an answer, so if you want to post it as an answer, I'll accept it.
Answer: For getting the new Postfix configuration you don't need to restart, you can just reload postfix as recommended : "in order to refresh the Postfix mail system after  a  con-
              figuration  change,  do  not  use the start and stop commands in
              succession. Use the reload command instead."


Redirect user after one-time-login

Question: When users get an email with one time login link, they will arrive on a page to set their password (separated form via Password Separate Form)
But once they click submit, it doesn't redirect them to the normal view of the profile page.
How should I make the redirect?
I tried different Rules (Test 1, Test 2) and I even wrote to the module support of Password Separate Form, but nobody answer me and I need to fix the issue.
Comment: Possible duplicate of [Redirect after user login](https://drupal.stackexchange.com/questions/195170/redirect-after-user-login)
Comment: That's the problem, nothing works from that page, because I have Password Separate From on. And I can't uninstalled it, it need to be a separate page.
Answer: For people that want to have a separate form, here is my own solution:
I deinstalled Password Separate Form and, instead, installed Password Reset Landing Page (PRLP)
It does the redirect, the separate form and make sure people don't forget to actually set the new password.

Redirect user after one-time-login


Should sampling for logistic regression reflect the real ratio of 1's and 0's?

Question: Suppose I want to create logistic regression model which can estimate a probability of occurrence of some animal species living on trees based on characteristics of trees (f.e. height). As always, my time and money are limited, therefore I am able to collect only a limited sample size.
I have following questions:
Should the ratio of 1's and 0's in my sample reflect the true ratio of 1's and 0's? (at least approximately) I noticed that it is a common practice to perform logistic regression model with balanced sample (equal number of 1's and 0's) - but such models give surrealistically high probability of occurrence - right?
Are there any articles/textbook which I can use to **support the notion, that the models which do not reflect the true ratio of 1's and 0's are "wrong"?**
And finally: Is it possible to perform 1:1 sampling and subsequently correct the model with tau according to Imai et al. 2007?

Kosuke Imai, Gary King, and Olivia Lau. 2007. "relogit: Rare Events
  Logistic Regression for Dichotomous Dependent Variables," in Kosuke
  Imai, Gary King, and Olivia Lau, "Zelig: Everyone's Statistical
  Software," http: //gking.harvard.edu/zelig.

Dots represent trees (red = occupied, grey = unoccupied). I am able to
  identify all occupied trees with 100% accuracy (1's) but I can not
  measure all trees in forest. The model is different for each sampling
  strategy (ratio).
Answer: If the goal of such a model is prediction, then you cannot use unweighted logistic regression to predict outcomes: you will overpredict risk. The strength of logistic models is that the odds ratio (OR)--the "slope" which measures association between a risk factor and a binary outcome in a logistic model--is invariant to outcome dependent sampling. So if cases are sampled in a 10:1, 5:1, 1:1, 5:1, 10:1 ratio to controls, it simply doesn't matter: the OR remains unchanged in either scenario so long as sampling is unconditional on the exposure (which would introduce Berkson's bias). Indeed, outcome dependent sampling is a cost saving endeavor when complete simple random sampling is just not gonna happen.
Why are risk predictions biased from outcome dependent sampling using logistic models? Outcome dependent sampling impacts the intercept in a logistic model. This causes the S-shaped curve of association to "slide up the x-axis" by the difference in the log-odds  of sampling a case in a simple random sample in the population and the log-odds of sampling a case in a pseudo-population of your experimental design. (So if you have 1:1 cases to controls, there is a 50% chance of sampling a case in this pseudo population). In rare outcomes, this is quite a big difference, a factor of 2 or 3.
When you speak of such models being "wrong" then, you must focus on whether the objective is inference (right) or prediction (wrong). This also addresses the ratio of outcomes to cases. The language you tend to see around this topic is that of calling such a study a "case control" study, which has been written about extensively. Perhaps my favorite publication on the topic is Breslow and Day which as a landmark study characterized risk factors for rare causes of cancer (previously infeasible due to rarity of the events). Case control studies spark some controversy surrounding the frequent misinterpretation of findings: particularly conflating the OR with the RR (exaggerates findings) and also the "study base" as an intermediary of the sample and the population which enhances findings. Miettenen provides an excellent criticism of them. No critique, however, has claimed case-control studies are inherently invalid, I mean how could you? They've advanced public health in innumerable avenues. Miettenen's article is good at pointing out that, you can even use relative risk models or other models in outcome dependent sampling and describe the discrepancies between the results and population level findings in most cases: it's not really worse since the OR is typically a hard parameter to interpret.
Probably the best and easiest way to overcome the oversampling bias in risk predictions is by using weighted likelihood.
Scott and Wild discuss weighting and show it corrects the intercept term and the model's risk predictions. This is the best approach when there is a priori knowledge about the proportion of cases in the population. If the prevalence of the outcome is actually 1:100 and you sample cases to controls in a 1:1 fashion, you simply weight controls by a magnitude of 100 to obtain population consistent parameters and unbiased risk predictions. The downside to this method is that it doesn't account for uncertainty in the population prevalence if it has been estimated with error elsewhere. This is a huge area of open research, Lumley and Breslow came very far with some theory about two phase sampling and the doubly robust estimator. I think it's tremendously interesting stuff. Zelig's program seems to simply be an implementation of the weight feature (which seems a bit redundant as R's glm function allows for weights).
Comment: Just the simple calculation here: http://stats.stackexchange.com/a/68726/17230. (I'm not quite sure now where I picked up that terminology or how standard it is.) I heard that weighting works better for mis-specified models.
Comment: (+1) Is prior correction worth a mention as arguably the easiest way to adjust the intercept for simple case-control sampling?
Comment: @Scortchi Do you mean Bayesian logistic regression with an informative prior on the intercept? Or constrained optimization? I'm not actually familiar with what that might be.
Comment: @Scortchi Ah, that would be pretty easy! It should be fine for prediction as long as error estimates are not required. Weighting will give you a different SE for the intercept *and* the slope but this method will affect neither.


JQuery change() dynamically loaded event issue

Question: I'm trying to attach an .change() event to a drop down select field using JQuery. The code is as follows:

    Rental Options :
    <select name="id" id="productSelect" style="visibility:hidden;width:400px;">
        <option disabled="disabled">3 Day Rental ($5.68 per day) ($17.05) - SOLD OUT</option>
        <option value="801110989">7 Day Rental ($4.41 per day) ($30.85)</option>
        <option value="894325197">10 Day Rental ($3.71 per day) ($37.12)</option>
        <option value="894454745">14 Day Rental ($3.32 per day) ($46.44)</option>
    </select>

The event only seems to fire once when the page loads and not when I change the selected item. Does anyone know how to get this event to fire each time the select box is changed?
Comment: It works fine for me. How are you changing the selected item when the menu is invisible? I had to remove `visibility: hidden` before I could run your code.
Answer: Try this:
$("#productSelect").change(function () {
    var str = "";
    // To fetch value of selected option
    str = $(this).val();

    alert('changed');

});

I have removed some unnecessary code.
Answer: You need to move that JS block to inside the [$(document).ready()][1] event. This will ensure the page (DOM) is ready and has registered that event with your <select> control. This way it will fire every time a selection has changed.
I also recommend using the selector of the actual control $("#productSelect")) as opposed to the code you have which will fire that event for every select control. This might be the logic you deisre but odds are it is control specific so you can capture selection data to make subsequent AJAX calls or whatever else needed.


Ideal of a ring polynomial?

Question: I'm doing a past exam paper and this is the question I am stuck on.
Define the conditions on a subset $I$ of a ring $R$ to be an ideal of $R$. Show that the set $I = \{f ∈ \mathbb{R}[X]|f(1) = 0\}$ is an ideal of $\mathbb{R}[X]$.
I know the conditions for I to be an ideal of R, but I'm confused about what the set actually means? What is the result of $f(a+b)$ if $a,b∈ \mathbb{R}$
Thanks in advance for any help!
Answer: The set is a collection of elements. :)
$f(a+b)$ is a number, but it's not really important here because You have not to do this operation. You rather need $f(x)+g(x)$.
Answer: $I$ is a subset of $\mathbb{R}[X]$, the ring of polynomials with real coefficients. Each polynomial can be viewed as a function on the real numbers; the set $I$ consists of particularly those functions which evaluate to $0$ at $x=1$.
The ring structure on $\mathbb{R}[X]$: You can add elements in $\mathbb{R}[X]$ as follows: given polynomials $f,g$, $f+g$ is the polynomial defined by the rule $(f+g)(x) = f(x) + g(x)$. Similarly, to multiply polynomials, $fg$ is the polynomial defined by $(fg)(x) = f(x)g(x)$.
Answer: The set $ I $ defined by you, in fact, is an ideal generated by $x-1$. That is ,any element of $ I$  is of the form $(x-1)g(x)$ for arbitrary $g(x)\in \mathbb R[x]$. The meaning of $f(a+b)$ is nothing just a valuation of $f(x)$ at $x=a+b$.

Ideal of a ring polynomial?


Combine multiple images into a single image for later painting, with alpha blending

Question: I have a graphics system for Java which allows objects to be "wallpapered" by specifying multiple images, which can have (relatively) complex alignment and resizing options applied.
In order to perform adequately (esp. on very low powered devices), I do the image painting to an internal image when the wallpaper is first painted, and then copy that composite image to the target graphics context to get it onto the screen.  The composite is then recreated only if the object is resized so the only work for subsequent repaints is to copy the clipped region from the composite to the target graphics context.
The solution works really well, except that when I have PNG images with alpha-channel transparency the alpha channel is lost when painting the composite - that is the composite has all pixels completely opaque.  So the subsequent copy to the on-screen graphics context fails to allow what's behind the wallpapered object show through.
I did manage to use an RGBImageFilter to filter out completely transparent pixels, but I can't see a solution with that to making blended transparency work.
Does anyone know of a way I can paint the images with the alpha-channel intact, and combined if two pixels with alpha values overlap?
Answer: What type of Image do you use for the composite image?
You should use a BufferedImage and set it's type to TYPE_INT_ARGB which allows translucency.
Comment: BufferedImage is the single most useful Image subclass Java has in my opinion. You should always use that when you can. If this image will be used quite often you should enable hardware acceleration on it by calling BufferedImage().setAcceleration() with a parameter greater than 0. Read the API for details.
Comment: I have just be using java.awt.component.createImage().  Will look into using a BufferedImage and let you know how it goes.
Comment: This works, thanks very much. How I missed BufferedImage, I do not know!


Sidekiq - delay until 3 days before a variable date - is it possible?

Question: I'm using Ruby on Rails and currently using Sidekiq to delay the sending of an email to a user for 3 days (after a create action) as such:
QuickcontactMailer.delay_until(3.days.from_now).reminder(@quickcontact)

I'm trying to find out if it's possible to use a variable date instead of "from_now", something like this:
QuickcontactMailer.delay_until(3.days.from(@quickcontact.date_required).reminder(@quickcontact)

I can't find any information about it, maybe I'm asking to do a bit too much here. Any help would be great thanks.
Answer: QuickcontactMailer.
    delay_until(@quickcontact.date_required + 3.days).
    reminder(@quickcontact)

Comment: I have slightly re-formatted your answer to respect ppl with not-so-wide screens.
Comment: Typo: `s/-/+/`.
Comment: `puts 'Thank you'`
Comment: Excellent thanks very much.. Although this brings a new problem... the date_required is a string in the format "01-01-2017", which throws the error "undefined method `+' for "29-01-2017":String". I'm guessing I'll need to convert the string into the required date format? How would I do that? Still learning all of this so appreciate your help!
Comment: Try `Date.parse('29-01-2017')`
Comment: I tried `QuickcontactMailer.delay_until(Date.parse(@quickcontact.date_required) - 3.days).reminder(@quickcontact)`  but get the error `undefined method to_f'  for Thu, 26 Jan 2017:Date`  Any idea? Thanks again
Comment: Any idea on how to solve the error @mudasobwa ? Thanks!
Comment: `Date#+` already adds days. Use: `Date.parse(@quickcontact.date_required) + 3`.
Comment: I tried that as well @mudasobwa but also with the same error.
Comment: It is impossible. The error is induced. Open the console and type `Date.parse('2017-01-13') + 3`, you'll get this Monday.
Comment: If I run in the console `@quickcontact = Quickcontact.last`, followed by `Date.parse(@quickcontact.date_required) - 3` it converts the string `12-03-2017` to `Thu, 09 Mar 2017` but would it be the delay_until method not accepting it and throwing the `undefined method `to_f' for Thu, 09 Mar 2017:Date` error?
Comment: Btw, why are you storing dates as a string in the db?


How many ViewStubs is too many for a single layout XML file?

Question: I have a layout defined in an XML file(base_layout.xml) which may contain 20+ ViewStub definitions in addition to 3-5 other views such an ImageView and a LinearLayout containing 3-5 ImageButton views.
Should i be concerned about how many ViewStub views i place in this layout file?
I read on the developer.android site:

A ViewStub is a dumb and lightweight
  view. It has no dimension, it does not
  draw anything and does not participate
  in the layout in any way. This means
  that a ViewStub is very cheap to
  inflate and very cheap to keep in a
  view hierarchy

is it cheap enough to have 20+ of them? not all being inflated of course, just 1-2 at a time.
when i say cheap enough or talk of being concerned, i am regarding performance of the UI
edit:
what i am trying to accomplish:
create a layout XML file which can be the skeleton for all my of activities.  in each Activity, i will inflate the correct ViewStub with the activity's layout.  Since i have so many activities requiring the same skeleton, i wish to re-use as much as possible
I have an Activity class which is the parent of almost all of my activities.  this parent class calls setContentView(R.layout.base_layout);.  for each child activity, all i am doing is inflating the corresponding ViewStub inside base_layout.xml.  doing this allows me to have a very customized UI with the same skeleton view used on all of my activity layouts
Answer: I don't think you'll see a big performance hit. It's still cheaper than having all of them inflated from the begining.
The downside of having so many stubs is that you could lose sight of the whole design. Maybe it makes more sense to group several views/items into one viewgroup. Maybe you could explain what you're attempting to do and see if there is a better way to realize it
edit:
Well, instead of having multiple ViewStubs which include different subviews like
<ViewStub android:id="@+id/stub"
           android:inflatedId="@+id/activity1"
           android:layout="@layout/myActivity1"
           />
<ViewStub android:id="@+id/stub2"
           android:inflatedId="@+id/activity2"
           android:layout="@layout/myActivity2"
           />

just have a single ViewStub and in your acitivities onCreate() do something like
setContentView(R.layout.base_layout);
ViewStub stub = (ViewStub)findViewById(R.id.stub);

stub.setInflateId(R.id.activity1);
stub.setLayoutResource(R.layout.myActivity2);
stub.inflate();

This way you'd still have only one ViewStub in your base_layout, which you could setup in code before inflating.
Comment: ah ha! i was trying to do something like that before, except i couldn't get it working.  now that i have used your sample code there, it works like a charm. excellent.
Comment: @Tseng I need to do something similar, thanks for the info, however how do you define id activity1 without including it in a layout file?
Comment: I think the answer to my question is something like this in file res/values/ids.xml:  (I haven't tried yet though, I only need a few ViewStubs so just going to define them in xml for now).
Answer: LinearLayout or RelativeLayout is extend of ViewGroup
so i used ViewGroup as parameter
this is my solution
public CategoryViewController(Context context, ViewGroup containerView) {
        this.context = context;
        LayoutInflater inflater = LayoutInflater.from(context);
        View categoryLayout = inflater.inflate(R.layout.category_section, null, false);
        containerView.addView(categoryLayout);
        this.categoryView = categoryLayout;
}


What does $dx$ mean?

Question: $dx$ appears in differential equations, such us derivatives and integrals.
For example, a function $f(x)$ its first derivative is $\dfrac{d}{dx}f(x)$ and its integral $\displaystyle\int f(x)dx$. But I don't really understand what $dx$ is.
Comment: Although the title is not exactly the same as your question, I believe your question is answered quite thoroughly in this similar post: http://math.stackexchange.com/questions/21199/is-dy-dx-not-a-ratio
Comment: @Garmen: Please take a look at my comments under the answer you accepted. That answer is quite misleading; one of the limits is wrong, and the concept "infinitesimally small" is being used informally without a definition. While there is an interesting branch of mathematics called *non-standard analysis* that defines infinitesimal quantities, standard analysis (which is presumably what you're asking about) has no such concept.
Comment: Also: http://math.stackexchange.com/questions/23902/what-is-the-practical-difference-between-a-differential-and-a-derivative/23914#23914
Comment: good question, but you can find lot about it in web as well !
Comment: And http://math.stackexchange.com/questions/46530/can-i-ever-go-wrong-if-i-keep-thinking-of-derivatives-as-ratios
Comment: dx is a differential form. Start your search there.
Comment: @Garmen1778 : there is a new answer by Carl Mummert that is the best so far and is infinitely better than the one you accepted.
Comment: @Stefan, did you happen to notice that Garmen asked this question a year-and-a-half ago, and hasn't been seen here in over half a year? I'm afraid the damage, if any, has already been done.
Comment: @GerryMyerson : Thanks for noticing that.  Apparently this is a lost cause.  But Carl Mummert's excellent answer from today is up to 10 votes, vs. 11 votes for the accepted answer.  Maybe Carl's answer will at least end up with the most votes.
Comment: http://blog.cambridgecoaching.com/but-what-is-dx-really-calculus-terms-explained
Answer: The formal definition of an expression such as
$$
\int_0^1 x^2\,dx
$$
will depend on the setting. This is because there is not just one "theory of integration" - there are several different theories in different areas.
I like the presentation at the beginning of this note by Terence Tao. The key point is that there are really at least three different viewpoints on integration in elementary calculus:

Indefinite integration, which computes antiderivatives
An "unsigned definite integral" for finding areas under curves and masses of objects
A "signed definite integral" for computing work and other "net change" calculations.

The value of an expression such as $\int_0^1 x^2\,dx$ comes out the same under all these interpretations, of course.
In more general settings, the three interpretations generalize in different ways, so that the "dx" comes to mean different things. In the setting of measure theory, "dx" is interpreted as a measure; in  the context of differential geometry, it is interpreted as a 1-form.
But, for the purposes of elementary calculus, the only role of the "dx" is to tell which variable is the variable of integration. In other words, it lets us distinguish
$$
\int_0^1 uv\,du = v/2
$$
from
$$
\int_0^1 uv\,dv = u/2
$$
Comment: there is also a fourth interpretation of $dx$ as an infinitesimal quantity under the nonstandard setting of the hyperreal field of Robinson. Also there are other interpretations of other nonstandard settings as in smooth infinitesimal analysis, just to name a phew for the curious reader
Comment: Though this answer is years old, I just want to comment that differential geometry doesn't only use the differential form generalization. It also uses a measure-theoretic analog: *densities*, which make integration possible on manifolds even without orientation. (These are important e.g. in relativity theory.) The rough intuition here is that a form + an orientation = a density.
Answer: Formally, $dx$ does not mean anything. It's just a syntactical device to tell you the variable to differentiate with respect to or the integration variable.
Comment: IMHO this is just one, very unenlightening way to look at it.
Comment: @Michael, sorry, can't tell my math-for-poets classes that it's a differential one-form; I *can* (and do) give them lhf's answer, and they get some mileage out of it.
Comment: @Stefan Smith: I think it is quite debatable whether the "dx" in calculus 1 is a one-form. For example, a typical calculus textbook will have a formal definition of the Riemann integral, but not any mention of one-forms. This holds even for books like Rudin's *Principles of Mathematical Analysis*.  So it could appear to be somewhat revisionist to say that dx is a one-form in that context. And, even if we want to be revisionist, what is to say that "dx" is not a measure, instead of a one-form?
Comment: @Stefan, $dx$ is different things to different people. I'm guessing that for the person who asked the question, the answer posted by lhf is about right, and any attempt to tell that person about differential forms would be counterproductive.
Comment: @GerryMyerson: I've never taught math-for-poets, but I wonder if teaching such people formal laws for manipulating symbols, without telling them about the meaning of it is more valuable than trying to explain in poetic terms what a differential one form is. (Maybe something like infinitesimal coordinates?)
Comment: @lhf : your answer is incorrect.  $dx$ is a differential form.  You should delete your answer.
Comment: @Stefan Smith: what surprises me about the overall answers to this question is that I would expect to see other answers with blanket statements: "$dx$ is a differential form", "$dx$ is a measure", "$dx$ is an infinitesimal", etc. In other words there are several "correct" answers, and this is just one of them. In the context of symbolic integration, which is after all a purely syntactic enterprise, the only role of the $dx$ is to specify the variable of integration. Why not write another answer beginning with "$dx$ is a differential form"?
Comment: @Michael, I encourage you to try that approach some time and report back on the results. Actually, math-for-poets isn't really what I deal with; it's math-for-accountants and other business students.
Comment: @GerryMyerson : you don't have to tell your math-for-poets classes anything about differential one-forms, but if you tell them that formally, $dx$ does not mean anything, it's a lie.
Comment: your answer is not clear and not answer the question, because if just we consider tow function $F(x,y)$ and $G(x,y)$ defined on $\mathbb{R}^2$, what would be the meaning of $F(x,y)dx-G(x,y)dy=0$ by the use of your definition !!!?
Comment: your answer is not correct. If you see a equation with dx and dy then they mean something and it is not simply a part of a derivative or an integral description. And you can't always simply split them to solve this equation
Comment: @GerryMyerson : regardless of what one thinks $dx$ means, this answer begins with a falsehood.  The OP should be least be informed that $dx$ has a precise meaning.
Comment: The question is about the meaning not the utility of $dx$.
Comment: @CarlMummert : the accepted answer begins with a blanket statement that $dx$ does not mean anything.  That is incorrect.  And of course a calculus textbook might not mention one-forms, because differential forms are a very difficult topic that most calculus students can't handle.
Comment: Obviously it's not meaningless. It means the product of $d$ with $x$... which is my somewhat snarky way of saying that, yes, of course context determines meaning, and in this context, there is no meaning (so the answer is correct).
Comment: @GerryMyerson : also, you can tell your math-for-poets orally that it's a differential one-form in about five seconds, and then move on, and never mention differential forms again.  If you write down lhf's answer verbatim, you've lied to them.  You can easily reword lhf's idea in a form that avoids oversimplification.
Comment: The problem with "$dx$ as pure syntax" is that it leaves change-of-variables as yet another formula that must be applied by rote. A little geometric intuition ($dx$ as an infinitesimal length, which gets scaled when you change variables) goes a long way.
Comment: How's this for a compromise: "For the purposes of Math 130 at Macquarie University, $dx$ doesn't mean anything."
Comment: @GerryMyerson : I find that acceptable.  It is completely different from the wording in the accepted answer.  But if you are going to tell students that, you should tell them why they should write $dx$ at all.,
Comment: @carlmummert sorry to reply to a 7 year old comment, but the dx of freshman calculus is a 1 form, and not a measure, because the integral from a to b is the opposite of the integral from b to a.  We would just integrate a measure over an interval, and the sign wouldn't change.
Comment: @lhf : I made a comment that $dx$ is a differential one-form.  $dx$ can also be interpreted as a measure.  I don't know if there are other ways.  Either way, the first sentence of your answer is incorrect.
Comment: It's obviously not "meaningless," since with $dx$ replaced with $dy$ you get a different result. At the very least, the $dx$ indicates with variable is changing...
Answer: As Silvanus Thompson put it in his book Calculus made easy: $\mathrm dx$ means "a little bit of $x$".
If that is not satisfying, there are various more precise explanations. One of them is: $\mathrm dx$ is a differential one-form.
Comment: I think "a little bit of $x$" holds many, many advantages for engineering maths.
Comment: I mean imagine a line of length x.Then dx is an extension of the line to the right.But here why is dx a little bit of x when it is on the extension?
Comment: What is meant by a little bit of x?I mean suppose we want to calculate the value of the slope at point (x,y).Then dx means a step to the right.But this dx is not in the line segment x.So how does it mean a little bit of x?It is outside of the line segment.
Comment: @AritraBarua X is usually a variable number, which is pictured along the x axis, not along the graph of the function, so it is along the line segment of the x axis. Does that answer your question?
Comment: You could also shrink the line, instead of extending it (since the "sign" of dx could also be negative). But I agree that the expression "a little bit of" can be confusing, as you explain. Probably a better way of capturing the idea is to say that d means "a little change of", instead of "a little bit of".
Answer: $dx$ means a very very small quantity, $dx=x_2-x_1$ where $x_1$ and $x_2$ very very near to $x$ (in geometry a very small distance), when you derive $\frac{d}{dx}f(x)$ it means you calculate the propinquity of $df(x)$ and $dx$, when you integrate, the sign $\int$ means a continuous sum, so $\int f(x) dx$ means a continuous sum of all the quantities $f(x) dx$ (geometrically very very small rectangles), in graduate language $dx$ is a linear map (differential form).
Comment: If I didn't already know what $dx$ was, I don't think this answer would clear anything up for me.
Answer: The d$x$ comes from approximating the area under a curve by a discrete sum of narrow rectangular slices of heights $f(x_i)$ and equal widths $\Delta x = x_{i+1}-x_i$. Look up Riemann sum for more details. So the area is then approximately $\sum^n_{i=1} f(x_i) \Delta x$. This approximation becomes exact when $\Delta x$ becomes arbitrarily small,  which is symbolized by replacing $\Delta x$ by d$x$ (and $\sum$ by $\int$). For derivatives, similar story; just replace "area" in the above by "slope" or "gradient", where the approximation is now a chord of length d$x$ along X-direction. NB: correct notation is d$x$, not $dx$.
Answer: I have a relevant blog post for those comfortable with multivariate calculus, found here.
Though treating $\mathrm{d}x$ as simply "that thing" works, there is hidden meaning behind it. To be clear, in this case, we are using $x$ to refer to the identity function $x(t)=t$, where $t\in\mathbb{R}$.
Imagine an arrow tangent to the real line. This can be represented by a vector (magnitude and direction) and a real number (position). We call such a vector a tangent vector. If the vector is $v$ and the position is $p$, then we denote the corresponding tangent vector* by $v_p$.
Mathematicians define $\mathrm{d}x$ as a type of function, called a differential $1$-form, that takes in a position $p$ and outputs a so-called "dual" tangent vector, or cotangent vector, which we call $\mathrm{d}x_p$. This $\mathrm{d}x_p$ is, somewhat confusingly, a function on the tangent vectors positioned at $p$. In the case of real numbers, though, the expression for $\mathrm{d}x_p$ is easy: $$\mathrm{d}x_p(v_p)=v.$$
Though many people will prefer to work with the (arguably more rudimentary) notion of "infinitesimals", differential forms have many advantages over the "old way". For example, change of variables, commonly known as $u$-substitution, has a simple formula in terms of something called the "pullback". As another example, when we move on to calculus on spaces that aren't strictly Euclidean, these differential forms give powerful information about the space itself, such as (in some sense) how many holes it has.
(* For the professionals, what I am meaning here is that $v_p=v\left.\frac{d}{dx}\right|_p$. Feel free to heckle in the comments.)

What does $dx$ mean?


How to solve an equation of third degree?

Question: I'm trying to solve this equation $x^3+bx^2+cx+d = 0$ and try to follow the steps from my notebook, but I barely understand my writing.
$(x+b/3)^3+bx^2+cx+d-xb^2/3-b^3/27$
$(x+b/3)^3+bx^2+x(c-b^2/3)+d-b^3/27$
Let $y= x+b/3$
$y^3+qy+r = 0$
I found out that $ q = (c-b^2/3)$ and $ r = d + (2b^3-3bc)/27.$ Is it correct ?
Let $y= \alpha + \beta $
$(\alpha+\beta)^3+q(\alpha+\beta)+r = 0$
$\alpha^3+3\alpha^2\beta+3\alpha\beta^3+\beta^3+q(\alpha+\beta)+r = 0$
$\alpha^3+\beta^3+(3\alpha\beta+q)(\alpha+\beta)+r = 0$
Then it says that $ \alpha^3+\beta^3 = -r $ and $\alpha\beta = -q/3 $. I can't figure out why.
Equation $t^2+rt-q^3/27=0 $ has the roots $ \alpha^3, \beta^3.$ I know this is from Vieta's formulas.
$ t_{1,2} = \frac {-r\pm\sqrt{r^2-4q^3/27}}{2}$
$\alpha_0 = \sqrt \alpha^3, \beta_0=\sqrt \beta^3$
$\alpha^3 = t_1$ has the roots $ \alpha_0,\epsilon\alpha_0,\epsilon^2\alpha_0.$
$\beta^3 = t_2 $ has the roots $ \beta_0,\epsilon\beta_0,\epsilon^2\beta_0.$
I'm lost here. I think that by $\epsilon$ he ment $\frac {cos2\pi}3 +i\frac {sin2\pi}3$. I don't understand why those are the roots.
The solutions of the equation $y^3+qy+r=0$ are $\alpha_0+\beta_0,\epsilon\alpha_0+\epsilon^2\beta_0,\epsilon^2\alpha_0+\epsilon\beta_0.$ Okay, but why ?
$ q = -1, r = 1.$ This makes no sense to me.
$\alpha_0 = \sqrt[3]{\frac {-1+\sqrt {1-4/27}}2} $
$\beta_0 = \sqrt[3]{\frac {-1-\sqrt {1-4/27}}2} $
$\alpha_0+\beta_0 \in R$
And that's all I have about cubic equations. I have the feeling that is uncomplete.
Comment: There are some nice answers in questions on the right side of the page under "related questions", which should show you how to solve cubic equations.
Comment: If your question is about understanding your own notes, this is a relatively individualized effort and you should really be the one to lead the project.  First, do you understand the overall approach?  Then, worry about understanding the details of the steps in that approach.
Comment: @SimpleArt I'm interested in this approach in particular. Maybe similar approaches.
Comment: @hardmath My question is about the algoritm and the steps that I don't understand.
Comment: :/ solving any polynomial algorithmic-ly should usually be done with Newton's method or similar.
Comment: Have you tried doing an example?  It would help you to find what you do and do not understand "about the algorithm".
Comment: @SimpleArt I'm not trying to solve any polynomial. I just want a simple algoritm for solving a cubic polynomial and I want to understand it.
Comment: @hardmath Yes, I have. And it didn't help me to understand what those steps do.
Answer: Hints.
1) Transform the equation to the form $x^3 + 3bx + c$. I see you already did it. In your case you have the form $y^3 + qy + r$ which is exactly the same.
2) Smartass trick: let $y = w - \frac{b}{w}$. This transforms the equation into $$w^3 + c - \frac{b^3}{w^3} = 0$$ which is a quadratic in $w^3$. So solve this
3) You now have a value for $w$.
Can you find then a root now?
Answer: The general strategy is to eliminate the quadratic term first, so as to have an equation in standard form $y^3+py+q=0$.
Then, Cardano's method replaces the single unknown $y$ by two unknowns $u$ and $v$ such that $y=u+v$. This introduces one degree of liberty, as physicists say. This allows to add a constraint, which will simplify the equation, namely  eliminating the term with factor $u+v$.
Finally it comes down to determining two numbers $u$ and $v$, knowing the sum of their cubes, and their product. A problem, which in turn comes down to determining $u^3$ and $v^3$, knowing their sum and their product – a classical problem on quadatic equations.


Memory warnings in IPAD app with UITabbar of 8viewControllers

Question: My application which is a UITabbar app has eight tabs. one tab for playing Audio, one for Playing Videos, one for Books(Leavesview is used for opening jpg image pages),one for Gallery.....so on.
So, Once I open all tabs the app throws memory warnings and crashes.
Then I did this: In each tabs viewController, I have allocated everything(views, imageViews.....) in ViewDidAppear method then I did removeFromSuperView and release in ViewDidDisappear method.Even then the problem persists.
Using Activity Monitor I observed that the app crashes when it exceeds 128 MB of Memory.
Each tab's ViewController is Occupying around 40MB memory. Even though I release everything in the ViewDidDisapper of the tab the memory is not freed but kept on increasing.
Is there anything regarding memory I have missed.  Please Help me resolve this ,   Thank You.
Answer: I have noticed that when instantiating a UITabBarController it loads all it's dependencies and is really stubborn when trying to release an entire UIViewController. I've done a few things to combat this when I've had high memory UIViewControllers attached to a UITabBarController. What I suggest is only releasing the memory hog controls associated with each UIViewController on the ViewWillDisappear and re-Instantiating them on the ViewWillAppear rather than trying to release the entire UIViewController. Typically this is bad practice because you want to recycle as many of the controls as possible but if you have to stick with the UITabBarController this is the only way I've been successful.
If I misread your post and you aren't trying to release the UIViewController the I would need to see some code to figure out why things aren' releasing on ViewWillDisappear.
Comment: I did the same but used viewDidAppear and viewDidDisappear methods. In viewDidAppear I allocated all the subview and added to self.view, in viewDidDisappear I removed all the subviews from superview and released.


vim mapping a plugin and providing argument coming from an external script

Question: I use ConqueGdb plugin on a fairly frequent basis for my debugging needs. I decided to set a mapping for it to make my life a little easier. Below is what my mapping looks like -
map gd :ConqueGdb ./binary_name !script_which_returns_pid_of_binary
OR
map gd: ConqueGdb ./binary_name str2nr(system('~/bin/which_pid.sh'))
I noticed that the script in this case is not getting evaluated but instead being pasted as text. Then I tried again by wrapping this script in a function which returns the pid  -
map gd :ConqueGdb ./binary_name call GETPID()
Same issue persisted.
Finally, I created a function and within in, I added the
ConqueGdb ./binary_name pid_variable
But here too the same issue prevails (i.e. pid_variable gets passed as text rather than being evaluated to the value it holds).
What am I doing wrong and how can I get vim to use the value stored in the variable rather than assume it is plain text?
TIA.
Answer: It seems you're looking for :exe
I guess something like:
exe ':ConqueGdb ./binary_name'. str2nr(system('~/bin/which_pid.sh'))

Instead of ./binary_name you could also use a variable that you assign somewhere else (like a local vimrc that acts as a plugin that defines your project (preferences & more))


Nested for loop performance in comparing 2 large data frames

Question: I have 2 data frames see 2 examples below . The first is about 3 330 076 lines and the second 400k.
The requirement is fairly simple if the "item code"  in the second dataframe == the article code in the first AND the salesdays entry in dataframe 1 falls between or is equel to "the start" and "end date" entry . Then add a count to the promo count column in dataframe 1 . Below is the nested for loop i attempted but the runtime is more than 2hours without it actually completing . Any help will be greatly appreciated
for ind , row in SalesDF.iterrows():
    for j ,row2 in SfPromos.iterrows():
        if (row['article'] == row2['Item Code']) and (row2['Start date'] <= row['SalesDays'] <= row2['End date']):
            row['PromoCount'] += 1
print(SalesDF['PromoCount'] > 0)

The requirement is fairly simple if the "item code"  in the second dataframe == the article code in the first AND the salesdays entry in dataframe 1 falls between or is equel to "the start" and "end date" entry . Then add a count to the promo count column in dataframe 1 . I attempted but the runtime is more than 2hours without it actually completing .
Comment: iterating 3Mio * 400k lines takes half a year if every operation takes one microsecond. You need to get off of quadratic scaling if you have data this large. Try to gather stats on ShopritePromos (without even reading SalesDF) than integrating that info back into SalesDF.
Comment: What exactly is in the 'SalesDays'-column? The 's' implies it is a number of days or a range of dates, but you are comparing it to single dates, implying SalesDays is a date.
Comment: SalesDays ==( single date) needs to be in between or equal to Start date and End date
Answer: I am not sure what you want to have as your output but i think that you may try to experiment with join + group by
Below i am doing left join which is going to combine items with promotions and create some statistics as already mentioned in comment
You can then join them back to original df
import datetime
import pyspark.sql.functions as F

sales = [
    (datetime.date(2022, 7, 4), 10123762, 50, 0),
    (datetime.date(2022, 7, 1), 10123762, 50, 0),
]
promos = [
    (10123762, datetime.date(2022, 7, 3), datetime.date(2022, 7, 5)),
    (10123762, datetime.date(2022, 7, 4), datetime.date(2022, 7, 4)),
]

dfSales = spark.createDataFrame(
    sales, schema=["SalesDay", "article", "TotalSales", "PromoCount"]
)
dfPromos = spark.createDataFrame(promos, schema=["Item Code", "Start date", "End date"])

joinedDf = dfSales.join(
    dfPromos,
    (dfSales["article"] == dfPromos["Item Code"])
    & (
        (dfPromos["Start date"] <= dfSales["SalesDay"])
        & (dfSales["SalesDay"] <= dfPromos["End date"])
    ),
    "left",
)

joinedDfWithMatchFlag = joinedDf.filter(joinedDf["Item Code"].isNotNull()).withColumn(
    "Promo Matched",
    F.when(F.col("Item Code").isNotNull(), F.lit(1)).otherwise(F.lit(0)),
)
statistics = joinedDfWithMatchFlag.groupBy("article", "Item Code").agg(
    F.sum("Promo Matched")
)

statistics.show()

Output:
+--------+---------+------------------+
| article|Item Code|sum(Promo Matched)|
+--------+---------+------------------+
|10123762| 10123762|                 2|
+--------+---------+------------------+

Comment: this is a very interesting approach , i will check it out . The goal is to count the number of promotions an article/item code  is on per day . The dataframes are different sizes  . the below error got generated    ValueError: Can only compare identically-labeled Series objects


Help calculating integral

Question: I need help calculating a integral. It is a Pareto distribution with common tail $\frac{1}{(1+x)^a}$, where I assume countermononicity between two variables $X_1$ and $X_2$.
$\int_0^1 ( (\frac{1}{1-x})^{-a}-1) ( (\frac{1}{1-(1-x)})^{-a}-1) dx $
when I type this in matlab it answers that I have to define a, but I do not know why I need that?
Can anyone help calculating this and the procedure?
Regards, Søren
Answer: If there is no typo in your question it amounts to computing
$$\int_0^1 x^a(1-x)^a\text{d}x-2\int_0^1 x^a\text{d}x+1$$which should not be a problem.
Comment: @Xi'an - this is true but at the same time the beta integral is tough to do from scratch - similar to working out the characteristic function of the Cauchy distribution.  Just one of the integrals stats people "know"!
Comment: If I use partial integration, I keep up getting some nasty integrals and I do not come closer to any solution.
Is partial integration the correct technic or is there some other way.
Comment: HInt: No need for partial integration: the first integral is connected with the normalising constant of a [Beta distribution density.](https://en.wikipedia.org/wiki/Beta_distribution).

Help calculating integral


Find the volume inside a cylinder and outside a hyperboloid

Question: I'm trying to find the volume of $f(x,y,z)=y$ inside the cylinder $x^2+y^2=4$ and outside the hyperboloid $x^2+y^2-z^2=1$,
and I got the integral
$\int_0^{2\pi} \int_0^y \int_1^\sqrt{1+z^2} rdrdzd\theta$
thank you!
Comment: What did you try so far?
Comment: I tried to change it in cylindrical coordinates, and I got stuck
$r^2=4, \Rightarrow 4-z^2=1, z=\sqrt 3$
$\int_0^{2\pi} \int_\sqrt 3^y \int_2^\sqrt{2-r^2}rdrdzd\theta$
Comment: There should be no $y$ anywhere in the limits. $y$ is not one of the cylindrical coordinates.
Comment: my mistake, then
$\int_0^{2\pi} \int_?^? \int_2^\sqrt{2-r^2}$
Comment: **Integral** of the function. And you are forgetting the integrand...
Answer: Cylinder:
$$
x^2+y^2 = 4\implies r = 2.
$$
Hyperboloid:
$$
x^2 + y^2 - z^2 = 1\implies z^2 = r^2 - 1\implies
r = \sqrt{z^2 + 1}.
$$
Now, you need to find the intersection between cylinder and hyperboloid... Can you continue?