Do I really need to add time as random effect in mixed model for repeated measures?

Question: I'm fitting a mixed model to explore effects of weather conditions (A,B, C; all factors) and their interactions on response Y (continuous). Study included several subjects and measures have been taken (for every subject) on many days. I'm not interested in the effect of time (or day).
I'm selecting fixed explanatory variables based on AIC. I started the selection process with just subject as random effect
fm1 <- lmer (Y ~ A*B*C + (1|subject), df)

everything ran smoothly and I obtained an interesting "final" model with all main effects and one interaction being significant. I tried the same process adding day as random effect
fm2 <- lmer(Y ~ A*B*C + (1|subject) + (1|day), df)
> anova(fm1,fm2)
refitting model(s) with ML (instead of REML)
...
    Df    AIC    BIC  logLik deviance  Chisq Chi Df Pr(>Chisq)
fm1 22 8011.0 8111.5 -3983.5   7967.0
fm2 23 7944.9 8049.9 -3949.5   7898.9 68.097      1  < 2.2e-16 ***

and I obtained significantly lower AIC's but ended up with just one significant factor and, in my view, with much less interesting results.
Now my questions are:
-are the random structures in fm1 and fm2 specified correctly for this design?
-do I need to include (1|day) in the model (even if I lose much of the effects I'm studying)?
Any help or comment is very appreciated. Thanks.
Comment: It could make sense if you had repeated measures within subject and day.
Answer:
I'm selecting fixed explanatory variables based on AIC

Do you mean to say that in addition to A, B, and C, there are some potential fixed effects that you threw out on the basis of an AIC-based model selection? If you want to consider all the potential fixed effects and also the question of whether to include a random effect of day, then you should be looking at the AIC of all the combinations, rather than using AIC to choose the fixed effects and then doing a separate AIC-based comparison for choosing the random effects.

I obtained significantly lower AIC's

The way you're supposed to use AIC for model selection is just to choose the model with the lowest AIC. If you're using a significance test here, you're doing something wrong.

are the random structures in fm1 and fm2 specified correctly for this design?

They both seem consistent with the very limited information you've given us about the design of the study.

do I need to include (1|day) in the model (even if I lose much of the effects I'm studying)?

There are lots of ways to select models, some of which are reasonable and some of which are unreasonable. AIC has at least some arguments in its favor. On the other hand, choosing a model because it gets more interesting results, or because it has a larger number of significant coefficients, makes no sense.


How can I make required cck date field "not required" by hook_form_alter?

Question: I could make some requited cck fields "not required"  by hook_form_alter a below but this doesn't work for date field.
for selection type
function hook_form_alter(&$form, &$form_state, $form_id) {
$form['field_smaple_1']['#required'] = 0;
}

or
for text are type
function hook_form_alter(&$form, &$form_state, $form_id) {
$form['field_sample_2']['0']['#required'] = '';
}

How can I do the same thing for date field?
Answer: To alter date field required to disable, you can use following snippet in your form alter
$form['#field_info']['field_date']['required']=0; //field_date use your field name


Nomes e tipos de dados Lua

Question: Sobre nomes e tipos de dados na linguagem Lua. Qual é o tamanho máximo de um nome? É permitida a definição de tipos Enumeração, Subfaixa, Registro e União? Não encontrei essas informações na documentação.
Comment: Com "nome" você quer dizer nome de variável/função?
Comment: Sim, variável/classe
Answer: Qual é o tamanho máximo de um nome?
Lua não possui um tamanho máximo para os nomes de variável. Internamente, basicamente os nomes são só strings.
Possui o tipo Enumeração?
Hoje ainda não suporta enumerações por padrão. Existem bibliotecas que tentam criar algo parecido como o lua-enum, ou você pode também simplesmente criar uma table:
local dias_da_semana = {
    ["SEGUNDA"] = 1,
    ["TERÇA"] = 2,
    -- ...
}

print(dias_da_semana.SEGUNDA) -- E então usar desta forma

Mas como esperado, não terá o mesmo comportamento de uma enumeração de verdade.
Possui o tipo Subfaixa?
Não, na linguagem não tem nada pronto para isso também.
Possui o tipo Registro?
Também não. O mais próximo que você vai conseguir é usando as tables, que podem servir com registros dinâmicos:
local registro = {
    x = 1,
    y = nil
}

Possui o tipo União
Não! E acho que nem faz muito sentido em uma linguagem com tipagem dinâmica. :v

Nomes e tipos de dados Lua


with BEF collapse expand items under their parent

Question: How to collapse and expand items under their parent using better exposed filter and Nested Checkboxes ..
What i mean ...that all the child items to be collapsed and they expand when the user click on (+ e.g) for the parent or check the parent box.
I am making a car dealer website and i need that to make an advanced search.
Any help will be appreciated.
Comment: Update: any help please
Comment: You will need to write some custom JavaScript to get the nested lists to expand/contract. There are several jQuery plugins that will do this as well as come custom code [as shown here](https://drupal.org/node/990080).
Answer: I fixed this issue and here is the solution for any one want to do the same, based on this conversion Collapse and Expand according to Hierarchy
add this code to your theme and you can use this module to add Javascript or CSS through the views page or block Code per Views Display
This code will add a + button beside the every parent, which will expand the checkboxes when clicked
(function ($) {
Drupal.behaviors.betterExposedFiltersExpandCollapseNested = {
attach:function (context, settings) {
  if (!('$befSetupDone' in window)) {
    $('ul.bef-tree-child.bef-tree-depth-1').css('display', 'none');
    var $expander = $('+');
    $('ul.bef-tree-child > li:has(ul) > div.form-item').prepend($expander);
    $('.expander')
      .click(function() {
        $ul = $(this).parents('li:first').find('ul');
        $ul.toggle('fast');
     })
    $befSetupDone = 1;
  }
 }
 }
 }) (jQuery);

and another code which will expand when the parent checkbox checked
(function ($) {
Drupal.behaviors.betterExposedFiltersExpandCollapseNested = {
attach:function (context, settings) {
  // first collapse the children
  $('ul.bef-tree-child.bef-tree-depth-1').css('display', 'none');
  $('.form-checkboxes.bef-select-all-none li').has('ul').once('bef-tree', function () {
    $(this)
      .find('input.form-checkboxes:first')
      .click(function() {
        $ul = $(this).parents('li:first').find('ul');
        if($(this).attr('checked')) {
          $ul.slideDown('fast');
        }
        else {
          $ul.slideUp('fast');
        }
      })
   });
  }
 }
}) (jQuery);

Note: You will have to choose (Nested Checkboxex/Radio Buttons) and check this option in better exposed filter

Add select all/none links
Answer: Based on the code from Ahmed Hassan, I added functionality:

keyboard navigation
checkbox hidden on parent nodes
aria, labels and other accessibility functionality
/**
 * @file store_better_exposed_filters_expand.js
 *
 * Provides some client-side functionality for the Better Exposed Filters expand/collapse of taxonomy terms
 *
 * Kevin Finkenbinder
 * Added keyboard interface, aria labels and functionality, removed checkbox in front of parent nodes
 * Based on the work of Ahmed Hassan (https://drupal.stackexchange.com/a/109214/19071)
 */
(function ($)
{
  Drupal.behaviors.betterExposedFiltersExpandCollapseNested = {
    attach: function (context, settings)
    {
      if (!('$befSetupDone' in window))
      {
        $('bef-tree').attr('role', 'tree');
        $('bef-tree-child').attr('role', 'treeitem');
        $('bef-tree-child ul').attr('role', 'group');
        $('bef-tree-child li').attr('role,treeitem');
        $('ul.bef-tree-child.bef-tree-depth-1').css('display', 'none');
        $('.bef-tree-child input').attr('tabindex', -1);
        var $expander = $('+');
        $('ul.bef-tree > li:has(ul) > div.form-item').prepend($expander);
        $('ul.bef-tree-child > li:has(ul) > div.form-item').prepend($expander);
        $('.expander').each(function (index)
        {
          $(this).attr('id', $(this).next().attr('id'));
        });
        $('ul.bef-tree > li:has(ul) > div.form-item > input ').remove();
        $('ul.bef-tree-child > li:has(ul) > div.form-item > input').remove();
        $('.expander').first().attr('tabindex', 0); /* tab to control but not individual elements - see accesssibleculture.org/articles/2013/02/not-so-simple-aria-tree-views-and-screen-readers/ */
        $('ul.bef-tree-child.bef-tree-depth-1').css('display', 'none');
        $('ul.bef-tree-child').css('list-style-type', 'none');
        $('ul.bef-tree').css('list-style-type', 'none');
        $('.expander').css('cursor', 'pointer');
        $('.expander').on('click keydown', function (event)
        {
          if (event.which == 32 || event.which == 13 || event.which==1) /*spacebar,enter or mouse click*/
          {
            $ul = $(this).parents('li:first').find('ul');
            $ul.toggle('fast');
            event.preventDefault();
            return false;
          }
          else if (event.which == 37) /*left arrow */
          {
            if ($(this).parents('li:first').find('ul').is(":visible"))
            {
              $(this).parents('li:first').find('ul').hide();
              event.preventDefault();
              return false;
            }
          }
          else if (event.which == 38) /*up arrow */
          {
            if (!$(this).closest("li").is(':first-of-type'))
            {
              if ($(this).closest("li").prev().find('ul').is(':visible'))
              {
                $(this).closest("li").prev().find("ul li:last div input:checkbox").focus();
              }
              else
              {
                $(this).closest("li").prev().find(".expander").focus();
              }
              event.preventDefault();
              return false;
            }
          }
          else if (event.which == 39) /*right arrow */
          {
            if ($(this).parents('li:first').find('ul').is(":visible"))
            {
              $(this).parents('li:first').find('ul input').first().focus();
              event.preventDefault();
              return false;
            }
            else
            {
              $(this).parents('li:first').find('ul').show();
              event.preventDefault();
              return false;
            }
          }
          else if (event.which == 40) /*down arrow */
          {
            if ($(this).closest('li').find('ul').is(':visible'))
            {
              $(this).closest('li').find('ul li:first div input:checkbox').focus();
            }
            else if (!$(this).closest("li").is(':last-of-type'))
            {
              $(this).closest("li").next().find(".expander").focus();
              event.preventDefault();
              return false;
            }
          }
        });
        $('.bef-tree input:checkbox').on('keydown', function (event)
        {
          if (event.which == 37) /*left arrow */
          {
            $(this).parents('li:eq(1)').find('.expander').first().focus();
            event.preventDefault();
            return false;
          }
          else if (event.which == 38) /*up arrow */
          {
            if ($(this).closest('li').is(":first-child"))
            {
              $(this).parents('li:eq(1)').find('.expander').first().focus();
            }
            else
            {
              $(this).closest('li').prev('li').find(':checkbox').focus();
            }
            event.preventDefault();
            return false;
          }
          else if (event.which == 40) /*down arrow */
          {
            if ($(this).closest('li').is(":last-child") && !$.isEmptyObject($(this).parents('li:eq(1)').next().find('.expander')))
            {
              $(this).parents('li:eq(1)').next().find('.expander').focus();
            }
            else
            {
              $(this).closest('li').next().find(':checkbox').focus();
            }
            event.preventDefault();
            return false;
          }
        });
        $befSetupDone = 1;
      }
    }
  }
})(jQuery);

Comment: Link to my display in case needed.  https://drupal.stackexchange.com/a/266489/19071
Answer: Here is what I used to output the field in a hierarchy.  Note, I include this using Display Suite Code Fields, but it could easily be placed in a module.
<?php

function map_leaves($term_parents, &$term_tree, $depth = 0) {
  if (!isset($term_tree[$term_parents[$depth]->name])) {
    $term_tree[$term_parents[$depth]->name] = NULL;
  }
  if ($depth < count($term_parents) - 1) {
    map_leaves($term_parents, $term_tree[$term_parents[$depth]->name],$depth + 1);
  }
}

function output_term_tree($term_tree) {
  $return = '
' . PHP_EOL;
  foreach ($term_tree as $term_name => $children) {
    $return .= '
' . PHP_EOL . $term_name . PHP_EOL;
    if (!empty($children)) {
      $return .= output_term_tree($children);
    }
    $return .= '
' . PHP_EOL;
  }
  $return .= '
' . PHP_EOL;
  return $return;
}

$node = node_load(explode('/', $_GET['q'])[1]);

$terms = $node->field_library_space_equipment['und'];
$term_tree = [];
if (!empty($terms)) {
  foreach ($terms as $term) {
    $term_parents = array_reverse(taxonomy_get_parents_all($term['tid']));
    map_leaves($term_parents, $term_tree);
  }
}
unset($term_tree['Space Location'], $term_tree['Space Types']);
$return = output_term_tree($term_tree);
echo $return;
?>


Using puppet to configure puppet master

Question: I'm starting to use puppet and in configuring the puppet master I feel I'd like puppet to maintain that host as well.  What's curious is that I see no recommendation or even much discussion for or against, which has me wondering if there's a reason.
I imagine something like this to bootstrap on host creation (pseudo-shell-script):
git clone git://github.com/me/puppit.git /etc/puppet/
puppet apply puppetmaster.pp

and then running puppetd on that host as well so that it pulls the catalog from puppetmasterd (same host) and so stays appropriately configured.
Answer: That's pretty much how I do it.  Depending on the exact situation, there will likely be some other commands to run (installing Ruby, Puppet itself), but in general I just have a deploy shell script in the root of the repo which does the necessary, including an initial Puppet run to get the machine bootstrapped.
Answer: I also manage my company's Puppet server with Puppet.
I used to work like this:
I've configured a hiera role (using a custom fact) which is called Puppet and then I'd configure everything related to the puppet server in the role.yaml file.
But since then, I've changed it to having a puppet.fqdn.yaml in the hieradata/fqdn folder and now when I want to change Puppet's configuration I edit that file.
Comment: Hiera is so often recommended in the sense of "eventually you'll realize you need it", why'd you switch away?
Comment: Because Puppet server is exceptional and I think it's safer that way.
Answer: What is your question exactly? I always use Puppet to manage the master itself. -- Even though the initial puppetmasterd installation may be manual or only shell-scripted.

Using puppet to configure puppet master


Computers can't deal with limit of $\Delta x \to 0$

Question: While I was studying about finite differences I came across an article that says "computers can't deal with limit of $\Delta x \to 0$ " in finite differences.But if computers can't deal with these equations does anybody know how they compute $ \frac {d}{dx}$ of $x^2$ and other such equations.Or whether these equations are pre-written.
Comment: After pew's answer, have a look at http://en.wikipedia.org/wiki/Automatic_differentiation. This would be interesting for you. Otherwise, numerical differentiation is very often used.
Comment: @ClaudeLeibovici:Are you saying that Automatic differentiation uses neither finite differences nor derivatives but rather use a number of pre-defined steps to compute derivative?
Comment: @justin the computers always follow some pre-defined steps. What these steps are depends on how you program it. You may use some very primitive definition and then use some set of axioms and definitions from which you _derive_ all the derivatives including such primitive as of $x^2$. Another way would be to tabulate the most common functions and their derivatives and use several rules like chain rule, derivative of composition etc. and get the derivatives of more complex functions this way.
Comment: @justin. Not at all ! In this kind of system, you enter the code for a function and it returns to you the analytical derivative. Have a look at https://www-sop.inria.fr/tropics/ad/whatisad.html. Their software Tapenade is on-line for free.
Comment: @ClaudeLeibovici:could you explain 'analytical derivative' or whether it simply means derivative.
Comment: @Ruslan:The reason why I asked this question is I really want to know whether they are any advantages of using finite differences in computer-science field while we compare it with differential calculus.I heard that finite differences might be good at solving ODE's compared to latter.Is that right or what's the reason behind this?
Comment: By "analytical derivative", I mean the formula which gives the exact derivative.
Comment: Finite differences are a numerical technique. It only gives exact results when the function you're trying to differentiate is linear. All what finite differences can generally give you is an approximation of the derivative. But there are lots of applications where it's impractical to use exact expressions. Exact formulas may be too large to handle and thus not useful for human when what is actually needed is some sort of approximation, e.g. with relative error of $10^{-6}$. Also, some differential equations are nearly impossible to solve exactly, so one uses numeric algorithms.
Comment: @Ruslan:Do you mean that $\sin$ and other series are represented using 'finite differnces' or could you mention an expression where it's derivative formula is impossible to express using an exact derivative formula.I think sin and other series are very large.
Comment: @justin $\sin x$ isn't a series. It's a function. Its derivative is $\cos x$. There's no elementary function for which a derivative would be impossible to exactly express in terms of elementary functions.
Comment: @Ruslan:So I couldn't get what you meant by "Exact formulas may be too large to handle".Are you saying that no formula really exist.Or could you mention a formula or expression which might be too large to handle.
Comment: See [this](http://www.wolframalpha.com/input/?i=derivative+of+ArcCsc%5Bx%5D%5Ex%5E2%5E%28x+Sqrt%5BArcSec%5Bx%5D%5D%29). This is not really large, but just an example I could make up.
Comment: @Ruslan:oh thanks.If we use finite difference can we solve this derivative?
Comment: Derivative is not a problem or equation. It can be _found_, not solved. Anyway, you can use finite differences to approximate this derivative to arbitrary precision, of course, but not to find exactly.
Comment: @Ruslan:Do you know why some ODE's can only be solved only using finite differences or whether there is any ODE that can't be solved using differential equations.
Comment: You are not obliged to use finite differences for numerical calculations. You can use finite elements, Fourier series expansion, Frobenius method (which sometimes may give exact results), many other techniques. An example of what you can't solve in terms of elementary functions is [Bessel equation](http://en.wikipedia.org/wiki/Bessel_function).
Answer: A table of the derivatives of primitive functions combined with differentiation rules yields an algorithm that allows a computer program to symbolically compute the derivative of any function that is a compound of primitive functions without having to rely on the limit definition at all (computer algebra).
In fact, unlike symbolic integration, this algorithm is fairly easy to implement.
Edit: It can only be re-emphasised that symbolic integration is a different matter entirely. In fact, while every function that is comprised of elementary functions has an elementary derivative, the same is not true for the antiderivative. This is a consequence of Liouville's theorem and finds application in the Risch "algorithm" (which is not an algorithm in the strict sense).
Comment: whether computer solve ODE using differential equations or whether it solves using finite differences?
Comment: @justin: That depends on the system being used and is a very complex question. Some systems use a hybrid approach even when numerically solving ODEs, i.e. they first transform the equation symbolically (e.g for better stability properties) and then use Runge-Kutta or similar to generate a numeric solution.
Comment: :Whether the algorithm you mentioned uses finite differences to compute derivative?Because I couldn't understand what you meant by "unlike symbolic integration".
Comment: @justin: Symbolic differentiation algorithms do not use finite differences. I added some more information about symbolic integration before reading your comment, but in practice (industry application etc.), ODEs are ***almost always*** solved numerically only, for example using [Runge-Kutta-like methods](http://en.wikipedia.org/wiki/Runge%E2%80%93Kutta_methods) which proceed in "small" (but not infinitesimal) steps. Such methods will produce a numerical trajectory of the integral given a fixed initial value but *not* a symbolic representation ("formula") of the antiderivative.
Comment: :I couldn't understand the term 'symbolic differentiation'.I looked in wikipedia but it says about algorithms.
Answer: This is not an answer but an illustration of automatic differentiation of a formula (I used Tapenade software online).
The source code I submitted is
<code>  SUBROUTINE DUMMY(X,Y)
    Y = X ** 2
  END
</code>
which was interpreted as
<code>  SUBROUTINE DUMMY(x, y)
  IMPLICIT NONE
  REAL x , y
  y = x**2
  END
</code>
and what I received is
<code>  SUBROUTINE DUMMY_D(x, xd, y, yd)
  IMPLICIT NONE
  REAL x , xd , y , yd
  yd = 2*x*xd
  y = x**2
  END
</code>
which now computes both the function $y$ and its derivative $\frac{dy}{dx}$ ($xd=x$).
Comment: nice illustration.But could you show with derivative of $x^2$.I think that would be simple to understand much better.
Comment: that's good.But did they compute derivative of $x^2$ using just a predefined step i.e it's derivative would be $2x$ or using any formula?
Comment: They use the same rules as you do !
Comment: okay.The reason why I asked this is whether it might be good if we use finite differences to compute a derivative or is there any place where finite differences are used to compute a derivative?


Como implementar UI como o recent do Lolipop

Question: estou tentando implementar UI como o recent do Lolipop preciso saber se é possível e se  posso faze-lo com RecyclerView e CardView?
Answer: Primeiramente, é importante saber que o Android Lollipop utiliza o Material Design, que é um conjunto de práticas e padrões de design ( cores, ícones,
   tipografia, animações, layouts, etc). Portanto, se
   você seguir estas regras do Material Design, o seu app ficará com uma
   ótima UI.
E sim, é possível( e recomendável ) implementar o Material Design usando Recycler Views e Card Views. Lembrando que se você for implementar o Material Design em dispositivos com API inferior a do Lollipop, será necessário você utilizar a biblioteca de suporte adequada. Aqui está exemplo de como implementar a UI do Lollipop.
https://tasafo.wordpress.com/2015/03/23/utilizando-material-design-em-android/


Change named range reference to be a combination of two other named ranges

Question: i am currently working on a app that is a combination of java + vba.
What i want to do:
Some of the data is exported to excel with the help of the apache poi library in the form of a table. I am using this table to define a couple of sub tables that contain the same information, just not the whole table, for example my main table has columns A to F and 300 rows of info, my sub table has column A to C with 150 rows of info. What i do is declare via apache poi 2 different named ranges, one for the header of the table and a second one for the exact content that i want. My goal is to combine these 2 named ranges into one by joining the references, since i want it as a separate table that i will export to a powerpoint template containing placeholders for these tables.
What i have:
I will show just the vba code, since i don't have any problems with the java part.
Public Sub test()

Dim rangeHeaderValue As Variant
Dim rangeContentValue As Variant

rangeHeaderValue = ThisWorkbook.Names("TABL1_Performance_Data_1").RefersTo
rangeContentValue = ThisWorkbook.Names("TABL2_Performance_Data_1").RefersTo
ThisWorkbook.Names.Add Name:="test", RefersTo:=Right(rangeHeaderValue, (Len(rangeHeaderValue) - 1)) &
";" & Right(rangeContentValue, (Len(rangeContentValue) - 1))

End Sub

What i receive as reference to the named range:
="Performance_Data!$A$10:$Q$14;Performance_Data!$A$14:$Q$18"

What i expect: The same, but without quotes, since it doesn't work for some reason. What may be the problem or is there any type of better solution? I am not really experienced with VBA, sorry in advance.
Tried doing it with Union, but it gives me errors because it expects ranges and the ranges of the named ranges change dynamically, a.k.a on each export, since the data is different.
Comment: Does changing ";" to "," the trick?
Comment: Nope, i am still not sure why it adds quotation around the reference.
Answer: add an =-sign: (and the , instead of the ;)
Public Sub test()

Dim rangeHeaderValue As String
Dim rangeContentValue As String

rangeHeaderValue = ThisWorkbook.Names("TABL1_Performance_Data_1").RefersTo
rangeContentValue = ThisWorkbook.Names("TABL2_Performance_Data_1").RefersTo
ThisWorkbook.Names.Add Name:="test", RefersTo:="=" & Right(rangeHeaderValue, (Len(rangeHeaderValue) - 1)) & "," & Right(rangeContentValue, (Len(rangeContentValue) - 1))

End Sub

Comment: Just tried it right now, worked like magic, thank you!


Im trying to create a translator but i am getting a syntax error

Question: So I am trying to get this python to work but when I run it I get a syntax error after 'for space'.
I have tried putting a colon there but even when it is there it still says the same error.
with open("text.txt", "a") as save:
        dot = '\n' + x + ' ' + ' ' + entry.get() #For new line empty spaces
    for space
        save.write(dot)

Comment: What are you trying to do here? Here's how a `for` statement is supposed to look: https://docs.python.org/2/tutorial/controlflow.html#for-statements
Comment: What do you want to achieve? I think you're confused between `for` and `if`.
Answer: Looks like you're trying to do a for loop. That's not the correct syntax.
I'd suggest going trough some basic tutorials first...! (Before coming on here and post basic problems with unclear code with an even unclearer thread title)
Here's a correct for loop:
data = [1,2,3,4]

for n in data:
    print n

Comment: I am trying to create a translator that has the option to add, remove and edit words in the program its self just by pressing the button, if you want I will post the code in its entirety so you can have a look
Comment: Like I said, I'd get the basics down first (if, for) before attempting the create an application.


Find infimum and supremum of the function $f$ defined by the formula $f(x, y, z) = 2x+ 2y-3z$ on the set $A$

Question:
Let $A = \{(x, y, z) \in \mathbb R^3 : x^2 + y^2 + z^2 = 2, xy + yz +zx +1 = 0\}$. Find infimum and supremum of the function $f$defined by the formula $f(x, y, z) = 2x+ 2y-3z$ on the set $A$.

I want to use Lagrange multipliers so I got the following system of equations:
$$
\begin{cases}
2= \alpha x + \beta y + \beta z \\
2= \alpha y + \beta x + \beta z \\
-3 = \alpha z+ \beta x + \beta y \\
x^2 + y^2 + z^2 =2 \\
xy + yz + zx +1 = 0
\end{cases}
$$
Then: $$
\begin{cases}
2= \alpha x + \beta y + \beta z \\
2= \alpha y + \beta x + \beta z
\end{cases} \Rightarrow \alpha (x - y)+\beta(y-x)=0 \Rightarrow  (x-y)(\alpha - \beta) =0 \Rightarrow y=x \text{ or } \alpha = \beta
$$
First case:

equation: $$x^2+2xz+1=0 \Rightarrow 2xz=-1-x^2 \Rightarrow z = \frac{-1-x^2}{2x}$$

equation:
$$2x^2+\frac{1+2x^2+x^4}{4x^2}=2 \Rightarrow 9x^4+2x^2+1-8x^2=0 \Rightarrow 9x^4-6x^2+1=0 \Rightarrow x = \pm \frac{1}{\sqrt 3}$$

Coordinates found: $(\frac{1}{\sqrt 3},\frac{1}{\sqrt 3},-\frac{2\sqrt 3}{3})$, $(-\frac{1}{\sqrt 3}, -\frac{1}{\sqrt 3},\frac{2\sqrt 3}{3})$.
But then I get contradiction. For example for $(\frac{1}{\sqrt 3},\frac{1}{\sqrt 3},-\frac{2\sqrt 3}{3})$: $\frac 92 = \sqrt{3} (\alpha - \beta)$ and $6=\sqrt 3 (\alpha - \beta)$
Second case:
$ 2 = \alpha (x+y+z)$ and $-3=\alpha (x+y+z)$ contradiction
Could someone check where I made a mistake? I don't think this problem has no solution...
Comment: The first equation should be $2=\mathbf{2}\alpha x+\beta y+\beta z$ and there are similar corrections to be made on the second and on the third equations.
Comment: @AnotherUser It isn't a mistake. If in each equation, there is the same multiple next to the parameter,, then it is worth "pulling it into the parameter". So for $2\alpha_1=\alpha$ I got my equations.
Comment: I see. What is your question? Is it how to solve the given problem? Or is it about why you get no solutions when you apply the method of Lagrange multipliers?
Comment: @AnotherUser I have already received a satisfactory answer from ghasheem but I still wonder why the determined points give me a contradictory system of equations, even though, according to ghasheem's answer, I determined the correct critical points.
Answer: Consider
$ (x + y + z)^2 = x^2 + y^2 + z^2 + 2 (x y + x z + y z ) = 2 + 2(-1) = 0 $
Therefore, the intersection of the two constraints is the same as the intersection of $x^2 + y^2 + z^2 = 2 $ and $x + y + z = 0 $.
The intersection of the sphere and the plane is a circle of radius $\sqrt{2}$ and is spanned by two vectors that are orthogonal to the normal vector of the plane.
We can find two orthogonal unit vectors $u_1, u_2$ that are orthogonal to the normal of $x+y+z=0$ which is $[1, 1, 1]$, and these unit vectors are, for example,
$ u_1 = [1, -1, 0] /\sqrt{2} $
$ u_2 = [1, 1, -2] / \sqrt{6} $
Hence,
$(x, y, z) = \sqrt{2} \left( \cos t \ u_1 + \sin t \ u_2 \right) $
$ f = 2 x + 2 y - 3 z = [2, 2, -3] \cdot \sqrt{2} \left(\cos t \ u_1 + \sin t \ u_2 \right) \\ = \sqrt{2} ( [2, 2, -3] \cdot u_1 \ \cos t + [2,2,-3] \cdot u_2 \ \sin t ) $
$ f = \sqrt{2} ( \dfrac{10}{ \sqrt{6} } \sin t ) $
Therefore, the maximum of $f$ is $\dfrac{10}{\sqrt{3} } $ and it occurs at $t = \dfrac{\pi}{2} $ at which, we have
$ (x, y, z) = \dfrac{1}{\sqrt{3}} [ 1, 1, -2 ] $
and the minimum is $-\dfrac{10}{ \sqrt{3}}$ and occurs at $ t = \dfrac{3\pi}{2} $, at which, we have
$(x, y, z) = - \dfrac{1}{\sqrt{3}} [1, 1, -2] $
Answer: The problem cannot be solved directly using the method of Lagrange multipliers. In fact, consider the map
$$
\begin{array}{rccc}
g:&\mathbb{R}^3&\longrightarrow&\mathbb{R}^2\\
&(x,y,z)&\mapsto&\left(x^2+y^2+z^2,xy+yz+zx\right).
\end{array}
$$
Let $g_1$ and $g_2$ be the first and the second component of $g$ respectively. Your problem is to find the maximum and the minimum of the restriction of $f$ to $g^{-1}\{(2,-1)\}$. You tried to solve the system
$$
\left\{\begin{array}{l}
         \nabla f(x,y,z)=\alpha\nabla g_1(x,y,z)+\beta\nabla g_2(x,y,z)\\
         g(x,y,z)=(2,-1)
       \end{array}\right.
$$
and you got no solutions. That's natural, because there is an assumption missing: the method works as long as $g'$ is a surjective map. And, when $(a,b,c)\in g^{-1}(\{(2,-1)\})$, $g'(a,b,c)$ is not surjective. In order to see why, note that $g'(a,b,c)$ is the map from $\mathbb{R}^3$ into $\mathbb{R}^2$ defined by
$$
(x,y,z)\mapsto(2ax+2by+2cz,(b+c)x+(a+c)y+(a+b)z).\label{sys}\tag1
$$
On the other hand
\begin{align}
(a+b+c)^2&=a^2+b^2+c^2+2(ab+bc+ca)\\
         &=2-2\\
         &=0,
\end{align}
and therefore $a+b+c=0$. So, $c=-a-b$ and then the map \eqref{sys} becomes
$$
(x,y,z)\mapsto(2ax+2by-2(a+b)z,-ax-by+(a+b)z),
$$
which is not surjective since for each point $(\alpha,\beta)$ in its range you have $\alpha=-2\beta$.
In order to use the method of Lagrange multipliers, you can change the problem a little. It follows from the computations made above that, if $(a,b,c)\in\mathbb{R}^3$ is such that $a^2+b^2+c^2=2$, then $ab+bc+ca=-1\iff a+b+c=0$. So, apply the method of Lagrange multipliers, but this time using the function
$$
\begin{array}{rccc}
h:&\mathbb{R}^3&\longrightarrow&\mathbb{R}^2\\
&(x,y,z)&\mapsto&\left(x^2+y^2+z^2,x+y+z\right)
\end{array}
$$
and the point $(2,0)$. The map $h'$ is surjective at every point $(a,b,c)\ne(0,0,0)$ and the method will then give you the correct answer.


transferir espaços vazios da base de dados para a última coluna no R

Question: Boa tarde
Para me ajudar no problema estruturei uma base de dados fictícia
dados1<-c(15,15,16,17,18,52,48,47,65,32,'',15,14)
dados2<-c(15,15,16,17,18,52,'',47,65,32,15,15,14)
dados3<-rbind(dados1,dados2)
dados3<-data.frame(dados3)

onde o resultado de dados3 é o seguinte
         X1 X2 X3 X4 X5 X6 X7 X8 X9 X10 X11 X12 X13
  dados1 15 15 16 17 18 52 48 47 65  32      15  14
  dados2 15 15 16 17 18 52    47 65  32  15  15  14

preciso transferir os espaços vazios para a última coluna, ou seja unir a base, deixando espaços vazios na última coluna
Comment: eu passaria cada linha para um vetor, excluiria o vetor vazio, e empilharia novamente. Mas é uma solução bem ingênua. Se ninguém responder em 1 semana, me mande um aviso aqui, que eu tento
Comment: Os espaços vazios podem ser interpretados como `NA`? Se primeiro espaço vazio (X7, dados2) for para a última coluna, quem deverá ocupar aquele *slot*? Descreva um pouco mais sobre as restrições do problema.
Answer: Esta solução parte do princípio que os dados deveriam ser numéricos mas que com o valor '' passaram a ser carateres ou fatores.
Então, primeiro transformam-se em numéricos, o que faz os '' ficarem NA.
dados3[] <- lapply(dados3, function(x) as.numeric(as.character(x)))

Agora, vou trabalhar com uma cópia. No seu caso pode mudar isto e a instrução apply.
dados3b <- dados3
dados3b <- t(apply(dados3b, 1, function(x){
  if(anyNA(x)){
    n <- length(x)
    na <- which(is.na(x[-n]))
    for(i in na){
      x[i:(n - 1)] <- x[(i + 1):n]
      is.na(x) <- n
    }
  }
  x
}))

dados3b <- as.data.frame(dados3b)
dados3b
#        X1 X2 X3 X4 X5 X6 X7 X8 X9 X10 X11 X12 X13
#dados1  15 15 16 17 18 52 48 47 65  32  15  14  NA
#dados2  15 15 16 17 18 52 47 65 32  15  15  14  NA
#dados2a 15 15 16 17 18 52 47 65 32  15  15  14  NA

Dados.
Para testar o código acima criei mais um vetor, com '' na última posição.
dados1 <- c(15,15,16,17,18,52,48,47,65,32,'',15,14)
dados2 <- c(15,15,16,17,18,52,'',47,65,32,15,15,14)
dados2a <- c(15,15,16,17,18,52,47,65,32,15,15,14,'')
dados3 <- rbind(dados1, dados2, dados2a)
dados3 <- data.frame(dados3)


Updated static files do not get served with CDN after deployment because of cache

Question: I recently started using AWS CloudFront to serve my static files with CDN. Since then, when I deploy updated static files such as js or css, CDN doesn't serve updated static files right away. Because of this, Python files (I'm using Django) or HTML files are shown wrong as they were supposed to be working correctly with updated static files.
I found this documentation. It says that I need to add identifier to the static files. For example, I have to change functions.js to functions_v1.js every time I deploy, so that CloudFront doesn't serve cached static files, but serve updated static files. I manually changed the updated static files, and it worked well. However, I felt like that's a hassle and there must be a better way so that I don't need to change all the updated file names one by one manually.
Can anyone give me a direction about this? I'm really confused about that.
Comment: Everybody does this.
Comment: omg.. even when they have to change a lot of static files? do they just edit versions manually one by one? I thought there must've been an automated way :(
Comment: There are automated ways - your build tool or development framework can handle it. Django has a number of solutions. https://stackoverflow.com/questions/9130555/django-static-files-versioning
Answer: Everybody does "cache busting", this very page has at least 5 versioned URIs. If you send a header to cache for a year, the browser isn't going to request it again for that long.
With tooling it does not have to be manual. Specifics about implementing this in your favorite content management system or web site generator are more of a topic for a web developer forums.


Deserializar Array JSON em um Array de Objetos

Question: Boa tarde, resolvi perguntar pois já estou há 3 dias agarrado nisso e por mais que eu tenha procurado, não encontrei uma solução para meu problema. Acesso um Web Service via C#, HttpClient, e obtenho um Json no seguinte formato:
{
    "games": [
        {
            "IdJogo": "1",
            "Titulo": "No Man's Sky",
            "DtaLancamento": "Junho 2016",
            "ResumoBR": "Em No Man's Sky  você assume o papel de um     explorador planetário com uma nave espacial, permitindo-lhes explorar a     superfície de vários planetas e interagir com a flora e fauna, e viajar pelo espaço, entrar em combate com forças inimigas e viajar a outros planetas.",
            "NomeImg": "NoManSky.jpg"
        },
        {
            "IdJogo": "2",
            "Titulo": "Starbound",
            "DtaLancamento": "Dezembro 2013",
            "ResumoBR": "Starbound é um sandbox/open world, nele você vive     em uma espaçonave e pode explorar diferentes mundos, sistemas solares, galáxias, etc. As possibilidades são praticamente infinitas!",
            "NomeImg": "Starbound.jpg"
        }

Estou utilizando o Json.net (newtonsoftjson) para converter cada "Jogo" contido no Json para um objeto com os mesmos atributos existentes no Json, mas obtenho os mais diversos erros. Atualmente, faço a conversão dessa maneira:
string jsonR = resposta.Content.ReadAsStringAsync().Result;

foreach (JObject elemento in jsonR)
{
    Game game = JsonConvert.DeserializeObject<Game>(elemento.ToString());
}

Porem, me retorna o seguinte erro:

Não é possivel converter um objeto do tipo Newtonsoft.Json.Linq.JValue no tipo Newtonsoft.Json.Linq.JObject

e quando tento colocar como tipo JValue dentro do foreach, obetnho o erro:

Error converting value 123 to type 'WpfApplication1.Game'.Path ",line1 position 3.

Desculpe qualquer erro ao postar dessa forma, mas já revirei a documentação do Newtonsoft, já revirei o google e nada conseguiu me ajudar.
Comment: `...(elemento.ToString());`? Isso deveria mesmo ser assim?
Comment: Quando eu tiro o ToString já obtenho um erro nessa linha dizendo que não da para converter de Newtonsoft.Json.Linq.JObject para string.
Comment: O metodo DeserializeObject aceita como parâmetro uma string Json.
Comment: Se você já tem um `JObject`, você pode chamar o método `ToObject` em vez de convertê-lo pra string e depois converter aquela string para o seu objeto.
Answer: Primeiro alguns pontos, e ao final uma solução.

Seu JSON é a representação de um objeto que possui uma propriedade, games, que por sua vez é uma coleção. Simplificado, ele pode ser expresso dessa maneira:
{ "games": []}
Essa coleção é formada por objetos simples (uma relação de propriedades com valores primitivos):
{"IdJogo": "","Titulo": "","DtaLancamento": "","ResumoBR": "","NomeImg": ""}

Para que sua desserialização ocorra com sucesso, você precisa criar classes que representem estas entidades:
public class listaGames () {
    public List<itemGame> games {get; set;}
}

public class itemGame () {
    public string IdJogo {get;set;}
    public string Titulo {get; set;}
    public string DtaLancamento {get; set;}
    public string ResumoBR {get; set;}
    public string NomeImg {get; set;}
}

Com essas estruturas presentes, você pode agora desserializar o JSON:
string jsonR = resposta.Content.ReadAsStringAsync().Result;

listaGames listagames = JsonConvert.DeserializeObject<listaGames>(jsonR);

Como resultado, o objeto listagames terá sua propriedade games populada com instâncias da classe itemGame.
Comment: Putz, muito obrigado, cara. Se eu pudesse eu te daria um abraço.
Comment: @Fumegz Sempre um prazer ajudar, fico feliz que tenha funcionado. =)
Answer: Crie o objeto com os campos desejados tipo:
struct ObjJogo
{
   public string IdJogo        { get; set; }
   public string Titulo        { get; set; }
   public string DtaLancamento { get; set; }
//-- e outros...
}

Depois pege a resposta em json e passe ela pelo código:
JavaScriptSerializer js = new JavaScriptSerializer();
ObjJogo jsonData = js.Deserialize<ObjJogo>(RespostaWS);

Se vier um lista utilize o List<ObjJogo>
esta na using System.Web.Script.Serialization;
Espero que ajude, tive um problema parecido com esse e assim o resolvi.
Comment: Ajudou e muito, vi o problema de um outro angulo. Vlw mesmo!
Comment: Não por isso, é sempre um prazer poder ajudar
Answer: O primeiro foreach está tentando converter o string jsonR em um JValue usando o conversor implícito. Você termina com uma string JSON, e não com um objeto, o que é o que você precisa.
Para ler usando o JSON.NET, você precisa primeiro fazer o parsing apropriado (i.e., de jsonR para um JObject). Depois você pode usar o método ToObject<T> para converter o objeto JSON para o seu tipo, como no exemplo abaixo.
class Program
{
    static void Main()
    {
        var jo = JObject.Parse(jsonR);
        var games = jo["games"].ToObject<Game[]>();
        foreach (var game in games)
        {
            Console.WriteLine(game);
        }
    }

    const string jsonR = @"{
        ""games"": [
            {
                ""IdJogo"": ""1"",
                ""Titulo"": ""No Man's Sky"",
                ""DtaLancamento"": ""Junho 2016"",
                ""ResumoBR"": ""Em No Man's Sky  você assume o papel de um explorador planetário com uma nave espacial, permitindo-lhes explorar a superfície de vários planetas e interagir com a flora e fauna, e viajar pelo espaço, entrar em combate com forças inimigas e viajar a outros planetas."",
                ""NomeImg"": ""NoManSky.jpg""
            },
            {
                ""IdJogo"": ""2"",
                ""Titulo"": ""Starbound"",
                ""DtaLancamento"": ""Dezembro 2013"",
                ""ResumoBR"": ""Starbound é um sandbox/open world, nele você vive em uma espaçonave e pode explorar diferentes mundos, sistemas solares, galáxias, etc. As possibilidades são praticamente infinitas!"",
                ""NomeImg"": ""Starbound.jpg""
            }
        ]
    }";
}

public class Game
{
    public string IdJogo { get; set; }
    public string Titulo { get; set; }
    public string DtaLancamento { get; set; }
    public string ResumoBR { get; set; }
    public string NomeImg { get; set; }
}

Comment: Muito obrigado! Agora vou tenho duas soluções! Ambas testadas e aprovadas!


Deploying Database Project

Question: lots of confusion for me while handling the VS Database Project. Okay, while trying to deploy the DB Project to a target database, the objects (SPs, Triggers) still refer to the previous database if included the reference of the same database in the objects. For example:
I have an SP which contains one of its table reference as DBName..TableName. After I deploy my project to a target database with a new name, the object still refers to the same DB which is DBName. Now to make my deployment work I change this hardcoded name to $(DBName) variable and this is passed along as the variable while deploying the Databases to the target DB. This gives an error while deployment. So can we deploy the database project containing cross references or references to the same DB to the new database target and get these names changed altogether.
Answer: Just try the "Publish..." Command from the Database Project Property Menu (right click on the project in solution explorer). Once the dialog is open you can set the values for your variables (e.g. [$(MyDatabase)]. If you choose the "Create publish script"-Option, a script will be generated containing SQLCMD-Variables which can be set to your target database.

Deploying Database Project


Magento URL indexer in progress joinLeft slow query in Category/Flat.php causes site outage

Question: Software: Magento Community
Flat Category Index enabled
Description of problem:
When I run a full URL index, it takes a very long time to complete, which I understand can be normal in some circumstances. This is not the issue im asking about. While the indexer is running the block cache continuously gets invalidated. When this happens, Magento tries to rebuild the menu from the flat category table while joining the url rewrite table. This is a part of the core in file
Mage/Catalog/Model/Resource/Category/Flat.php
While the indexer runs, this query repeatedly shows up in mysql client connections.
<code>SELECT `main_table`.`entity_id`, main_table.`name`, main_table.`path`, `main_table`.`is_active`, `main_table`.`is_anchor`, `url_rewrite`.`request_path`, `main_table`.`url_override`, `main_table`.`display_subcategories`
 FROM `catalog_category_flat_store_19` AS `main_table`
 LEFT JOIN `core_url_rewrite` AS `url_rewrite` ON url_rewrite.category_id=main_table.entity_id AND url_rewrite.is_system=1 AND url_rewrite.product_id IS NULL AND url_rewrite.store_id='19' AND url_rewrite.id_path LIKE 'category/%'
 WHERE (main_table.is_active = '1') AND (main_table.include_in_menu = '1') AND (main_table.path like '1/1877/%') AND (`level` <= 3)
 ORDER BY `main_table`.`position` ASC
</code>
This query is extremely slow due to the joinLeft. This Join is defined in the file mentioned above. When the indexer is running, this query times out. Connections build up on the server all trying to run the same query to rebuild the navigation menu.
if I change the query to a joinInner instead of a joinLeft, the problem immediately goes away. I do not understand the purpose of a left join, because I think its highly unlikely there wouldn't be a value in this table, and if there wasn't we might not want to show this category.
I have seen a least a few other reports of this problem, but they are quickly brushed off with a generic performance issue while running index or cache.
I dont understand why this query acts very differently when the indexer runs because I can do a full select on each table individually in a normal amount of time. Only with the left join combined with the indexer does this problem happen. Understand that in general this is a slow query.
Question: Can you please provide information on the left join, why it is needed because its very slow. Can you also recommend a solution to solve my problem.
Comment: There are many things going on here. The indexer will invalidate the cache right away, so all the front-end requests that come in while the nav block is not in the cache will each try to rebuild it (queries ran by the default navigation block in Magento 1.X are expensive). The issue is avoided in Magento 2 and 3rd party extensions by making the navigation HTML generated and cached/stored elsewhere, only being updated when it is regenerated. And in the case of the indexer, invalidated only after the data is updated, not before it runs.
Answer: This issue happens because it is just a problem query in this version of Magento. Later versions of Community have rewritten this method/query to not have any left join.
There is still an issue where the block cache is invalidated and the menu is getting regenerated, but the main issue reported is solved.
The function in reference is getParentCategories of file Mage/Catalog/Model/Resource/Category/Flat.php


Undefined offset: 0. Doctrine and native sql

Question: I have little problem, I want to print id of user, but I have an error: "Undefined offest: 0". Here is my code:
$rsm = new ResultSetMapping();
$em = $this->getDoctrine()->getManager();
$user= $this->get('security.context')->getToken()->getUser();
$query = $em->createNativeQuery('SELECT id FROM fos_user WHERE username_canonical = ?', $rsm);
$query->setParameter(1, $user);
$users = $query->getResult();
echo $users[0]['id'];

Somebody have idea what is wrong?
Comment: Error is becouse you are using user object ($user) as query parameter. Query doesn't return any user and you try to get undefinde offset.
Comment: If you already have the user object from the security context then you don't need to then find it on the database to get the id. A simple `echo $user->getId()` should give you what you are after.
Answer:
Add EntityResult and FieldResult to $rsm
$rsm = new ResultSetMapping();
$rsm->addEntityResult('App\UserBundle\Entity\User', 'u');
$rsm->addFieldResult('u', 'id', 'id');

Change setParameter
$user to  $user->getUsernameCanonical();
getResult
foreach($users as $user)
{
    echo $user->getId();
}

Answer: Change string:
$query->setParameter(1, $user);

to
$query->setParameter(1, $user->getUsernameCanonical());


Ridge Trace Plot - Interpretation

Question: In my research, I aimed to perform a regression model with four predictors and one response variable. When I verified a high collinearity among the predictors, I was instructed to handle this problem using a ridge regression. So, I developed this analysis using R's glmnet package, and I generated the ridge trace plot below.

I understand that the most important predictor is the one whose coefficients converge more slowly to 0 as the shrinkage penalty increases. Considering this, could I say that the variable corresponding to the green line on my plot would be the most important? I concluded this because it took longer to shrink regarding to the red and blue lines, which decreased remarkably as λ increased. And with respect the purple line, would it be correct to say that it was the second most important variable?
Answer: To me it seems that the most important variable is represented by the red line, and second most important by the blue line. That's because initially, when the penalty for having high coefficient values is low, they are both quite high.
After the penalty increases the model is forced to shrink the coefficients and the third variable - represented by the green line - takes their place to compensate.
In contrast the purple line is least important because its influence (coefficient) remains close to zero regardless of the penalty.
Note: I have never interpreted such a plot before, so don't take this as being authoritative. Also this answer assumes that all the variables are standardised for this kind of plot and are represented by comparable units.
Comment: Thank you very much for the reply! Yes, all variables were standardized before analysis and are represented by comparable units. Your interpretation is quite different from mine, but I am inclined to agree with you. Could you explain to me: "[...] the third variable - represented by the green line - takes their place to compensate"?
Comment: Sure, however keep in mind that this is only an interpretation. You said that your variables are collinear. According to the plot it seems like the model prefers using the "red" covariate. However when we forbid it from placing large coefficients on one variable via ridge penalty it then tries to instead combine multiple correlated covariates. This is what I meant by "green line takes their place to compensate".
Comment: But it all depends on what you are trying to achieve. If your goal is to get accuracy, then the model with lambda penalty = 1 might be more robust and hence more accurate on some testing set, since it incorporates 3 correlated variables instead of relying on one, which might be noisy and increase variance of the predictions.

Ridge Trace Plot - Interpretation


Javascript content rotation based on percentage

Question: I need to be able to rotate content inside a placeholder div based on percentage like this. The rotation will occur on page load. So each time a user reloads a page he has these chances of seeing content 1, 2 or 3 in the content placeholder:
Content 1 = show 50% of the time
Content 2 = show 25% of the time
Content 3 = show 25% of the time
I prefer Javascript but if there is a easier way to do it in ASP.NET on the front end template not the codebehind, that is also acceptable. If you have a solution or can point me to an existing script I would appreciate it. Thanks!
Comment: I was about to say you can't rotate things in HTML until I realised you meant it in a different context.
Answer: There's really no need to multiply/floor/ceil anything: the Math.random() function gives value which is larger than or equal to 0 and less than 1.
The following code would be a bit easier to maintain if you change the number of options or the chance percentage.
var contentId, random = Math.random();

if (random < 0.5) {
  // option 1: chance 0.0–0.499...
  contentId = 0;
} else (random < 0.75) {
  // option 2: chance 0.50—0.7499...
  contentId = 1;
} else {
  // option 3: chance 0.75–0.99...
  contentId = 2;
}

loadContent(contentId);

Comment: Thanks Damir, I ended up using this one and it works exactly how I wanted it to work. Plus it saves a few lines of code.
Answer: Here is a quick hack, there is probably a better way.
var randomnumber=Math.floor(Math.random()*4)
if((num==0) || (num==1)) {
//show hidden div or document.write (50% probability)
} else if (num==2) {
//show hidden div or document.write (25% probability)
} else {
//show hidden div or document.write (25% probability)
}

Comment: If you use floor, values will be in range from 0 to 3, not 1 to 4
Answer: For the random part of the script, you just have to play with Math.random
Something ugly and hardcoded would look like this :
var contentToShow = -1;
var NB_MAX = 4;
var myRand = Math.floor(Math.random()*NB_MAX);
if(myRand<1) contentToShow = 1;
else if (myRand<2) contentToShow = 2;
else contentToShow = 3;

Then you just have to load the content with ajax.
An exemple in jQuery could look like :
var myPlaceHolder = $("#myPlaceHolder")
$.myPlaceHolder.load("/mycontents/mycontent_" + contentToShow + ".asp");

But using ajax request on a page load is not the way to go imo. ( 2 server request instead of 1 if the random content is handled by the server )
Comment: This is the correct implementation, but I would agree that it needs to be handled server side to get better results. (Bringing in Ajax content on load will probably look awkward)


The relationship between code behind class and aspx generated class

Question: I was reading a book says that "a Web Form's code-behind class was the base class for the class generated by the runtime from the .aspx file itself, as the picture below shows:

I don't know how the generated class looks like, as I only deal with aspx.cs which is the code-behind class.
So let say I have a .aspx file that have some controls like textboxes, do the generated class generated by .aspx file contains Textbox class?  and how this generated class inherit the code-behind class, I'm really confused, can anybody post an example code of generated class generated by .aspx file?
Answer: The generated classes are stored here:
%windir%\Microsoft.NET\Framework\version\Temporary ASP.NET Files\root

Replace the version in the above path with the version of your framework. There will be many files in there but you can delete them all to start afresh. Then restart the web application in question and you will see a brand new folder (with a numeric name) will be created in the root folder. Inside the folder you will see many files but if you sort them by type, one of the CS Files will be the one generated for the .aspx page. The name will not be a friendly name so you will have to keep opening them and search for nameofpage_aspx. For example, if the aspx page is named About, search for about_aspx. If you do not find it, search for it in another file and one of them will be for about_aspx.
You may also look for the first line in the file which starts with #pragma checksum and it will have the name of the .aspx page. Not all files will have this line.
In those CS File types are the generated code which will be used by asp.net and you can examine its contents in more details if you want. Please do not ask me to explain the details of what is in those files but I am sure if you search online, you will find info on that.


Adding a Namespace to a MessageContract (WCF)

Question: I am trying to create a SOAP message to send to an SAP endpoint, however, I am having trouble setting the namespace correctly. I have been trying for days and tried many suggestions I found online, but none seem to work. I am hoping some of you can help me.
This is an example of the C# code that I have:
[ServiceContract]
[XmlSerializerFormat]
public interface IWcfClient
{
    [OperationContract(IsOneWay = true)]
    void SendUpdates(UpdateRequest request);
}

[MessageContract(IsWrapped = true, WrapperName = "MyRoot", WrapperNamespace = "myNamespace")]
public class UpdateRequest
{
    [MessageBodyMember]
    [XmlElement(ElementName = "updateType")]
    public byte UpdateType { get; internal set; }

    [MessageBodyMember]
    [XmlElement(ElementName = "updateEntry")]
    public UpdateEntry[] UpdateEntries { get; set; }
}

public class UpdateEntry
{
    [XmlElement]
    public string DeviceId { get; set; }

    [XmlElement]
    public DateTime LastSeen { get; set; }
}

This results in the SOAP body looking something like this:
<s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <MyRoot xmlns="myNamespace">
        <updateEntry>
            <DeviceId>12345</DeviceId>
            <LastSeen>2017-04-24T14:44:30.8030649Z</LastSeen>
        </updateEntry>
        <updateEntry>
            <DeviceId>56789</DeviceId>
            <LastSeen>2017-05-03T01:33:02.084Z</LastSeen>
        </updateEntry>
        <updateType>2</updateType>
    </MyRoot>
</s:Body>

What I am trying to achieve, is to add another namespace to the root and have the sub-elements use that namespace. In end effect I am looking for a result similar to this (mySecondNamespace):
<s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <MyRoot xmlns="myNamespace" xmlns:a="mySecondNamespace">

            12345
            2017-04-24T14:44:30.8030649Z

            56789
            2017-05-03T01:33:02.084Z

        2
    </MyRoot>
</s:Body>

I have tried:

Adding XmlRoot to the MessageContract
Adding XmlType to the MessageContract
Using "XmlNamespaceDeclarations" attribute on a getter/setter in which the new namespace is added to the namespace collection
Setting the namespace on the OperationContract

But nothing seems to work. Adding the namespace to the XmlElement seems to have effect, but in that case the namespace is not on the root element and is not propagated to the underlying elements. Any ideas?
Answer: After a long search I finally found the solution to my problem. What I had to do was to switch to the XmlSerializerFormat on the OperationContract instead of on the Interface itself and update the contracts accordingly:
[ServiceContract]
public interface IWcfClient
{
    [XmlSerializerFormat]
    [OperationContract(IsOneWay = true)]
    void SendUpdates(UpdateRequest request);
}

[MessageContract(IsWrapped = false)]
public class UpdateRequest
{
    [MessageBodyMember(Name="UpdateEntry")]
    public UpdateEntry[] UpdateEntries { get; set; }
}

[Serializable]
[XmlType(Namespace = "myNamespace")]
public class UpdateEntry
{
    [XmlElement(ElementName = "UpdateEntry", Order = 0)]
    public Device[] DeviceInfo { get; set; }

    [XmlElement(ElementName = "UpdateType", Order = 1)]
    public byte UpdateType { get; set; }
}

[Serializable]
[XmlType(Namespace = "myNamespace")]
public class Device
{
    [XmlElement(ElementName = "DeviceId", Order = 0)]
    public string DeviceId { get; set; }

    [XmlElement(ElementName = "LastSeen", Order = 1)]
    public DateTime LastSeen { get; set; }
}


Differentiability and continuity of $f(x)=x^2+\frac{x^2}{1+x^2}+\frac{x^2}{(1+x^2)^2}+\ldots \to \infty$

Question: If $$f(x)=x^2+\frac{x^2}{1+x^2}+\frac{x^2}{(1+x^2)^2}+\ldots \to  \infty \,,$$ then
choose the correct option:
$(A)$ lim($x \to 0$) $f(x)$ does not exist.
$(B)$ lim($x \to 0$) $f(x)$ exist but $f(x)$ is discontinuous at $x=0$
$(C)$ At $x=0$, $f(x)$ is continuous but not differentiable
$(D)$ $f(x)$ is differentiable everywhere.
Now what I see here is that $f(0)=0$ and when $x \to 0$, then we can apply sum of infinite terms of G.P. as common ratio will be less than $1$ in that case and I got $\lim_{x \to 0} f(x)$ as $1$ which makes the function discontinuous.
Am I correct?
Comment: On essentials, yes. But it looks to me as though $\lim_{x\to0}f(x)=1$ not 2. The series seems to sum to $1+x^2$ except at $x=0$ when it sums to 0.
Answer: Hint. From the standard geometric series evaluation, one has
$$
 f(x) =
    \begin{cases}
0,  & \text{if $x=0$} \\[2ex]
x^2 \cdot \frac1{1-\frac1{1+x^2}}=\color{red}{1+x^2}, & \text{if $x\neq 0$.}
\end{cases}
$$
Answer: $$ f(x) = x^2\sum_{n\geq 0}\frac{1}{(1+x^2)^k}=\frac{x^2}{1-\frac{1}{1+x^2}}=1+x^2 $$
holds for any $x\neq 0$, since the involved geometric series is convergent ($1+x^2>1$).
However, at $x=0$ we clearly have $f(x)=0$, hence $f$ is a discontinuous function and $\color{red}{(B)}$ is the correct option.


Lista de compras dentro de função

Question: Estou a tentar resolver um exercício que estou a fazer de PHP (sou iniciante) mas não estou a conseguir fazer com que o código funcione, a seguinte mensagem é exibida:

"Notice: Undefined variable: produtos in C:\xampp\htdocs\teste3.php on
  line 39"

Código:
$br = "
";

function lista($artigos) {

    $produtos = array(
        'Leite' => array('preco' => 0.8, ),
        'Iogurte' => array(
            'preco' => 0.25,
        ),
        'Queijo' => array(
            'preco' => 2.2,
        ),
        'Peixe' => array(
            'preco' => 3.1,
        ),
        'Carne' => array(
            'preco' => 3.5,
        ),
        'Bolachas' => array(
            'preco' => 0.6,
        ),
    );

}
if (isset($_GET['produto'])) {
    if (isset($_GET['quantidade'])) {
        echo 'Preço por unidade: '.$produtos[$_GET['produto']]['preco'].
        '
';
        echo 'Preço total: '.$produtos[$_GET['produto']]['preco'] * $_GET['quantidade'];
    } else {
        echo 'nao existe essa quantidade';
    }
} else {
    echo ' nao existe esse produto!';
}

Exercício :
Comment: Qual é o problema?
Comment: Ola @stderr, eu quero que quando faça directamente no browser por exemplo: http://localhost/teste3.php?produto=Queijo&quantidade=30 apareça o preço do produto e neste caso a soma do mesmo (x30) mas quando corro dá erro "Notice: Undefined variable: produtos in C:\xampp\htdocs\teste3.php on line 39"
Comment: Comece por aqui: http://pt.stackoverflow.com/tour
Comment: Já fiz o tour..
Answer: Para a proxima é melhor colocar a parte relevante codigo aqui, para ajudar a quem o quer ajudar, nem toda a gente tem tempo/quer ir a links externos para ver código.
Pode fazer assim, sugiro estas melhorias:
<?php
function procurar($produto) {
    $produtos = array(
        'Leite' => array('preco' => 0.8,
        ),
        'Iogurte' => array(
            'preco' => 0.25,
        ),
        'Queijo' => array(
            'preco' => 2.2,
        ),
        'Peixe' => array(
            'preco' => 3.1,
        ),
        'Carne' => array(
            'preco' => 3.5,
        ),
        'Bolachas' => array(
            'preco' => 0.6,
        ),
    );
    $produto = ucwords(strtolower($produto));
    if(array_key_exists($produto, $produtos)) {
        return $produtos[$produto];
    }
    return false;
}
if(isset($_GET['produto'])) {
    $prod = procurar($_GET['produto']);
    if($prod) {
        if(isset($_GET['quantidade'])) {
            echo 'Preço por unidade: ' .$prod['preco']. '
';
            echo 'Preço total: ' .$prod['preco']*$_GET['quantidade'];
        }
        else {
            echo 'nao existe essa quantidade';
        }
    }
    else {
        echo ' nao existe esse produto!';
    }
}
else {
   echo 'Produto invalido';
}

A função deve retornar algo, neste caso retorna os dados do produto que quer, fiz também de maneira a que a busca por chave no array seja case insencitive
Comment: De nada @MarioCaeiro. Editei, pois os echos de baixo estavam trocados
Comment: Ainda estou muito verdinho, não tinha reparado! Obrigado
Comment: @Miguel Já que as chaves do *array* começam com letra maiúscula, o [`ucwords`](http://php.net/manual/pt_BR/function.ucwords.php) também pode servir, por exemplo: `$produto = ucwords(strtolower($produto))`. :)
Comment: Sim claro, é verdade @stderr , escusava de mudar as chaves do próprio array, tens razão, vou editar
Comment: É isso mesmo Miguel! Penso que seja a melhor maneira e obrigado pela dica do case insenctive ! Muito obrigado!
Answer: Use o isset antes para verificar se a variável foi definida.
function verificarProduto($produto, $quantidade) {
    $produtos = array('Leite' => array('preco' => 0.8, ),
                      'Iogurte' => array('preco' => 0.25, ),
                      'Queijo' => array('preco' => 2.2, ),
                      'Peixe' => array('preco' => 3.1, ),
                      'Carne' => array('preco' => 3.5, ),
                      'Bolachas' => array('preco' => 0.6, ),
                );

     if ($produto) {
         // Verifica se o produto existe na lista de produtos
         if (isset($produtos[$produto])) {
             // Pega o preço do produto
             $preco = $produtos[$produto]['preco'];
             echo "{$produto} existe na lista! Preço por unidade: {$preco}
";

             // Se a quantidade for especificada
             if ($quantidade) {
                 $total = $quantidade * $preco;
                 echo "Total: {$total}
";
             }
         }
         else {
             echo "{$produto} não existe.
";
         }
     }
}

// Verifica se foi atribuído os valores, em caso negativo, atribui-se "false"
$produto = isset($_GET['produto']) ? $_GET['produto']: false;
$quantidade = isset($_GET['quantidade']) ? $_GET['quantidade']: false;

verificarProduto($produto, $quantidade);

Comment: seu código é limpo e explicito, obrigado pela ajuda serve na perfeição também para o que precisava de fazer! Obrigado pelo tempo despendido !

Lista de compras dentro de função


Formalizing using $\sin h \approx h$ to evaluate a limit.

Question: Assume $f \in C^{\infty}(\mathbb{R}^2)$ satisfies $f(\sin 2t, \sin t)=0$ for all $t\in \mathbb{R}$. I want to evaluate the limit
\begin{equation*}
 \lim_{h \to 0}\frac{f(2h,h)}{h}.
\end{equation*}
It seems that (from the context from which this question came up) this limit should be equal to $0$ and an intuitive rationale that supports this is to consider $h\approx \sin h$, so that if we rewrite the limit above as
\begin{equation*}
 \lim_{\theta \to 0}\frac{f(2\sin\theta,\sin \theta)}{\sin\theta} \underset{\text{looks like}}{=}\hspace{0.1cm}  \lim_{\theta \to 0}\frac{f(2\sin\theta\cos \theta,\sin \theta)}{\sin\theta} = 0,
\end{equation*}
where the last equality follows from the fact that $f$ is $0$ in points of the form $(\sin2t, \sin t)$. How to formalize this intuition?
Comment: You need an estimate for $f(2h\sqrt{1-h^2},h)-f(2h,h).$ Seems like a job for mean value theorem on the $x$ variable.
Comment: I think this did it! Thank you so so much!
Answer: $f(u,v)=au+bv+o(\|(u,v)\|)$ gives
$f(\sin(2t),\sin t)=a(2t+o(t))+b(t+o(t))+o(t)=(2a+b)t+o(t)$.
Since $f(\sin(2t),\sin t)=0$, we deduce $2a+b=0$ hence
$f(2h,h)=a(2h)+bh+o(h)=o(h)$.
Answer: We can evaluate
$\frac{d}{dt}f(\sin (2t), \sin(t)) = (\frac{\partial f}{\partial x} 2 \cos(2t) + \frac{\partial f}{\partial y} \cos(t))|_{(x, y) = (2t, t)} = 0$
using the multivariable chain rule. Plugging in $t = 0$ gives us $(2 \frac{\partial f}{\partial x} + \frac{\partial f}{\partial y})_{(x, y) = (0, 0)} = 0$.
Now note that $\lim\limits_{h \to 0} \frac{f(2h, h)}{h} = \frac{d}{dt} f(2t, t)|_{t = (0, 0)}$ by the definition of the derivative. We apply the multivariable chain rule again to get that this derivative is $(2 \frac{\partial f}{\partial x} + \frac{\partial f}{\partial y})_{(x, y) =(0, 0)}$. But we've already demonstrated that this quantity is $0$.
Answer: You would want to be careful with intuition such as this.  For example, suppose you defined a function $f$ by
$$f(x,y) = \frac{x - 2y\sqrt{1-y^2}} {y^3}.$$
Then $f(\sin(2\theta), \sin(\theta)) = 0$ at least for $-\frac{\pi}{2} \le \theta \le \frac{\pi}{2}$.  However, $f(2h, h) = \frac{2h - 2h\sqrt{1-h^2}}{h^3}$, and a Taylor expansion of the square root term will show that $f(2h, h) \to 1$ as $h\to 0$, so $\frac{f(2h, h)}{h}$ would have no limit.
Of course, this has the issue that $f(x,y)$ is not defined on the $x$-axis.  You could try making some adjustments near $y=0$ to get a better defined function.  However, if you do that, you might see that you continue to get functions which are not differentiable at the origin -- as the following argument using the differentiability will show:
Under the given conditions, in particular, $f$ is continuous at $(0, 0)$.  Therefore, $(\sin(2t), \sin(t)) \to (0, 0)$ as $t\to 0$ implies $f(0, 0) = \lim_{t\to 0} f(\sin(2t), \sin(t)) = 0$.  Also, using the multivariate chain rule, we have that
$$\left. \frac{d}{dt} [f(\sin(2t), \sin(t))] \right|_{t=0} = 2 f_x(0, 0) + f_y(0, 0) = 0.$$
Now since $f(0, 0) = 0$, the given limit is equal by definition to
$$\left. \frac{d}{dt} [f(2t, t)] \right|_{t=0} = 2 f_x(0, 0) + f_y(0, 0) = 0.$$
Comment: Your example $f$ is not in $C^{\infty}(\mathbb R^2),$ is it?
Comment: Thanks for the comment on caution! However as I described in the post, there is a greater context that suggested that the limit had to be 0. In any case, By looking at the last part of your post, I have to ask, how can you tell that $2f_x(0,0)+f_y(0,0)=0$? I also thought about it this way but I didnt know how to conclude from there.
Comment: Right, it's not.  My point with that example is: unless you make tighter error estimates, just figuring $(\sin(2t), \sin t)$ is "close enough" to $(2t, t)$ isn't necessarily going to give you a valid conclusion.  But, it does turn out that the differentiability at $(0, 0)$ is sufficient to get such a tighter error estimate (and the answer by Anne Bauval makes it a bit more explicit what the estimate of $f$ is near $(0, 0)$ based on that assumption, and why it's sufficient.
Answer: For $h\in[-1,1]$ you get $f(2h\sqrt{1-h^2},h)=0.$
So $$\frac{f(2h,h)}{h}=\frac{f(2h,h)-f(2h\sqrt{1-h^2},h)}h\tag1$$
Now, by the mean value theorem, there is some $h'$ between $h$ and $h\sqrt{1-h^2}$ so that $$f(2h,h)-f(2h\sqrt{1-h^2},h)=2h\left(1-\sqrt{1-h^2}\right) f_x(2h',h).$$
So, if $f_x$ is bounded by $C$ in some neighborhood of $(0,0),$ then:
$$\left|\frac{f(2h,h)-f(2h\sqrt{1-h^2},h)}h\right|\leq 2C\left(1-\sqrt{1-h^2}\right)$$
So the right hand side of $(1)$ goes to zero as $h\to 0.$
So you only need that $\frac{\partial f}{\partial x}$ exists and is bounded on some neighborhood of $(0,0).$


Compute limit of Cov(X, Y)

Question: Let $X$ ~ $N(0,1)$ and $Y = cX$.
Compute $\lim_{c\to0^+}Cov(X,Y)$.
I've computed:
$\lim_{c\to0^+}Cov(X,Y) = \lim_{c\to0^+} E(XY)-E(X)E(Y)$
$\qquad\qquad\qquad\qquad= \lim_{c\to0^+} cE(X^2)-c(E(X))^2$
$\qquad\qquad\qquad\qquad= \lim_{c\to0^+} cVar(X)$
$\qquad\qquad\qquad\qquad= \lim_{c\to0^+} c$
$\qquad\qquad\qquad\qquad= 0$
Similarly, $\lim_{c\to0^-}Cov(X,Y) = 0$.
Is this right?
Comment: The calculation is fine.
Answer: I think yes, because also the Covariance between a variable and a constant is zero (they react fully independent).
When c is positive or negative, X and cX would be perfectly positively/negatively correlated, but for $0$ it should be independent. I see no discontinuity so the limit should equal $0$.

Compute limit of Cov(X, Y)


$\frac{-1}{2}$ Zero of odd powers sum polynomials?

Question: Consider the polynomial $S_k(x) \in \mathbb{Q}[x]$ such that $S_k(n)=\sum_{i=1}^{n}i^k, \forall n \in \mathbb{N}$. Now if i recall correctly the definition it should be that $S_n(x)=\frac{B_{n+1}(x)-B_{n+1}}{n+1}$ where $B_{n+1}(x)$ is the (n+1)-th Bernoulli polynomial and $B_{n+1}$ is the $(n+1)$-th Bernoulli number.
I saw that a certain question i'm working on, reduces to the following: for wich $n$ odd, $S_n(\frac{-1}{2})=0$?
That is: for wich n even $B_n(\frac{-1}{2})=B_n$?
Of course for n even(resp odd) this is always the case.
Is this something known from the existing literature about Bernoulli polynomials/numbers?
Thanks for any help!
Answer: According to pag 3 of the following article http://ac.els-cdn.com/0021904587900712/1-s2.0-0021904587900712-main.pdf?_tid=aec020e0-7282-11e4-a9ba-00000aab0f6c&acdnat=1416686813_61c8897ff66e12d7ed1920c64b6f87eb
We get, putting $z=\frac{-1}{2}$, $B_{2k}(\frac{-1}{2})\frac{({2\pi})^{2k}}{2(2k)!}(-1)^{k+1} \to -1$.
Putting $z=0$ we get $B_{2k}(0)\frac{({2\pi})^{2k}}{2(2k)!}(-1)^{k+1} \to 1$.
So making the quotient we get that $B_{2k}(0)$ and $B_{2k}(-\frac{1}{2})$ have opposite sign for k large enough(more precisely the quotient converge to -1).
So $S_{2k+1}(\frac{-1}{2}) \neq 0 $ for k large enough.
Since it seems a very delicate argument because it works just because we ahave different signs in the same expression i would be glad if someone confirms me that it's everything correct and this answer my original question.


Multiple (AND) queries for a nested index structure in Elasticsearch

Question: I have an index with the below mapping
{
  "mappings": {
    "xxxxx": {
      "properties": {
        "ID": {
          "type": "text"
        },
        "pairs": {
          "type": "nested"
        },
        "xxxxx": {
          "type": "text"
        }
      }
    }
  }
}

the pairs field is essentially an array of objects - each object has a unique ID associated with it
What i'm trying to do is to get only one object from the pairs field for updates. To that extent , i've tried this
GET /sample/_search/?size=1000
{
    "query": {
      "bool": {
        "must": [
            {
              "match": {
                "ID": "2rXdCf5OM9g1ebPNFdZNqW"
              }
            },
            {
              "match": {
                "pairs.id": "c1vNGnnQLuk"
              }
            }
          ]
      }
  },
  "_source": "pairs"
}

but this just returns an empty object despite them being valid IDs. If i remove the pairs.id rule - i get the entire array of objects .
What do i need to add/edit to ensure that i can query via both IDS (original and nested)
Answer: Since pairs is of nested type, you need to use a nested query. Also you might probably want to leverage nested inner-hits as well:
GET /sample/_search/?size=1000
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "ID": "2rXdCf5OM9g1ebPNFdZNqW"
          }
        },
        {
          "nested": {
            "path": "pairs",
            "query": {
              "match": {
                "pairs.id": "c1vNGnnQLuk"
              }
            },
            "inner_hits": {}
          }
        }
      ]
    }
  },
  "_source": false
}

Comment: What you can also do is to set `_source` to false if you don't need the `_source` section and you'll only get the inner hits.
Comment: Thank you - but for some reason , i'm still getting the entire array of objects with the above query. do i need to refine it a bit more?
Comment: Check the `inner_hits` section in the response, you should only get the element that matches.
Comment: Oh you're right .. the inner_hits is returning the required object alone - thank you


Network Location Awareness Applications for Windows or Mac

Question: I've heard of applications on Mac that can be used to launch certain programs depending on the Network location.  I'm looking for an application that can accomplish this on Windows or Linux.
One use case is I want to launch synergy with the correct configuration automatically depending on where I am.  And possibly launch certain applications when I get to work or something.
Thanks
Comment: It's called Marco Polo
Comment: What is the Mac application called?  This might help track down an alternative.
Answer: The "Network Location Awareness" service (http://msdn.microsoft.com/en-us/library/ms739931(VS.85).aspx) in Windows XP (and 2000? I don't recall...) and up will enable this functionality, but I haven't found where anybody has written an application to take advantage of it. I'd love to code something myself, but I don't have enough spare cycles to even begin to think about it.
This wouldn't be a simple little VBScript thing, but it wouldn't be that much coding either. Maybe somebody could pick up the idea and run with it. There's even sample code at http://www.microsoft.com/downloads/details.aspx?familyid=ef8a6228-f11d-4ba0-b73e-dd8dc7dd11e8&displaylang=en.
There have been numerous times I've wanted this functionality, and I'd think there are more than a few people who would like to see it.


how to find even duplicates character in a string in C# .Net

Question: I have a question of how to remove even duplicates in a string in C#.
example - input string:

acdhqodcqasaf

output:

acdhqosaf

What I really mean is to remove even occurrences of characters.I have written the logic but I have used nested for loops and its efficiency is O(n^2) which is not good efficiency.So I was asked to do in different way searched online still did not get the answer
Comment: What are even duplicates?
Comment: "I have written the logic" Do you mind sharing that with us?
Comment: @Brian I think that's not wrong. If I understand correctly, the OP wants to remove every second occurrence of a char - so if that char appears three times in the input (and `a` does) it should appear two times in the output.
Comment: Do you need to do this in a tight loop, or do you have very large strings? because if not, I wouldn't worry about O(n^2) efficiency too much.
Comment: Sure I will share-@Heretic.
Comment: you have two "a"s in the output
Comment: I'm guessing an "even duplicate" is every other instance..
Comment: @ZoharPeled Whoops. you're right, it does say so in the question.
Comment: I edited my answer. please have a look.
Answer: You could use a dictionary to track the number of occurences and use the % operator:
string input = "acdhqodcqasaf";
var charOccurences = new Dictionary<char, int>();
int removeEvery = 2;
var outputBuilder = new StringBuilder();

foreach (char c in input)
{
    charOccurences.TryGetValue(c, out int charOccurence);
    charOccurence++;
    charOccurences[c] = charOccurence;
    if (charOccurence % removeEvery != 0)
        outputBuilder.Append(c);
}

string output = outputBuilder.ToString();

Answer: I'd use a HashSet to keep track of which characters you've seen an odd number of times.
string input = "acdhqodcqasaf";
var oddOccurrences = new HashSet<char>();
var output = new StringBuilder();
foreach (var c in input)
{
    if (!oddOccurrences.Contains(c))
    {
        output.Append(c);
        oddOccurrences.Add(c);
    }
    else
    {
        oddOccurrences.Remove(c);
    }
}
Console.WriteLine(output.ToString());

Comment: Yes,for the sake of completeness i have provided this [dictionary approach](https://stackoverflow.com/a/53088006/284240)
Comment: Nice one. Now remove every third :)
Comment: Note that you could improve performance marginally by using the bool return on Add or Remove to avoid the call to Contains, but I feel like that would reduce the readability of the method.
Comment: @TimSchmelter: Haha, yeah. You could use a Dictionary to track the number of occurrences and use an arbitrary criteria on the count to determine whether to output the value.
Answer: Create a bool[], that keeps track of odd and even for you:
bool[] even = new bool[256];
string input = "acdhqodcqasaf";
string output = "";
for(int i=0;i<input.Length;i++)
{
    int x = (int)input[i];
    if(!even[x])output += input[i];
    even[x] = !even[x];
}

change bool[256] to bool[256*256], for 16-bit char support.
Live Demo
Comment: Slightly faster than my HashSet approach, but it assumes that all char values will fall in the 0-255 value range.
Comment: Yep, chars are 16-bit in C# ;)
Answer: You can traverse the array, keep a dictionary<char,int> to keep count of each character. Check the count to see if you should delete the char or not add it in a result string.
Answer: Just for fun and giggles I've stopwatched the top answers for this question and added a Distinct method:
return new string(input.Distinct().ToArray());

The output was interesting (10k runs):
ASDHFAJSHKDFASJDFHJgasdfkjhasdjhfashdfkjasdjkfajkhewkjrhwakhfuiwhfsdnfvjndfsjkgnklwerjliu4596945
Distinct 344
RunForEach1 551
RunForEach2 522
RunFor 454

When running 10k times distinct seems to win (in speed) although when running 100 times the result is quite different:
ASDHFAJSHKDFASJDFHJgasdfkjhasdjhfashdfkjasdjkfajkhewkjrhwakhfuiwhfsdnfvjndfsjkgnk
Distinct 9
RunForEach1 7
RunForEach2 1
RunFor 1

Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var input = Console.ReadLine();
            var sw = new System.Diagnostics.Stopwatch();

            sw.Start();
            for (int i = 0; i < 100000; i++)
            {
                RunDistinct(input);
            }
            sw.Stop();
            Console.WriteLine($"Distinct {sw.ElapsedMilliseconds}");

            sw.Reset();
            sw.Start();
            for (int i = 0; i < 100000; i++)
            {
                RunForEach1(input);
            }
            sw.Stop();
            Console.WriteLine($"RunForEach1 {sw.ElapsedMilliseconds}");

            sw.Reset();
            sw.Start();
            for (int i = 0; i < 100000; i++)
            {
                RunForEach2(input);
            }
            sw.Stop();
            Console.WriteLine($"RunForEach2 {sw.ElapsedMilliseconds}");

            sw.Reset();
            sw.Start();
            for (int i = 0; i < 100000; i++)
            {
                RunFor(input);
            }
            sw.Stop();
            Console.WriteLine($"RunFor {sw.ElapsedMilliseconds}");

            Console.ReadKey();
        }

        private static string RunDistinct(string input) {
            return new string(input.Distinct().ToArray());
        }

        private static string RunForEach1(string input) {
            var charOccurences = new Dictionary<char, int>();
            int removeEvery = 2;
            var outputBuilder = new StringBuilder();

            foreach (char c in input)
            {
                charOccurences.TryGetValue(c, out int charOccurence);
                charOccurence++;
                charOccurences[c] = charOccurence;
                if (charOccurence % removeEvery != 0)
                    outputBuilder.Append(c);
            }

            return outputBuilder.ToString();
        }

        private static string RunForEach2(string input)
        {
            var oddOccurrences = new HashSet<char>();
            var output = new StringBuilder();
            foreach (var c in input)
            {
                if (!oddOccurrences.Contains(c))
                {
                    output.Append(c);
                    oddOccurrences.Add(c);
                }
                else
                {
                    oddOccurrences.Remove(c);
                }
            }
            return output.ToString();
        }

        private static string RunFor(string input)
        {
            bool[] even = new bool[256];
            string output = "";
            for (int i = 0; i < input.Length; i++)
            {
                int x = (int)input[i];
                if (!even[x]) output += input[i];
                even[x] = !even[x];
            }

            return output;
        }
    }
}


Preciso igualar uma matriz de string em outra matriz, como faço?

Question: #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 3
#define LEN 80
char texto[MAX][LEN];
int main(){
    char string[MAX][LEN];
    int i, j, k;
    for(i=0;i<MAX;i++){
        printf("Inf. uma string: ");
        gets(texto[i]);
    }
    printf("\n\nstrings digitadas foram\n\n");
    for(i=0;i<3;i++){
        printf("%s \n",texto[i]);
    }
    printf("\n\n");

    for(i=0;i<3;i++){
        for(k=0;texto[i][k];k++){
            if(i==2){
                string[i][k]=texto[i][k];
                printf("String 2: %s\n",string[i][k]);
            }
        }
    }
    system("pause");
    return 0;
}

Answer: Você pode usar a função strcpy() da biblioteca padrão string.h para realizar a cópia de cada uma das strings contidas entre as arrays bidimensionais texto[][] e string[][].
Nunca use a função gets()! Ela foi considerada deprecated devido ao risco de buffer overflow que ela representa. Use scanf() ou fgets() da biblioteca padrão stdio.h.
Segue um código testado com as devidas correções:
#include <stdio.h>
#include <string.h>

#define MAX 3
#define LEN 80

char texto[MAX][LEN];

int main(){
    char string[MAX][LEN];
    int i;

    for( i = 0; i < MAX; i++ ){
        printf("Informe string %d: ", i );
        scanf( "%s", texto[i] );
    }

    printf("\nStrings digitadas foram:\n");

    for( i = 0; i < MAX; i++ )
        printf("[%d] %s \n", i, texto[i] );

    for( i = 0; i < MAX; i++ )
        strcpy( string[i], texto[i] );

    printf("\nStrings copiadas foram:\n");

    for( i = 0; i < MAX; i++ )
        printf("[%d] %s \n", i, string[i] );

    return 0;
}

Porém, se o desafio é não usar a função strcpy(), voce pode tentar algo como:
#include <stdio.h>

#define MAX 3
#define LEN 80

char texto[MAX][LEN];

int main(){
    char string[MAX][LEN];
    int i, j;

    for( i = 0; i < MAX; i++ ){
        printf("Informe string %d: ", i );
        scanf( "%s", texto[i] );
    }

    printf("\nStrings digitadas foram:\n");

    for( i = 0; i < MAX; i++ )
        printf("[%d] %s \n", i, texto[i] );

    for( i = 0; i < MAX; i++ )
        for( j = 0; j < LEN; j++ )
            string[i][j] = texto[i][j];

    printf("\nStrings copiadas foram:\n");

    for( i = 0; i < MAX; i++ )
        printf("[%d] %s \n", i, string[i] );

    return 0;
}

Saída:
Informe string 0: aeiou
Informe string 1: abcdefghijklmnopqrstuvwxyz
Informe string 2: 1234567890

Strings digitadas foram:
[0] aeiou
[1] abcdefghijklmnopqrstuvwxyz
[2] 1234567890

Strings copiadas foram:
[0] aeiou
[1] abcdefghijklmnopqrstuvwxyz
[2] 1234567890


Views results diplay modes

Question: I have a view with its filters exposed. when someone searches for any content results are shown perfectly in list view . now wat i want is a link showing grid view of the same result. more apecific i want a result to be in 2 modes  1) list view and another one is the grid view.
Answer: You can do this by creating two different display of same view. If your current view display is page at path like /view/list-view then create another page display of same view with path like /view/grid-view. Then Configure that display as Grid view under views Format settings. You can use that path to create link to that view later anywhere you want.

Views results diplay modes


Exercises for commutative algebra

Question: I'm currently studying for my final exam of commutative algebra. In the class we covered Artinian rings, Dedekind domains, Integral closures, Grobner basis, (discrete )Valuation rings... I'm particularly interested in exercises involving the exactness of $\operatorname{Hom}(\cdot,N) $ and $\operatorname{Hom}(N,\cdot) $.

Thought that you guys could provide some exercises.

Thank you all in advance.
Answer: A few suggestions:

The canonical recommendation is probably Commutative Algebra by Atiyah and MacDonald. There are a lot of exercises and you can find solutions online to most of them if you want to check your work.
Lang's Algebra has many sections  that might be useful. In particular, his second chapter contains a section of exercises on Dedekind Domains, as does the third chapter if I recall correctly.
If you are looking for some somewhat easier exercises, maybe you can try some of the material in Dummit and Foote.
I believe that Eisenbud's book Commutative Algebra with a View Towards Algebraic Geometry goes into some depth on Gröbner Bases.

My own personal experience is mostly with the first three suggestions. I did a large portion of the exercises in the first 5 chapters of Atiyah and MacDonald and a fair few exercises in Lang.

Exercises for commutative algebra


Is there a topological space which is star compact but not star countable?

Question: A topological space $X$ is said to be star compact if whenever $\mathscr{U}$ is an open cover of $X$, there is a compact subspace $K$ of $X$ such that $X = \operatorname{St}(K,\mathscr{U})$.
A topological space $X$ is said to be star countable if whenever $\mathscr{U}$ is an open cover of $X$, there is a countable subspace $K$ of $X$ such that $X = \operatorname{St}(K,\mathscr{U})$.
We know that there are some topological spaces which are star countable but not star compact. However I don't know whether star compact implies star countable. Is there a topological space which is star compact but not star countable?
Added: $St(K, \mathscr{U})=\cup\{u\in \mathscr{U}: u \cap K \neq \emptyset\}$
Comment: Could you provide a definition of $\operatorname{St}(K,\mathscr{U})$, please?
Comment: $St(K, \mathscr{U})=\cup\{u\in \mathscr{U}: u \cap K \neq \emptyset\}$
Comment: Such a space (if it exists) cannot be normal, because for $T_4$ spaces star compact is equivalent to star finite, so certainly star countable.
Comment: It also hasn't countable extent, and hence it can't be countably compact. However, every star compact space is pseducompact. So the space must be pseudocompact but not countably compact!
Comment: The definition of $\operatorname{St}(K, \mathscr{U})$ added ad the end of your post does not say what you believe it says. You define a set $V\subseteq\mathscr{U}$ by $V=\{u\in \mathscr{U}: u \cap K \neq \emptyset\}$, then what is $\cup V$... I guess you mean something like $\operatorname{St}(K, \mathscr{U})=\bigcup\limits_{u\in V}u$.
Comment: @Didier Piau Right. However we always define that in topological language :)
Comment: In set theory such a notation is widely used
Comment: @Norbert: Any reference?
Comment: @Didier: A reference shouldn't be necessary: that $\cup x=\cup\{y:y\in x\}$ is bog-standard, at least in set theory. However, Ken Kunen's *Set Theory* (North Holland, 1980) defines $\bigcup\mathscr{F}=\{x:\exists Y\in\mathscr{F}(x\in Y)\}$ at the foot of p. 12.
Comment: @Didier: Essentially the same definition is found on p. 11 of Hrbacek & Jech, *Introduction to Set Theory* (Marcel Dekker, 1978) and on p. 34 of Judy Roitman's *Introduction to Modern Set Theory* (Wiley, 1990). Willard's *General Topology* notes the usage on p. 2, though he tends to use indices instead.
Comment: @Brian: Thanks.
Answer: Let $X=\Big(\beta\omega_1\times(\omega_2+1)\Big)\setminus\Big((\beta\omega_1\setminus \omega_1)\times\{\omega_2\}\Big)$ as a subspace of $\beta\omega_1\times(\omega_2+1)$; I claim that $X$ is star compact.
Let $\mathscr{U}$ be an open cover of $X$. For each $\xi\in\omega_1$ there are $U_\xi\in\mathscr{U}$ and $\alpha_n\in\omega_2$ such that $$\langle \xi,\omega_2\rangle\in \{\xi\}\times(\alpha_n,\omega_2]\subseteq U_\xi\;.$$ Let $\alpha=\sup_\xi\alpha_\xi<\omega_2$, and let $K=\beta\omega_1\times\{\alpha+1\}$; $K$ is compact, and $$\omega_1\times \{\omega_2\}\subseteq \operatorname{st}(K,\mathscr{U})\;,$$ since $U_\xi\subseteq \operatorname{st}(K,\mathscr{U})$ for each $\xi\in\omega_1$. The ordinal space $\omega_2$ is countably compact, so $\beta\omega_1\times\omega_2$ is countably compact and therefore star finite, and there is a finite $F\subseteq \beta\omega_1\times\omega_2$ such that $\beta\omega_1\times\omega_2\subseteq\operatorname{st}(F,\mathscr{U})$. But then $K\cup F$ is compact, and $\operatorname{st}(K\cup F,\mathscr{U})=X$, as desired.
However, $X$ is not star countable. To see this, let $$\mathscr{U}=\{\beta\omega_1\times\omega_2\}\cup\Big\{\{\xi\}\times(\omega_2+1):\xi\in\omega_1\Big\}\;;$$ $\mathscr{U}$ is certainly an open cover of $X$, but if $C$ is any countable subset of $X$, we can choose $\xi\in\omega_1$ such that $C\cap\big(\{\xi\}\times (\omega_2+1)\big)=\varnothing$, and then $\langle \xi,\omega_2\rangle\notin\operatorname{st}(C,\mathscr{U})$.
This is a modification of Example 2.1 of Yan-Kui Song, On $\mathcal{K}$-Starcompact Spaces, Bull. Malays. Math. Soc. (2) 30(1) (2007), 59-64, which is available as a PDF here.


Reloading a DIV with another DIV

Question: I'm wondering whether or not it is possible to reload a certain div with its content without refreshing the page or having an external include which loads that div only. For example, when I click my button I'd like the content of my div to be refreshed, without having the whole page reloaded.
Here is an example of what I've tried to do, seems like it doesn't work well but at least explain quite fine what I'm aiming for:
<code>$("#content").load("mypage.php".$("#content"));
</code>
Or for instance:
<code>$("#content").load("mypage.php #content");
</code>
The file IS found and loaded, however something happens during the process. It just comes up as blank window without printing my text and the content of the div (in the original file).
Comment: The first one is invalid. The second one should work, assuming that `mypage.php` returns an HTML page which includes an element with ID `content`. Read more about `load`: http://api.jquery.com/load/, Loading Page Fragments.
Comment: You'll probably need to do an AJAX call, but it is possible.
Comment: Just refer to the Loading Page Fragments http://api.jquery.com/load/ and it will give you what you want. The load also has a callback on complete so you know when it is finished.
Comment: @Felix Kling - Well in that case that's quite odd, because according to what you're saying it should work, whilst it certainly doesn't. My page does have a div with the ID "content" assigned to it, however nothing comes up. Any ideas?
Comment: You can use Ajax, but you can also use element.replaceChild() method
Comment: He doesn't need AJAX if he is just loading static content from another page, `.load()` will do that. `mypage.php` is on the same server/domain right?
Comment: is "mypage.php" the current page?  What data is in the div that needs refreshing?
Comment: To all who mention Ajax: That's exactly what `.load` is doing! It makes an Ajax call, retrieves the HTML and then sets it as new content of the selected element(s).
Comment: @Givi: You cannot say either or. You use Ajax to get the data and then DOM manipulation methods to insert the data.
Comment: "mypage.php" is the very same page, I'm simply trying to refresh its content. It just loads a blank white window when I try to use the method, even though I believe I'm doing everything according to the rules. The div I'm trying to refresh contains some HTML call and PHP functions within it as well.
Comment: @Tommy: I fear there is not really much we can say without more information. I recommend to create a simple example and try to get it working. When/how/where are you calling `$("#content").load("mypage.php #content");`?
Comment: @Felix: I call this function upon a successful submission of my form. There is no problem with the rest of my code though, the problem is with this function only.
Comment: @FelixKling why not ? you can create documentFragment and then toggle elements with replaceChild
Comment: @Tommy: How are you submitting the form? If you want to update the div without reloading the page, you have to submit the form via Ajax as well. Otherwise you will just be redirected after the form was submitted.
Comment: @Givi: And how do you get the updated data? Of course you can create DOM elements with JavaScript and populate it with data generated with JS, but here in this case the OP needs the data from the server! You don't have to choose between Ajax OR DOM manipulation. These are two different things.
Comment: @FelixKling Well in that case, you're right.
Comment: It's possible that the form is getting cached.  Try adding a timestamp as a query string
$("#content").load("mypage.php?t=23433 #content");
Comment: @Givi: I disable the submission, I meant to say that I call this function on a successful validation of my form. It doesn't do anything at this point, it used to alert me that the validation is fine but I disabled it in order to test this reloading thing. In other words, the form doesn't get submitted in the end of my process.
Comment: Another possibility is that it's not finding the page.

try to set the path a little more relative

$("#content").load("../mypage.php #content");
Comment: @Javaslu: Not much of a change, still a blank white page. Although I find it hard to believe it can't find the page, considering the fact it's the very same page I'm trying to load. I might be missing something, though.
Comment: @Tommy: Without seeing the code or at least simplified version, we can only guess.
Comment: Well problem is that I've got quite much of a code in both of my pages, I'll try to come up with a live example though.
Comment: I've edited my main question with an example of a file I'm trying to include.
Comment: Sorry for the bump but is anyone having any ideas?
Comment: @TommyNaidich You can start a bounty if you want to bump.
Answer: I assume you want to update an element with the newest content.
Let's say you open a web page now, edit a certain element, then open the edited one in a new tab, and you want an element from the first tab to get the latest content of a new tab.
I made this really simple function, no jQuery needed. Check it out:
<code>function reloadElement(selector, url){
    if(!url) url = location.href;
    var container = document.createElement("div");
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            var r = this.responseText;
            container.innerHTML = r;
            var e = container.querySelector(selector).outerHTML;
            var l = document.querySelector(selector);
                l.outerHTML = e;
        }
    };
    xhttp.open("GET", url, true);
    xhttp.send();
}
</code>
Here's how it works:

The function expects two parameters: a CSS selector and an optional url where to reload from.
If the url parameter is not passed, current page's url is used instead.
It loads the page in an artificial container and finds a required element by a path, fetches its content and updates the real one.

Reloading a DIV with another DIV