When $f_n$ convergent in measure?

Question: Suppose $f_n$ is a sequence of functions over measurable space $(X,\mu)$. Which one of the followings statements hold?

If we have $f_n \to f$ uniformly, could we say $f_n \to f$ in measure?
If  we have $f_n \to f$ in $L^1(\mu)$, could we say $f_n \to f$ in measure?
If  we have $f_n \to f$ $a.e.$, could we say $f_n \to f$ in measure?

If those are not true, which conditions are required?
Comment: Please edit your post to show what you tried so far. Also, there is no complex or functional analysis involved here. Please remove those tags. You may consider adding the measure theory tag, however.
Answer:
yes
yes
no

If the space is finite or if the convergence is dominated, then 3 is valid.

When $f_n$ convergent in measure?


Facebook flash games high scores API

Question: As I am new to facebook games is there any third party API for flash games.
Actually I used mochi highscore API but I don't want to login through mochi. Direct submission through facebook id. Let me know any third party API or suggest any tutorials.
regards,
chandu
Answer: It is fairly easy to post a score to the highscores in Facebook, check out the following code. All you need is a userID which you get from facebook when you log the user in and the value that you use in your game as a score like experience, points or whatever.
<code>// post experience as score
$experience = 1000; // get this from your database
$contents = file_get_contents("https://graph.facebook.com/oauth/access_token?client_id=".FACEBOOK_APP_ID."&client_secret=".FACEBOOK_SECRET_KEY."&grant_type=client_credentials");

$exploded = explode("=",$contents);

$accessToken = $exploded[1];
$score_URL = 'https://graph.facebook.com/' . $userFacebookID . '/scores';
$score_result = https_post($score_URL,
  'score=' . $experience
  . '&access_token=' . $accessToken
);
</code>
https_post function looks like this :
<code>function https_post($uri, $postdata)
{
    $ch = curl_init($uri);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
    $result = curl_exec($ch);
    curl_close($ch);

    return $result;
}
</code>
You can put this in your index.php after you get the facebook user ID and their score will be sent every time they come to the game.
Hope that helps.

Facebook flash games high scores API


Customizing logback color scheme

Question: I have been messing with my logback coloring and Im wondering if I can change the highlighting colors. Right now I have this

Which is ok, but I would like to make info blue, warnings yellow and errors non-bold red or something along those lines. Is that possible? Also, is it possible to select different colors for the logger name highlighting? For instance, if I wanted com.blah to be cyan and org.apache logger magenta or something else? My current pattern is
 <Pattern>%d{HH:mm:ss.SSS} %highlight(%-5level) [%thread] %cyan(%logger{36}) - %highlight(%msg%n)</Pattern>

This is a Scala project with SBT and I use logback for logging if that makes a difference.
Answer: Yes, judging from the Spring ColorConverter this should be possible with a bit of custom code. See the default Spring logback configuration.
For coloring JSON output with Logback Logstash, I've written (shameless plug) this project in which the same type of functionality can be added.
Answer: the bellow works for me
Java Code
package com.acme.logback;

public class MyCustomHighlighting extends ForegroundCompositeConverterBase<ILoggingEvent> {

    @Override
    protected String getForegroundColorCode(ILoggingEvent event) {
        Level level = event.getLevel();
        switch (level.toInt()) {
        case Level.ERROR_INT:
            return ANSIConstants.BOLD + ANSIConstants.RED_FG; // same as default color scheme
        case Level.WARN_INT:
            return ANSIConstants.RED_FG;// same as default color scheme
        case Level.INFO_INT:
            return ANSIConstants.CYAN_FG; // use CYAN instead of BLUE
        default:
            return ANSIConstants.DEFAULT_FG;
        }
    }

}

Logback.xml
<configuration>

    <conversionRule conversionWord="myCustomHighlighting" converterClass="com.acme.logback.MyCustomHighlighting" />

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <withJansi>true</withJansi>
        <encoder>
            <pattern>[%thread] %myCustomHighlighting(%-5level) %logger{15} - %myCustomHighlighting(%msg) %n</pattern>
        </encoder>
    </appender>

    <root level="DEBUG">
        <appender-ref ref="STDOUT" />
    </root>
</configuration>

Customizing logback color scheme


Form With Inline Input Boexes

Question: I am trying to create a form that will have the input boxes inline and next to one another. I have created the following module but nothing seems to help. Can anyone help to solve this issue? Also the form doesn't seem to be reacting to changes in the size parameters.
function name_search_block_info() {
    $blocks['name_search'] = array(
        'info' => t('Name Search Block'),
    );
    return $blocks;
}

function name_search_block_view($delta='')
{
     $block = array();
     switch($delta)
     {
        case 'name_search':
          $block['subject'] = t("Search Form");
          $block['content'] = "
".drupal_render(drupal_get_form('name_search_custom_search_form'))."
";
          break;
     }
     return $block;
 }

function name_search_custom_search_form($form_state) {
  $form = array();

  $form['keyword'] = array(
    '#type' => 'textfield',
    '#required' => TRUE,
    '#attributes' =>array('placeholder' => t('Search')),
    '#maxlength' => 64,
    '#size' => 32,
    '#required' => TRUE,
    '#id' => 'searchfield',
    '#prefix' => '
',
    '#suffix' => '
',
  );
  $form['location'] = array(
    '#type' => 'textfield',
    '#required' => TRUE,
    '#attributes' =>array('placeholder' => t('Zip')),
    '#maxlength' => 5,
    '#size' => 7,
    '#required' => TRUE,
    '#id' => 'locationfield',
    '#prefix' => '
',
    '#suffix' => '
',
  );

  $form['#submit'] = array('name_search_custom_search_form_submit');

  return $form;
}

function name_search_custom_search_form_submit($form, &$form_state) {
  $redirect_url = 'search/node/';
  $redirect_url .= 'type:' . $form_state['values']['type'];
  $redirect_url .= ' category:' . $form_state['values']['category'];
  $redirect_url .= ' %' . $form_state['values']['keyword'] . '%';

  $form_state['redirect'] = $redirect_url;
}

Answer: No need to add prefix/suffix markup, just add a container or fieldset and use CSS to float them inside.

Form With Inline Input Boexes


Number of lattice points in a $L^1$-ball

Question: I am trying to count the number of elements in
$$
S_{n,k} = \left\{(n_1,\ldots, n_k): \forall i,n_i \in \mathbb Z, n_i \geq 0, \sum_i n_i = n\right\},\\
T_{n,k} = \left\{(n_1,\ldots, n_k): \forall i,n_i \in \mathbb Z, \sum_i |n_i| = n\right\},\\
$$
I have already find out the size of $S_{n,k}$ here. But I find it hard to find a simple expression for $T_{n,k}.$ To express $T_{n,k}$ in terms of $S_{n,k},$ one need to do lots of overcounting and inclusion-exclusion, and apparently it is hard to find a closed form.
Does a nice expression for the size $|T_{n,k}|$ exists?
Comment: Obviously $|T| \leq 2^k |S|$. You have at most $2^k$ cases for each case in $S_{n,k}$. Because you can switch the signs.  For example: $(n_1, n_2), (-n_1,n_2), (n_1,-n_2), (-n_1, -n_2)$ are in $T$ for $(|n_1|, |n_2|)$ in $S$. I said at most because you have to deal with zeroes. You can seperate cases with zeros like $(0,n_2)$. It's doable.
Answer: In this answer, Christian Blatter proved
$$|T_{n,k}|=\sum_{j=0}^{\min(n,k)}\binom nj\binom kj2^j.$$ This cannot be written without a summation, which you can prove using Zeilberger's algorithm and Petkovšek's algorithm.
This formula reveals a symmetry between $k$ and $n$ which is not at all obvious from the definition.


Imprimir duas ou mais paginas usando o jsPDF

Question: Estou a gerar o meu html em PDF com JsPDF. O meu html é maior do que uma folha A4. Para resolver o problema preciso de criar paginação em Jspdf.
Código que tenho que só gera pdf com uma página:
window.html2canvas = html2canvas;

function demoFromHTML() {

const html_source = document.getElementById('employee_detail'); // O id do elemento que contém o Html que quer imprimir.
const filename = 'Test.pdf';

html2canvas(html_source).then(function(canvas) {
let imgData = canvas.toDataURL('image/png');

let pdf = new jsPDF('p', 'mm', 'a4'); // Essas demissões [297, 210] correspondem a um A4

// addImage(imageData, format, x, y, width, height, alias, compression, rotation)
// x: Coordenada (em unidades declaradas no início do documento PDF) contra a borda esquerda da página
// y: Coordenada (em unidades declaradas no início do documento PDF) contra a borda superior da página
pdf.addImage(imgData, 'PNG', 10, 10);
pdf.save(filename);
})

}

Para criar essa paginação preciso de usar o pagesplit, mas não estou a conseguir gerar pdf com mais de uma página.
Comment: Viva. Tenho uma ideia para te ajudar. Mas preciso da sua ajuda, me encontras no [chat room](https://chat.stackexchange.com/rooms/93960/discussion-between-cristiano-gilberto-joao-and-bruno).
Answer: Esta solução quebra uma página grande em várias páginas automaticamente.
window.html2canvas = html2canvas;

function demoFromHTML() {

  const html_source = document.getElementById('employee_detail'); // O id do elemento que contém o Html que quer imprimir.
  const filename = 'Test.pdf';

  html2canvas(html_source).then(function(canvas) {
    /*
    [210,297] Sao os números (largura e altura do papel a4) que eu encontrei para trabalhar com eles.
    Se você puder encontrar números oficiais do jsPDF, usa.
     */
    let imgData = canvas.toDataURL('image/png');
    let imgWidth = 210; // Largura em mm de um a4
    let pageHeight = 297; // Altura em mm de um a4

    let imgHeight = canvas.height * imgWidth / canvas.width;
    let heightLeft = imgHeight;
    let position = 0;
    let pdf = new jsPDF('p', 'mm');
    let fix_imgWidth = 15; // Vai subindo e descendo esses valores ate ficar como queres
    let fix_imgHeight = 15; // Vai subindo e descendo esses valores ate ficar como queres

    pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
    heightLeft -= pageHeight;

    while (heightLeft >= 0) {
      position = heightLeft - imgHeight;
      pdf.addPage();
      pdf.addImage(imgData, 'PNG', 0, position, imgWidth + fix_imgWidth, imgHeight + fix_imgHeight);
      heightLeft -= pageHeight;
    }

    pdf.save(filename);
  })

}

Comment: o código está a funcionar e gera as 3 páginas no pdf, só existe um problema, não quebra de forma correta, corta as linhas a meio, exemplo [link](https://i.stack.imgur.com/PH03x.png)
Comment: precisava da sua ajuda, podemos falar no chat [link](https://chat.stackexchange.com/rooms/93960/discussion-between-cristiano-gilberto-joao-and-bruno)
Comment: pode ver o chat


Logic and Sets; questionable deduction skills of the Investigator (Textual problem)

Question: The Investigator knows about the 4 suspects P, Q, R and S:
Here we have 4 laws to follow (a,b,c,d)

(a) P is guilty if and only if Q is innocent.
(b) R is innocent if and only if S is guilty.
(c) If S is a perpetrator, then P and vice versa.
(d) If S is guilty, then Q is involved.

I made a truth table for all possible outcomes for p q r and s
P Q R S

T T T T
T T T F
T T F T
T F T T
F T T T
T T F F
T F F T
F F T T
T F F F
F F F T
F F F F

then i set the laws in order;

Law A:"P is guilty if and only if Q is innocent." which implies the following; P<=>(¬Q) which is bijuction but I reversed Q with
negation
Law B: "R is innnocent only if S is guilty" which i also read as bijunction (¬R)<=>S
Law C " If S is a perpetrator, then P and vice versa." which is bijunction but without the need to negate anything, therefore it assume it can be written as S<=>P
Law D "If S is guilty, then Q is involved" where there is no "vice versa" so its vectorish?, like subjunction; S -> Q

So I inserted the negations of R and Q in my table sinceI'll be needing them and added the results of the rules
P Q R S ¬R ¬Q P<=>(¬Q) (¬R)<=>S S<=>P S->Q

T T T T  F  F    F          F     T     T
T T T F  F  F    F          T     F     T
T T F T  T  F    F          T     T     T
T F T T  F  T    T          F     T     F
F T T T  F  F    T          F     F     T
T T F F  T  F    F          F     F     T
T F F T  T  T    T          T     T     F
F F T T  F  T    F          T     F     F
T F F F  T  T    T          F     F     T
F F F T  T  T    F          T     F     F
F F F F  T  T    F          F     T     T

After this i really got lost, I've been trying a lot of methods but none of them have concrete sense.
I tried getting rid of one suspect by merging two into one following the sense of the laws like S -> (P <=>(¬Q) or something like that, but nothing really makes sense.
The question remains: Who did it?
Comment: Your table has only 11 rows. It should have 16.  You're missing 5 rows!
Answer: Note that S<=>P<=>(¬Q) and S=>Q, therefore S is false and consequently P is false as well and R and Q are true. The combination F T T F is not listed. You should have $2^4$ possibilities.
Answer: Solved it and after that and just kinda forgot about it, thanks!
It all added up, Q and R were the Killers. There is no great skill behind it, you just have to find the one row where every condition is True(T)
Untill next time!


Automatic method to set the tabindex using form helpers

Question: Is there an easy way to have the form helpers set the tabindex parameter automatically when using form helpers in Rails?
Basically, I don't want to have to manually set the tab index on every form element when building forms (I keep forgetting to update them when I change things).  The majority of the forms I write are basically a list of fields.  The tab index should be in the order they are defined.  Ideally, I would set the initial index in the form_for call and everything else would be handled for me.
Does anyone know how to do this?
Answer: I usually add a method like this to ApplicationHelper
def autotab
  @current_tab ||= 0
  @current_tab += 1
end

Then in my views I make calls to the helper with a :tabindex => autotab like so:
<%= text_field "post", "login",:tabindex => autotab, :value => @login %>

You can also modify all the text_field, check_box,  methods one at a time to add the tabindex automatically, by adding something like this to your application helper: (untested but you get the point)
def text_field_with_tabindex(*args)
  options = args.last
  options[:tabindex] = autotab if options.is_a?(Hash) && options[:tabindex].nil?

  text_field_without_tabindex(*args)
end

def self.included(base)
  base.class_eval do
    alias_method_chain :text_field, :tabindex
  end
end

That might be more trouble than it's worth
Comment: I have use local variable instead of instance variable will you please explain me why its not working if I take current_tab instead of @current_tab


Add class and remove class in Ul li a using jQuery

Question:

Product Master

|

Charges Computation Master

I need to add active class in anchor tag when I click  and remove the active class from previous  tag
Comment: can you add a fiddle with your whole css and html code
Comment: Please share minimum piece of code what you have tried and also the markup!
Answer: Try this one..
$(".tab_sublinks a").on("click", function(){
$(".tab_sublinks a").removeClass("active");
  $(this).addClass("active");
});

this one will remove active class from all a tags inside tab_sublinks and add active  class to the current element.
Comment: I've already answered the same. Please check other answers before posting.
Comment: No issues buddy. I have updated my answer. :-) Also just a note, if possible, always try to explain your attempt. This will ensure everyone (*even beginners*) gets you answers.
Answer: You should use a generic selector to remove active class from all  tags and then use this to add class to current tag.
Generic selector
This will work if the generic selector is unique i.e. you do not have more of tab_sublinks.

$('.tab_sublinks a').on('click', function(){
  $(".tab_sublinks a").removeClass('active');
  $(this).addClass('active');
})
.active{
  background: #ddd;
}

Product Master

|

Charges Computation Master

Search using this
This is more robust way as you are using this to search element and will have effect in current scope. If you have multiple tab_sublinks this is more preferred way

$('.tab_sublinks a').on('click', function(){
  $(this)
  // Search nearest element with `tab_sublinks`
  .closest('.tab_sublinks')
  // Search for a.active in this element
  .find('li a.active').removeClass('active')
  $(this).addClass('active');
})
.active{
  background: #ddd;
}

Product Master

|

Charges Computation Master

Product Master

|

Charges Computation Master

Answer: You can add the active class using the jQuery click event.

$(document).on('ready', function() {

  $('.js-nav-item').click(function() {
    $('.c-active-link').removeClass('c-active-link'); // Remove Class First
    $(this).addClass('c-active-link'); // Add Class to Active Item
  })

});
.c-active-link {
  color: red;
}

Product Master

|

Charges Computation Master

Comment: This will have huge impact as `.active` can be applied to a lot of elements
Comment: @Rajesh you are correct if OP was using the class `active` in multiple areas. However, this will not impact the user if the class is unique to the nav area (i.e. `c-active-link`) but OP is asking for jQuery advice and not performance/structural advice.
Comment: `.active` is a very commonly and widely used class. But yes, if OP is using only one element, nothing wrong with it
Comment: I have updated my answer to portray the uniqueness of the nav-link active class. Whatever OP is planning to develop I am certain they will intend on avoiding css/jQuery conflicts in their code.


Are copyright traps in musical scores a thing?

Question: Maps, dictionaries, and similar sometimes contain copyright traps, which are intentionally false information like a street that does not exist. The point of these is that when somebody plagiarises the work and includes the copyright trap, this evidences the plagiarism.
Is it known that such copyright traps exist in musical scores as well?
I am asking because I sometimes notice notational quirks in arrangements of public-domain music, such as:

A G♯ when the rest of the score uses A♭ in analogous places (and it's a piano score such that the distinction between G♯ and A♭ doesn't matter).
Different fingerings for analogous sections.
Dynamic indications that only affect breaks.

These are without any real effect, but so bizarre that they are unlikely to be just mistakes. My best explanation is that they are copyright traps. And since these are arrangements, a copyright trap actually has some purpose: For example, without one, it might be difficult to prove that somebody plagiarised your arrangement of Pachelbel's canon instead of copying the (public-domain) original.
Mind that I am not asking about the legal implications of these traps or whether they are a good thing, just whether they exist.
Comment: I've heard anecdotal talk about the opposite, that International music editions (notoriously iffy) would copy older editions but intentionally introduce errors so they could claim to be distinct
Comment: "and it's a piano score such that the distinction between G♯ and A♭ doesn't matter": this isn't correct.  The distinction between G♯ and A♭ almost always matters in piano music, just as it almost always matters in any staff notation.  What is "Dynamic indications that only affect breaks"?
Comment: I don't remember what piece it was, but in one particular score that I read, I saw several minor sevenths where there should have been harmonic sevenths.
Comment: *The distinction between G♯ and A♭ almost always matters in piano music* – How would it matter? I am pressing the same key. I can only imagine some fringe cases, where I tune the piano for this particular piece. — *What is "Dynamic indications that only affect breaks"?* – Something like *forte, break, piano* as opposed to *forte, some notes, piano*. You are essentially instructed to play a break (and only that) with higher volume.
Comment: "How would it matter?" First, it's difficult to read enharmonically misspelled music.  Second, the reader has to decide whether you're trying to convey something specific and meaningful, or you don't know what you're doing. The choice of G sharp or A flat is dictated by the musical function or role of the note; the fact that this may also have implications for tuning is secondary.  Can you add some examples of these "quirks"?  They may be easy to explain as legitimate choices, but without seeing them we can only speculate.
Comment: @AndyBonner A similar case happened for the Rite of Spring, as one of the reasons for a new edition (which included a revised version of the Sacrifical Dance) was to avoid copyright issues of existing versions from other editors.
Comment: Were all the "notational quirks" you mentioned found in self-published sheet music only (yes, I count Musescore as self-published), or did you find at least one in an actual music book?
Comment: @Dekkadeci: I found these in actual books.
Comment: @phoog: Okay, it doesn't matter in the sense that it affects what is actually played. It does matter for readability. — *Can you add some examples of these "quirks"? They may be easy to explain as legitimate choices, but without seeing them we can only speculate.* – Well, speculation about each of these choices and their purpose is exactly what I wanted to avoid. If I want to know about potential explanations for a particular quirk, I might ask a separate question on this. This question is about whether "it's a copyright trap" is an explanation that generally holds any water.
Answer: The comparison with maps doesn't really hold:
With notated music, the typical piracy threats are:

Stealing from a composer by notating and distributing their composition without their permission. Easy to prove or disprove the piracy with the composer: Either you got permission or you didn't.

Stealing from a publisher by copying their sheet music (even if the copyright of the composition itself is already expired). This could be by scanning printed sheet music or copying the PDFs. Even if you do the effort of masking out the copyright statements of the publisher, there's so many variables in music typesetting (spacing, fonts, stem directions, ...) that it should be obvious to prove the piracy.

With maps, there is no composer; nobody has copyright on the earth. And anyone that creates a map is bound to come up with very similar results. Furthermore, you can easily reformat stolen map data to make it look like your own. This is harder to do for music. I suppose you could process sheet music by optical music recognition software, reformat and republish the results... But I doubt that this constitutes a big loss for music publishing companies (and, if the copyright of the composition hasn't expired, then you can still get caught for type 1 piracy).
Comment: @Wrzlprmft if two people make _arrangements_ of Pachelbel's Canon, they aren't the same except by chance or by copying.  The point of putting a copyright trap in your map is to identify people who got their _facts_ from your work.  In an arrangement of Pachelbel's Canon, the only facts are the original work itself, which doesn't change over time as geography does, and where using a recent edition isn't going to save anyone much time compared to using an old one.  Any notes in your arrangement that differ from the original aren't a copyright trap; they're the arrangement itself.
Comment: @phoog: To take up the fingering example, of course all the fingerings are protected by copyright, but Carl may claim that his fingering matches Theodore's not due to plagiarism but because it is one of few reasonable fingerings for the piece. If however Theodore is using some unusual fingering where the normal reader wouldn't notice (e.g., because it's a repetition), and Carl copies that, Carl's claim would be disproven. Finally mind that my question is not about what is technically copyright infringement or what is litigable, but whether any publisher chose this as a precaution.
Comment: *And anyone that creates a map is bound to come up with very similar results.* – Well, that's more or less my point: Every simple arrangement of, say, Pachelbel's canon will be similar. Maybe less similar than maps, but similar enough that it's difficult to claim that somebody copied from the arrangement instead of the original. — *you can easily reformat stolen map data to make it look like your own. This is harder to do for music.* – Map data maybe, but not compiled maps. I would argue that scores can be easily copied once you know how to typeset scores.
Comment: Another way of looking at it, since you mention fingering in the question: if Theodore publishes an edition of Pachelbel's Canon with fingerings, there's no point in varying the fingerings in analogous places because _all_ of the fingerings are protected by copyright.
If the fingerings in Carl's edition match, they match, regardless of any internal inconsistencies in the source.
Comment: @Wrzlprmft fair points.  At first I was thinking only of musical arrangements, where these considerations aren't really applicable.  But for other editorial elements there's more of a case to be made.


Relationship between logistic regression and linear regression

Question: I've encountered a problem where I need to analyze the relationship between a movie's length, a movie's price and it's sale on a video streaming platform. Now I have two choices to quantify sale as my dependent variable:

whether or not a user ended up buying the movie
selling rate (# of people buying the movie / # of people watched the trailer)

if I use selling rate I essentially would use a linear regression where I have $$selling\ rate= \beta_0 + \beta_1*length + \beta_2*price + \beta_3*length*price$$
But if I'm asked to use option 1 where my response is a binary output, and I assume I need to switch to logistic regression, will my coefficients change and how will them change? How would the standard error change? Will the standard error be an underestimate?
This is just a discussion question and I don't have actual data for it, I'm confused on how is logistic and linear regression related and whether they are interchangeable in some way?
Answer: As both scenarios represent a binary choice of buy/didn't, both would best be modeled with logistic regression. Linear regression is designed for continuous outcomes that are theoretically unrestricted in values. That not the case for either scenario.
The second "selling rate" model might be interpreted in two ways. If all who bought also had watched the trailer, then its outcomes are restricted to the range [0,1] and a logistic regression makes sense. If people can buy without watching the trailer, how do you deal in a linear regression with an infinite "selling rate," as you defined it, if no one happened to watch the trailer but at least one bought? The latter interpretation of the second scenario would also best be modeled by logistic regression, with watchedTrailer as a predictor in the model and including all visits to the site in the data set.
It's hard in general to associate linear and logistic regression coefficients, as they represent different things. For linear regression it's the change in value of the outcome per unit change in a predictor, here a change of probability. But probabilities can't be outside of [0,1]. For logistic regression it's the corresponding change in log odds of the probability of the outcome, with values covering [$-\infty,\infty$].
That said, sometimes people do formulate a linear probability model, with probability as the outcome variable in a linear regression. If you do use a linear probability model, you can interpret a regression coefficient in terms of the fractional change in probability associated with a unit change in the predictor. If probabilities are in the middle range near 50/50 that can work OK and results might be similar to a logistic regression. But with probabilities near the edges of [0,1] a linear probability model can make predictions of probabilities outside that theoretically allowed range.
So use a logistic regression or other modeling approach that takes the [0,1] limits of probability into account when you encounter these types of scenarios.
Comment: Does it mean that since selling rate takes range [0,1], I can treat it like a probability and model it use a logistic regression?
Comment: @RoxS yes. Logistic regression software like `glm()` in R allows for outcomes to be individual 0/1 results or aggregate counts of yes/no. So if you have aggregated data for each movie (its covariates, the number who saw the trailer, and the number who bought) then you can simply do a logistic regression once you have the data in the proper format. For example, `glm()` expects outcomes for aggregated data to be in a 2-column matrix of success counts and corresponding failure counts. But do that with the raw counts, to take into account the greater information provided by more counts.
Comment: What if people buy the movie without watching the trailer?
Comment: @kurtosis the "selling rate" outcome proposed in the OP wouldn't make sense in that situation. In the answer I nevertheless suggested modeling with `watchedTrailer` as a logistic regression predictor if individuals can buy movies without watching the trailer. That would be most useful with individual-level data, but you might even get some information with aggregated data on numbers/proportions who watched
Comment: Beta regression would be an option for the selling rate?
Comment: @NicolasMolano in principle yes, provided all values were between 0 and 1, with no values exactly 0 or 1. This question, however, was specifically about linear versus logistic regression.


Can you SET a MySQL variable in ADOdb to avoid repeating bind variables?

Question: I'm using ADOdb with MySQL in PHP and trying to pass a keyword multiple times as a bind variable without having to repeat it in my $queryParams array, is this possible? I'm having an error thrown due to the semicolon.
  $queryParams = [$keyword, $row_ids];
  $query = "
    SET @myKeyword = ?;
    SELECT *
    FROM my_table
    WHERE row_id IN (?)
    AND (
      row_desc1 = @myKeyword
      OR row_des2 = @myKeyword
      OR row_desc3 = @myKeyword
    )";

  $connection->execute($query, $queryParams);

What I'm trying to avoid:
  $queryParams = [$row_ids, $keyword, $keyword, $keyword];
  $query = "
    SELECT *
    FROM my_table
    WHERE row_id IN (?)
    AND (
      row_desc1 = ?
      OR row_des2 = ?
      OR row_desc3 = ?
    )";

  $connection->execute($query, $queryParams);

Comment: You have my sympathy.
Comment: @Dai you can, just not like this.
Comment: ...why are you using ADODB in PHP instead of PDO?
Comment: Because that's what the codebase I was assigned to is using and I have a job to do.
Comment: The problem is that you cannot parameterize the `WHERE x IN ( ... )` operator in SQL. You need to either generate dynamic parameters (which is almost as fun..er...painful as Dynamic-SQL) or do an `INNER JOIN` on a table-valued-parameter.
Comment: And then your next question will be how to bind multiple values for in operator as the query matches the first value only...
Answer: Most query interfaces do not support multi-statements by default. That is, you can't send two SQL statements in one call.
https://dev.mysql.com/doc/internals/en/multi-statement.html says:

The client must announce that it wants multi-statements by either setting the CLIENT_MULTI_STATEMENTS capability or by using COM_SET_OPTION.

This is something the code making the connection (ADODB in this case) would have to do when you connect.
But it won't work anyway, because multi-statements cannot work with prepare(), therefore cannot be used with query parameters.
https://dev.mysql.com/doc/refman/8.0/en/prepare.html says:

The text must represent a single statement, not multiple statements.

You could make two calls, one to do the SET and the second to do the SELECT that uses that variable you had set in the first call. As long as the two calls use the same MySQL session, the variable will keep its value.
Alternatively, in your example of repeating the keyword, you could write it this way:
AND (
  ? IN (row_desc1, row_des2, row_desc3)
)

This allows you to pass the keyword parameter once, and it still compares it to three columns.
P.S.: You also have a problem with your other condition: row_id IN (?). You can't use a single parameter for multiple values for an IN predicate like that.
Comment: Right, I assumed that it was a CSV string. But it will execute as if you had written a query with `WHERE row_id IN ('1, 2, 3, 4')` which is a single string, not a list of discrete values. Keep in mind that query parameters are not simply string substitution.
Comment: _"Most query interfaces do not support multi-query by default. That is, you can't send two SQL statements in one call."_ - is that something unique to PHP? Because ODBC/OLE-DB/ADO.NET supports statement-batches, heck, even MS Access 97 does....
Comment: It's not unique to PHP, it's a MySQL connector option that is not enabled by default. Also I forgot another issue: Even if the ADODB connector allows you to enable multi-statements, MySQL does not support `prepare()` for multi-statements, so you can't use multi-statements and query parameters anyway.
Comment: It's a CSV list of numbers, e.g. `WHERE row_id IN (1, 2, 3, 4);`


Custom PHP vs Drupal Workflow for a Web Application not Websites

Question: This question can be too ambiguous but i think many new drupal users face this difficulty like me.
There are many blogs which says that Drupal is a CMF and we can use it for making Web Application rather then using it like Wordpress for articles and pages.
For the sake of example lets say i have to make a task management system with a specific Application style UI and features. If i would have to make it by custom programming i would be making tables for tasks, users, task_attachments, clients and so on and will make relations accordingy.
My question is how we can do all this stuff in Drupal? Nodes are for content and i would not go for nodes to achieve this. The other thing is Entity but How one can properly utilize Entities. If i have to list all tasks for a specific user, If a user want to update a status of his task or attach some file, If its a team and other team members should also be allowd to post updates on tasks. These are the common application scenarios that we usually make in this kind of application.
If someone provide a brief workflow then it would be a great effort for helping beginners like me to use Drupal as a developer rather than doing a data entry job by installing modules and copying content , images.
There is a good example erpal.info but its too advanced for me at this level to jump into it. but a mini erpal would be great.
Thanks Alot.
Answer: Your questions are somewhat vague but I'll provide some examples:

For instance I have a site that from a CSV file allows certain visitors emailed access keys to access a Webform and its tracked via a custom Node that has an embedded field collection and this relationship + status is tracked via a Relation. I use the Migrate module to add or update allowed visitor information from the CSV.

I use the Webform API, EntityFieldQuery's and drupal hooks to do my webapp business logic. Drupal core and contrib modules provide additional APIs. I use Views Send for bulk emailing.

I have another form site for class reviews for a campus. I use Migrate to pull $form structure info from a 3rd party survey database and then use a custom drupal entity and the drupal Form API to build a custom form from remote data. The remote database has a custom schema for say: Question, Options, Question position in Form, Form ID, etc ... it gets converted into a drupal $form array with some simple PHP in a Migration class. Again I use Relation to track what the student has completed between a uid and a nid. I use the drupal authorization mechanisms such as authmaps to integrate our local LDAP server.
On another site students should fill out like 10 content types after login. I use hook_menu_alter and a cookie to assure a student has Opted-In daily to EULA's for uploaded content. Then I use the core Form API to link 10 node edit forms on submission from 1 to another. Creating a kind of workflow for the student.

There are numerous times where knowing the Drupal contributed modules that help you create business logic, such as: Rules, Triggers, Rules Link, Maestro and WorkBench all help you create types of business logic.
Modules like References, Relation, Field Collection, Paragraphs let you create "embedded relationships". Mix and match as you need.
... I got tired of linking contrib modules :P
Comment: Nice Examples. So the relation works the same as we make relations in databases by foreign keys ?
Comment: not exactly. if a table has a `FK` in a legacy application using the Relation module you'd make a `Relation` (entity) to describe it. No `FKs` are added to the `User` or `Node` tables for example. It's a developer module, you may like EntityReference better.


How to add the placeholder in view exposed filter

Question: I am just created a block-view with exposed filter in view,, now i want to give the placeholder to auto-complete widget type same as label name , how can i do this ?
Answer: You can simply add below code to form alter hook
<code>$form['title']['#attributes']['placeholder'] = t('Keyword search');
</code>


How do I get the data from "#PCDATA" in Scala?

Question: def loadXml(node: Node): Unit = {

  val children = node.child

  children.foreach(child => {
    var tag = child.label

    //if owner tag, load the owen
    if (tag == "zip")
    {
      loadZipXML(child)
    }
    else if (tag == "owner")
    {
      //if owner tag, make a new pet and have it load the info it wants, then add it to the list
      val owner = Owner()
      owner.loadXml(child)
      insurance += owner
    }
  })
}

I have the following code and I'm feeding it this XML:
<?xml version='1.0' encoding='UTF-8'?>
<insurance>
    <zip code="57701">
        <owner name="Harold">
        </owner>
        <owner name="Bob">
        </owner>
        <owner name="Indiana Jones">
        </owner>
        <owner name="Darth Vader">
        </owner>
    </zip>
    <zip code="57702">
        <owner name="Sue">
        </owner>
        <owner name="Captain Kirk">
        </owner>
    </zip>
    <zip code="57703">
    </zip>
</insurance>

I can pull the zip code fine. But every time I get owner the label becomes #PCDATA. I know that means that its a child with more data, but how do I grab that label and then keep traversing the XML file?
Comment: You forgot to include the `import` statement that informs the compiler, and the reader, which XML library you're using.
Comment: Would that be   "import scala.xml._"
Answer: Not sure why you need the XML label, but it sounds like you're trying to marshal the data in to an "owner" data structure.  For example, consider this "owner" class:
final case class Owner(
  label: String,
  name:  String,
  text:  String,
  zip:   String)

I'd probably iterate through the XML as:
val insurance = scala.xml.XML.load("insurance.xml")
val owners =
  for {
    zip   <- insurance \ "zip"
    owner <- zip \ "owner"
  } yield {
    Owner(
      label = owner.label,
      name  = owner \@ "name",
      text  = owner.text.trim,
      zip   = zip \@ "code"
    )
  }

Printing the file:
owners.foreach(println)

Outputs:

    Owner(owner,Harold,,57701)
    Owner(owner,Bob,,57701)
    Owner(owner,Indiana Jones,,57701)
    Owner(owner,Darth Vader,,57701)
    Owner(owner,Sue,,57702)
    Owner(owner,Captain Kirk,,57702)


test proportional odds assumption of lagged variable in ordered logistic regression

Question: I want to estimate transition probabilities between different disease states called "Remission", "Mild" and "moderate/severe".
I have an unbalanced panel of 250 patients with time differences between observations of approximately 3 months.
Since the disease states have a natural order, I have estimated an ordered logit model with the polr package and included lagged dummie variables for the disease states, so that it will be possible to calculate transition probabilities between each of the states with the estimates.
The extimated model looks roughly like this:
<code>m <- polr(State_nr ~
            lag(Mod_Sev) +
            lag(Mild) +
            Other)
</code>
State_nr being an ordered factor containing the disease states, Mod_Sev and Mild being dummie variables for the specific disease states and Other being other explanatory variables such as BMI or age.
Now I want to test the proportional odds assumption.
I have used the brant package by Benjamin Schlegel, but when I run the function on m I get the following error message:
<code>> brant(m)
Error in lag(Mod_Sev) : object 'Mod_Sev' not found
</code>
I suppose the problem is that the package cannot handle the lag operator.
Does anyone know a simple way to test the assumption when one or more of the explanatory variables are lagged?
Answer: In the end I created two new variables for lag(Mod_Sev) and lag(Mild) so that I did not need to use the lag() operator in the regression formula.


Estimate the difference between her February and her December spending

Question:
my try for part 1:
water for February =20
water for December =20
water difference spending = 20 -20 =0
gas for February =45
gas for December =35
gas difference spending = 45 -35 =10
electricity for February =29
electricity for December =30
electricity difference spending = 30 -29 =1
is that correct ??
and about part 2 , I don't understand it and need help
Answer: Your calculations for water and gas look correct. However, you say the electricity expense for February was $29$ and for December was $30$. To my eyes, February's gas mark seems to be on the same horizontal line as December's and looks to be $30$. So I would put the electricity difference as $30-30=0$.
However, you overlook that the question was for the spending difference "for all three utilities combined." You should combine the three differences by adding. Therefore the answer to the first question is $0+10+0=10$.

Part 2 asks about the basic field properties. The ones used in your problem are:
a) replacing $8(n+5)$ with $8\cdot n+8\cdot 5$. This is the distributive property of multiplication over addition.
b) replacing $8n+40$ with $40+8n$. This is the commutative property of addition.
c) replacing $15+(40+8n)$ with $(15+40)+8n$. This is the associative property of addition.
d) replacing $55+17n$ with $17n+55$. This is the commutative property of addition again.


Bach Invention 2 Bar 13 overlapping keys for both hands while playing mordent

Question: I know there are related previous discussions (I had asked one here, which , interestingly, was also a Bar "13"), but they concerned one individual key overlap. In this case, left hand plays a mordent, and the D and Eb are overlapped more than once. How to play it? I'm attaching the urtext and also one that spells out the mordent.
Comment: Note, Bach's "inventions" aren't specifically written "for piano"; they aren't even *strictly* written for keyboard; they're just 2-part counterpoint. Granted, he probably *was* thinking primarily of keyboard, and I'm guessing, of single-manual at that. But many harpsichords and organs could play this with the left hand on a different manual, and thus a different voice or register.
Comment: @AndyBonner the pieces are from the _Clavier-Büchlein vor Wilhelm Friedemann Bach._  They're definitely keyboard pieces.  This passage suggests very strongly that this one is intended for a double manual instrument.  Why would you guess that he was thinking of a single manual?  He had five harpsichords when he died, surely there was one with two manuals for his son to practice on 30 years earlier,
Answer: To get one thing straight: What you are talking about is not a mordent but a trill, which basically means:

Then when Bach wrote this instruments (like big Harpsichords) often had two manuals. The reason for this is to allow for some tonal differentiation. On a big harpsichord one can get two manuals which allows to pluck the strings in different positions for different sound as well as using different sets of strings with different length (with one set sounding an octave above).
As a result of this crossing parts can be much easier on a two manual harpsichord than on a modern piano, as each hand has its own manual.
But if you only have one manual you need stop sounding notes for new notes which then just requires the right articulation and timing (and on a modern piano touch) to convey the melody.
So you'd need to do something like
Answer: I own the Alfred edition of the Inventions, and it has notes on bar 13...

The embellishment is a trill not a mordant.
Alfred solves the "problem" with parenthesis around the R.H. Eb4 to show it will not be played literally, as the L.H. will play it on the down beat. After that initial Eb4 in the L.H. the rest of the notes for the two hands do not form unisons.
Alfred adds this footnote:

Consecutive unisons result from beginning the trill on the upper note, but the performance of the ornament as a Schneller does not solve the problem (if indeed there is a problem other than the fact that the composition was written to be played on an instrument with two manuals.) The realization shown here is possible. The Schneller is impossible to perform in this measure.

The Schneller is explained in the introduction to the edition, and is basically an upside down mordant, an embellishment using the upper neighbor tone.
Answer: Just play the ornament. The repetition of the Eb won't interrupt the overall melodic flow of the upper voice.
The other repetitions — the Ds at the end of beat 2, the RH Eb on the "and" of 3, and the Cs at the end of beat 3 — can all be played as written, with LH first and RH following.
As one example of many, here is Glenn Gould's recording (timed to m. 13). It can be clearly heard that he plays the ornament, but there's no felt interruption in either voice.

The same can be heard in Andras Schiff's recording.


Azure You don't appear to have an active Azure subscription. pipeline

Question: I signed on to a free-tier Azure subscription and am trying to create a CICD pipeline.
I go pipelines -> classic editor

Azure repo source --> docker container

but when starting to enter Azure subscription

I get the following error:

I tried references from Deploy azure subscription using azure devops pipeline, Azure Subscriptions are missing on a pipeline, You don't appear to have an active Azure subscription when creating new Kubernetes service connection in Azure DevOps, and Error when creating a pipeline. "You don't appear to have an active Azure subscription." to no avail.
Azure's troubleshoot https://learn.microsoft.com/en-us/azure/devops/pipelines/release/azure-rm-endpoint?view=azure-devops also gave me the same error, You don't appear to have an active Azure subscription.
Can anyone suggest what I might be missing?
Comment: That does not unfortunately help either @pravallika KV
Comment: Check if the troubleshooting steps provided in this [document](https://blog.georgekosmidis.net/troubleshooting-you-dont-appear-to-have-an-active-azure-subscription.html) helps to fix the issue.
Answer: I have faced the same issue when trying to reproduce the issue. As an alternative way, I have configured the container service connection as below.
Go to Azure container registry and enable admin in Access keys and make a note of the username, password and login server.

Next, in azure devops, docker task, select the latest version (2) and fill in the required details as shown in the screenshot.

In the above screenshot, the docker registry is the ACR login server name and the docker ID is the ACR username.
Save and run the pipeline.
Comment: I got the following error `The pipeline is not valid. Job Job_1: Step  input containerRegistry references service connection undefined which could not be found. The service connection does not exist or has not been authorized for use. For authorization details, refer to https://aka.ms/yamlauthz.` while trying your suggestion
Answer: Thank you for suggestions, but I checked again today, and my Azure subscription populated the correct space.
Only thing I did was contact Azure and set up a meeting (which they did not show up for).

Azure You don’t appear to have an active Azure subscription. pipeline


Unlimitted entries in Watchdog table

Question: I need to set watchdog log entries to unlimitted. Now it clears every time when cron is called.
admin/settings/logging/dblog

now maximum is 100000, is there any better way to do this.
Answer: Just change the setting to "ALL" that should work. Please see the screen below !

Cron will run only if minimum limit is set in the select box see the below code in dblog module.
function dblog_cron() {
  // Cleanup the watchdog table.
  $row_limit = variable_get('dblog_row_limit', 1000);

  // For row limit n, get the wid of the nth row in descending wid order.
  // Counting the most recent n rows avoids issues with wid number sequences,
  // e.g. auto_increment value > 1 or rows deleted directly from the table.
  if ($row_limit > 0) {
    $min_row = db_select('watchdog', 'w')
      ->fields('w', array('wid'))
      ->orderBy('wid', 'DESC')
      ->range($row_limit - 1, 1)
      ->execute()->fetchField();

    // Delete all table entries older than the nth row, if nth row was found.
    if ($min_row) {
      db_delete('watchdog')
        ->condition('wid', $min_row, '<')
        ->execute();
    }
  }
}

If we select value as "ALL" which is 0, Cron won't delete any entries !
For Drupal 6,
You can use Elysia Cron module, to turn off the dblog_cron feature.
Elysia Cron Module tells,

Turn off (disable) a cron task/feature you don't need.
Comment: Updated solution for D6 :-)
Answer: Never flushing your Watchdog log via CRON or at least manually clearing the log every so often will eventually cause you problems.  If you are on a dedicated or virtual Linux host consider using Syslog instead of Watchdog for your Drupal logging (available in both Drupal 6 and 7.)
This will allow you to keep an unlimited and permanent log of your Drupal events.  The setup guide also shows you how to use logrotate so log files don't get out of hand.
This will likely have a huge impact on performance as well. This is due to being able to prevent the excessive DB writes that Watchdog initiates.
Excerpt from Drupal.org regarding the Syslog module

Install & configure the Syslog module
Go to the Modules page, /admin/build/modules, and install the Syslog
  module. Then go to the Syslog settings page,
  /admin/settings/logging/syslog (D6) or the Logging and errors
  configuratiion page, admin/config/development/logging (D7), and select
  which Syslog level to attach to the log messages. Choose one that is
  not in use by Syslog
Configure Syslog to Log to a Separate File
Edit /etc/syslog.conf and add:
local0.* /var/log/drupal.log

(if local0 is the level that you configured Syslog to use in Step 1)
Then, restart Syslog:
service syslog restart

Note that this is optional. If you do not do this, your messages will
  most likely be in /var/log/messages.
Disable the Database Logging (formerly, Watchdog) Module
Check that you are seeing messages in the syslog by using
tail /var/log/drupal.log

You can also browse the file by using less.
If it is working, you may now go to the modules page and disable
  Dblog.

For complete entry, visit Syslog: OS-integrated logging
Comment: If you are going to use dblog (aka can't use syslog due to a shared environment or other BS), what do you think is a reasonable upper boundary for number of log entries?

Unlimitted entries in Watchdog table


Find the asymptotes to the hyperbola $3x^2+2xy-y^2+8x+10y+14=0$

Question:
The hyperbola is given with the following equation: $$3x^2+2xy-y^2+8x+10y+14=0$$
  Find the asymptotes of this hyperbola. ($\textit{Answer: }$ $6x-2y+5=0$ and $2x+2y-1=0$)

In my book, it is said that if the hyperbola is given with the equation:
$$Ax^2+2Bxy+Cy^2+2Dx+2Ey+F=0$$ then the direction vector $\{l,m\}$ of the asymptotes are found from the following equation: $$Al^2+2Blm+Cm^2=0$$ (Actually, I don't know the proof) Then to solve this, we let $k=\frac{l}{m}, \ \  (m \not =0)$ and solve the quadratic equation for $k$: $$Ak^2+2Bk+C=0, \text{ in our case } 3k^2+2k-1 = 0$$
From here, I got $k=-1 \text{ or } k=\frac{1}{3}$ (which give us slopes of the two asymptotes).
Hence we search for the asymptotes of the form $y=kx+b$ and restrict $b$ in such way so that the line does not intersect the line. Plugging this $y$ and $k=-1$ into the equation of the parabola I got: $$(4b-2)x-b^2+10b+14=0$$
so $b=\frac{1}{2}$ (as the equation should not have a solution). Then, $y=-x+\frac{1}{2}$ or $2x+2y-1=0$ as in the answer!
However, I could not find the second one in this way...
Then, I got stuck...
It would be greatly appreciated either if you help me understand (why the asymptotes are to be found so) and complete this solution or suggest another solution.
Comment: Isn't there a typo? I have found the first asymptote $6x-2y+19=0.$
Comment: Not necessarily. The other asymptote of the equation that you wrote is vertical. It might be _any_ other non-horizontal line, though.
Comment: Just search for asymptote in https://archive.org/details/elementsofcoordi00loneuoft
Comment: In maxima CAS `eq1:3*x^2+2*x*y-y^2+8*x+10*y+14;` `solve([diff(eq1,x),diff(eq1,y)],[x,y]);` `[[x = -9/4,y = 11/4]]` `factor((-y^2)+2*x*y+10*y+3*x^2+8*x+14-((-(11/4)^2)+2*(-9/4)*(11/4)+10*(11/4)+3*(-9/4)^2+8*(-9/4)+14));` `-((2*y-6*x-19)*(2*y+2*x-1))/4`
Comment: @user376343  But I'm sure that I copied it right from the book, then there seems to be a typo in the book
Comment: Be aware that requiring $m\ne0$ misses horizontal asymptotes, but you'll know that's a possibility if you only get a single value for $k$.
Comment: @amd the presence of a horizontal asymptote will be quite obvious right?.....the hyperbola will be of the form $(x-a)(y-b)=k$.....correct me if i'm wrong
Comment: @amd I see...thanks for clarification
Answer: To justify the approach, note that asymptotically the quadratic terms of the curve
$f(x,y)=3x^2+2xy-y^2+8x+10y+14$ dominate, i.e.
$$3x^2+2xy-y^2=(3x-y)(x+y)=0$$
which corresponds to the asymptotic behaviors of the asymptotes and yields their slopes $3,\> -1$.
To obtain the actual equations of the two asymptotes, let $f'_x= f'_y=0$ to determine the center, i.e.
$$ 6x+2y+8=0,\>\>\>\>\>2x-2y+10=0$$
Solve to get the center $(-\frac94, \frac{11}4)$. Then, use the point-slope formula for the equations
$$y-\frac{11}4=-(x+\frac94),\>\>\>\>\> y-\frac{11}4=3(x+\frac94)$$
Comment: I got the clue, thanks! So, I now take these slopes $k$ and then search for the asymptotes of the form $y=kx+b$. Then, restrict $b$ in such way so that this line does not intersect the hyperbola. Am I right?
Comment: @VIVID - Please see the edit
Answer: Here is a view I have on hyperbola's asymptotes :
The asymptotes and the hyperbola behave the same way as we go to a point $(x,y)$ at an infinite distance from the centre of hyperbola, along the asymptotes.
So for a hyperbola: $H:ax^2+by^2+2hxy+2gx+2fy+c=0$, the terms containing $x$ and $y$ will affect the behaviour at such a point. Since the two(equation of hyperbola and the pair of asymptotes) have same behaviour (and hence same value of power of point), the only thing that differs in the two equations is the constant term.
So the equation of pair of asymptotes will be of the form: $A=ax^2+by^2+2hxy+2gx+2fy+d=0$
Now you can find the equation of asymptotes by using the fact that the centre of hyperbola passes lies on the asymptotes.
The centre can easily be found by solving: $\frac{\delta H}{\delta x}=0$ and $\frac{\delta H}{\delta y}=0$ .
So this point (Say $(x_o,y_o)$) will satisfy $A=0$
Find $d$ by putting the point in the equation.
For eg. in the hyperbola in your question:
The centre is $(-9/4,11/4)$ .
So if the equation of asymptotes is : $3x^2+2xy-y^2+8x+10y+\lambda=0$
To find $\lambda$ put the centre into the equation
$$\frac{243}{16}-\frac{99}{8} -\frac{121}{16}-18+\frac{55}{2}+\lambda=0$$
$$\lambda=\frac{19}{4}$$
So factorise the equation for asymptotes to get asymptotes.
$$(6x-2y+19)(2x+2y-1)=0$$
Answer: You say that you got stuck when trying $k=\frac13$. That's likely because that's not the slope of either asymptote. If a line has direction vector $(l,m)$, then its slope is equal to $\frac ml$, not $\frac lm$. So, what you found by solving $3k^2+2k-1=0$ was the reciprocals of the slopes. You can, of course, get the slopes directly using your method, but the equation to be solved is instead  $A+2Bk+Ck^2=0$.
The reciprocal of $-1$ is $-1$ again, so your method of adjusting $b$ so that there is no intersection worked accidentally. On the other hand, there is an infinite number of lines with slope $\frac13$ that don't intersect this hyperbola, and that's why you didn't get a definitive result for that. Using the correct slope value of $3$, we end up with $(38-4b)x=b^2-10b-14$, and setting $b=\frac{19}2$ guarantees no intersection with the hyperbola.
There's another method of finding the constant terms for the asymptotes that may or may not be easier to use. If you vary $F$ in the general equation, you get a family of hyperbolas with common asymptotes. For some value of $F$ the hyperbola degenerates into intersecting lines—the asymptotes themselves. Now, a joint equation of the asymptotes is $$(k_1x-y+b_1)(k_2x-y+b_2)=0.$$ Per the preceding observation, if you expand this expression, the coefficients of all but the constant term must be proportional to the corresponding coefficients in the original hyperbola equation. Comparing coefficients will result in a simple system of equations to solve for $b_1$ and $b_2$. (Indeed, when the quadratic part of the conic equation factors easily, as it does in this problem, you can go straight to comparing coefficients without going through solving the work of solving a quadratic equation.)
In this problem, we have $$(-x-y+b_1)(3x-y+b_2) = -3x^2-2xy+y^2+(3b_1-b_2)x-(b_1+b_2)y+b_1b_2.$$ Comparing this to the original system gives $$3b_1-b_2=-8 \\ b_1+b_2=10.$$ I trust that you can solve this system.
As for why you can find the direction vectors of the asymptotes by considering only the quadratic part of the equation, I'll offer a projective-geometric explanation. A hyperbola intersects the line at infinity at two points; its asymptotes are the tangents to the hyperbola at those points. On the other hand, the point at infinity on a line corresponds to its direction vector. We can find these intersection points by homogenizing the equation to $$Ax^2+2Bxy+Cy^2+2Dxw+2Eyw+Fw^2=0$$ and then setting $w=0$.
Another way to understand this method of finding the asymptote slopes is to translate the hyperbola so that its center is at the origin. This doesn't affect any of the second-degree terms, so the resulting equation is of the form $Ax^2+2Bxy+Cy^2=F'$. Per the earlier discussion, varying the constant term on the right-hand side produces a hyperbola with the same asymptotes, and it should be fairly obvious that at $F'=0$ you get intersecting lines. Since these lines both pass through the origin, the coordinates of any point on one of these lines also give a direction vector of that line.
Comment: Thank you for the detailed explanation :)
Answer: Just what I thought, asymptotes for quadratic curve can be reformatted as the ratio of $y/x$ approach to a constant as $x$ goes up.
as pointed out by other the slope of asymptotes is $\frac{m}{l}$, let $y = \frac{m}{l} x + b$, so
$$ \lim _{x \to \infty} \frac{y}{x} = \frac{m}{l} $$
as well as
$$ 0 = \lim _{x \to \infty} A + 2B \frac{y}{x} + C (\frac{y}{x})^2 + \frac{2D}{x} + \frac{2Ey}{x^2} + \frac{F}{x^2} = A + 2B\frac{m}{l} + C(\frac{m}{l})^2$$
Naturally yield what you want.


How to run email/sms in landscape iPhone app?

Question: I have an iPhone app, which is running only in landscape mode, but recently I wanted to add mail/sms/facebook features (via UIButton actions). The last one is running smoothly, I launch web browser (itself manages portrait mode), but starting mail or sms composer is driving me mad.
I Just want to use this app only in landscape mode, excluding launching mail/sms/fb (browser actually).
I managed to have mail/sms composer in portrait mode when having app screen in landscape, but keyboard appears in landscape too, which is blocking the left/right half of composer - did it with <code>[composer setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];</code>
either I'm reading bad stuff on this topic or I'm simply blind ;) - either way any help needed, thanks
EDIT:
I have a root ViewController with overridden:
<code>- (BOOL)shouldAutorotateToInterfaceOrientation
</code>
which is returning YES in both landscape modes. This rootVC is firing up ShareVC which has 3 buttons for mail/sms/fb. I wish to acheive something like firing up web browser, which starts in portrait. The same with mail & sms, but using modal view controllers and then returning to ShareVC after sending mail/sms...
I also set orientations in plist to landscape modes. Hope this clarify what I am trying to do :)
Comment: ok, if someone knows how to launch mail/sms composers in landscape mode within landscape app - that would be also satisfactory
Answer: Try adding this to the desired ViewController:
<code>- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
  return interfaceOrientation==UIInterfaceOrientationLandscapeLeft;
}
</code>
I don't have a Mac nearby, so there might be error(s).
hope it helps
Comment: but you mean with the snippet I mentioned? or just fire up MFComposers as always with overridden shouldAutoRotate?
Comment: Just copypaste this code to the view controller. It's a default method. So when a user will turn a device it will turn too, but only to a landscape.
Comment: yeah, but when you use landscape app you are not expecting suddenly to change orientation, and I suppose problem is in firing up MFComposers in landscape :/ I will add some additional info in edit in a sec
Answer: Problem fixed :)
turned out I was calling present/dismiss modalViewController on a childVC not on rootVC itself, here is code snippet:
<code>-(IBAction)goMail{
    NSLog(@"gomail...");
    MFMailComposeViewController *picker = [[[MFMailComposeViewController alloc] init] autorelease];
    NSUserDefaults *settings = [NSUserDefaults standardUserDefaults];

    if ([MFMailComposeViewController canSendMail]) {
        picker.mailComposeDelegate = self;
        [picker setSubject:@"Hello iPhone!"];

        // Set up recipients
        NSArray *toRecipients = [NSArray arrayWithObject:@"firstname.lastname@example.com"];
        [picker setToRecipients:toRecipients];
        [picker setMessageBody:@"mail content..." isHTML:NO];
        [self.controller presentModalViewController:picker animated:YES];
        //[picker release];
    }
}
</code>
Comment: here  is where I've found [solution](http://www.iphonedevsdk.com/forum/iphone-sdk-development/76670-getting-modal-view-controller-display-landscape-orientation.html)


Como substituir o seletor * em produção

Question: Então, ao usar o seletor * para fazer o reset do margin|padding geral do HTML o CSSLint aponta que em produção pode dar gargalo para o usuário.
*{
   margin:0;
   padding:0;
 }

Para mim a "solução" que me vem é:
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
    margin: 0;
    padding: 0;
}

Mas, não é basicamente a mesma coisa? Eu realmente não sei porque, mas dessa maneira o CSS Lint não aponta possíveis problemas de performance. Existe alguma função para fazer isso? ou maneira melhor? Agradeço.
Answer: Seletores universais como *, [disabled], [type="text"], etc. são muito caros para o navegador para corresponder, como cada elemento no DOM deve ser verificada.
O seletor universal é usado frequentemente para box-sizing e outros globals. No entanto, muitas vezes isso pode ser otimizado pelo agrupamento de elementos relevantes. Veja solução de dimensionamento.
    html, body, div, article, section, main, footer, header, form, fieldset, legend,
    pre, code, p, a, h1, h2, h3, h4, h5, h6, ul, ol, li, dl, dt, dd, textarea,
    input[type="email"], input[type="number"], input[type="password"],
    input[type="tel"], input[type="text"], input[type="url"], .border-box {
    box-sizing: border-box;
}

Veja mais aqui https://github.com/tachyons-css/tachyons-box-sizing

Como substituir o seletor * em produção


the article can't show the image in the full mode in drupal 7

Question: my article can't show images in the full view but only in the teaser view, even go to the article content type setting, in the full mode, it is fine that I allow to show the image.
any idea why?
Answer: Make sure to set the display on the content type (manage display link) as it ultimately sets the values of the teaser and full node.


disable the keyboard on textbox tap on windows phone

Question: okay, so i am now very frustrated about this topic on google, because no one asks the right questions.
i have a textbox on my windows phone 8 applications right.
now once i click on that textbox the SIP keyboard pops up(that part i get, it is done by the OS).
now what i want to do is once i click on the textbox i dont want the SIP to open up , cause it will navigate to a another page, but i cant make it a button cause the user can edit the info in the textbox once they chose the data from the other page.
now is there a property on windows phone textboxes that will restrict the keyboard from popping up?
and i cant make it read-only because that will not look good, and then the user will see the textbox as uneditable.
any links, code , or previous questions will be appreciated!
EDIT: I have also tried setting focus on some other control, but it doesn't happen fast enough so keyboard also pops up!,
I have no physical controls, my controls are all dynamic, depends on what is sent through
the webservice:
Here is a sample! :
<code> else if (field.CtlType == WFCoreLib.DataModels.Generic.FieldAttributes.ControlType.ctFinder)
                        {
                            TextBox txtFindercontent = new TextBox();
                            txtFindercontent.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
                            //txtFindercontent.Text = field.FieldDescLoc.ToString();
                            txtFindercontent.SetValue(Grid.ColumnProperty, 1);
                            txtFindercontent.SetValue(Grid.RowProperty, count);
                            txtFindercontent.Width = 220;
                            txtFindercontent.FontSize = 20;
                            txtFindercontent.TextWrapping = TextWrapping.Wrap;
                            txtFindercontent.IsHitTestVisible = true;
                            //txtFindercontent.LostFocus += txtcontent_LostFocus;
                            txtFindercontent.Name = "fndDescription" + count.ToString();
                            txtFindercontent.Tag = field.MaxValue + "," + field.FieldDescLoc + "," + field.IsRequired + "," + count + "," + blockindex + "," + field.FieldID + "," + field.ColumnName + "," + field.FieldCode;
                            txtFindercontent.GotFocus += txtFindercontent_GotFocus;

                            if (field.FieldType == WFCoreLib.DataModels.Generic.FieldAttributes.DataType.dtInteger || field.FieldType == WFCoreLib.DataModels.Generic.FieldAttributes.DataType.dtDouble)
                            {
                                InputScope scope = new InputScope();
                                InputScopeName name = new InputScopeName();

                                name.NameValue = InputScopeNameValue.Number;
                                scope.Names.Add(name);

                                txtFindercontent.InputScope = scope;
                            }
</code>
PS: The Apple/iPhone textbox has a property that restricts the keyboard. i hope WP8 has one aswell
Regards
Comment: Why not style the button to look like a textbox then?
Comment: Sounds to me like you want a button, with its text property bound to a property on your view-model?
Comment: well basically, yes. but our app needs to look the same on all platforms, so i must use a textbox, and this is frustrating me, cause it looks weird, as soon as i click on the control the keyboard pops up for a sec then it navigates. i so badly want to use a button, but cant
Comment: Can't you apply a custom style for your read-only so it looks ok? I have developed an app which does exactly what you want to do. Our TextBox is read-only and we bind the navigation to the Tap event of the textbox.
Answer: I think you can achieve this by a simple logic. So what you want to do is, Create a transparent button using expression blend. Place that button above your textbox. Bind the ZIndex property of your button. Whenever you navigates to the page check your text box contains any values. If yes set the ZIndex of button to move behind the TextBox. If the condition is wrong do the reverse. I think this will solve your issue.
Comment: i see where you going with this, but i have no physical contorls? all my controls are added dynamically, we have a very customizable workflow, that we put on a mobile device?, prob should have stated that in my question.
Comment: Editied my question again :)


Is the realm of sets belonging to weakly reachable from below stages of the cumulative heirarchy a model of ZF?

Question: I want to know how high is the universe of sets in ZFC as seen from below.
We say that a stage $V_\alpha$ of the cumulative hierarchy is reachable from below if and only if $\alpha$ is isomorphic to an ordering on a set that belongs to a prior stage. Formally:
$\text{reachable} (V_\alpha) \iff \exists S \in V_\alpha \exists f \exists \mathcal R \\ [ f: \alpha \hookrightarrow S  \land \forall \beta,\gamma \in \alpha \ (\beta < \gamma \Leftrightarrow f(\beta) \ \mathcal R \ f(\gamma) )]$
Now we define hierarchical gap as a nonempty stage of the hierarchy that is not reachable from below.
Define: $\text{weakly-reachable} (V_\alpha) \iff |\{ V_{\beta <\alpha}| V_\beta \text { is hierarchical gap } \}| < |V_\alpha|$
A stage is hereditarily weakly-reachable from below if it and every stage prior to it is weakly-reachable from below.

Does the realm of all sets beloning to hereditarily weakly-reachable from below stages constitute a model of ZF? Or ZF can prove the existence of a non weakly-reachable stage from below?

If we redefine weak reachability as:
$\text{weakly reachable} (V_\alpha) \iff |\{ V_{\beta <\alpha}| V_\beta \text { is hierarchical gap } \}| < |\alpha| $

Can ZF prove existence of a non weakly reachable stage?
Comment: I don't understand the definition of reachable. If $f$ is a bijection from $X$ to $Y$, then every relation on $X$ can be translated to a relation on $Y$. All you say is that $|S|=|\alpha|$. So unreachable is simply $V_\alpha$ when $\alpha$ is not smaller than any $x\in V_\alpha$. These are exactly the fixed points of the strong limit cardinals.
Answer: $\mathsf{ZF}$ proves that there are lots of non weakly reachable stages, even according to the stronger definition. In fact, $\mathsf{ZF}$ proves that the class of indices of such stages is a club.

The key point is that the indices of levels of $V$ which are not reachable from below form a club (this is easiest to see if we use a simpler definition of reachability: $V_\alpha$ is reachable from below iff $\alpha$ is in bijection with some $S\in V_\alpha$). To see this, think about iterating the function $$\xi\mapsto\sup\{\aleph^*(V_\zeta): \zeta<\xi\}.$$
Now $\mathsf{ZF}$ proves$^*$ that, given any club $C$, there is some ordinal $\theta\in C$ such that $\theta\cap C$ has ordertype $\theta$; this is a standard exercise. Applying this to the club of indices of non-reachable-from-below levels of $V$ gives the desired result for the second sense of weak reachability; for the first sense, just consider the intersection of $C$ with the club of ordinals satisfying $\vert\alpha\vert=\vert V_\alpha\vert$.
And in fact this really shows that $\mathsf{ZF}$ proves that there is a club of such ordinals.

$^*$Strictly speaking, $\mathsf{ZF}$ proves a theorem scheme: for each formula $\varphi$, $\mathsf{ZF}$ proves "If $\varphi$ defines a club of ordinals, then there is some ordinal $\theta$ such that $\varphi(\theta)$ and the set of ordinals $<\theta$ satisfying $\varphi$ has ordertype $\theta$."
Comment: What's the fixed point if $V_\xi$ is not well-ordered? You want to actually map $\xi$ to the Lindenbaum of $V_\xi$, and then take a limit. Or if you want to be *continuous*, which you seem to want (for a good reason), just take $\xi\mapsto\sup\{\aleph^*(V_\zeta)\mid\zeta<\xi\}$ instead.
Comment: @AsafKaragila Whoops, fixed!
Comment: what is the ordinal index of the smallest non weakly-reachable stage in ZF called?


Proving that $\lim_{x \to 0} \frac{f(x)}{|x|}=1$ implies $f$ is not differentiable at $0$.

Question: $$\lim_{x \to 0} \frac{f(x)}{|x|}=1$$ Then prove that $f$ is not differentiable at $0$.
I was given this assignment and I'm not sure about my proof.. it feels like I'm assuming too much and not explaining with enough detail. Is there anything I need to add to make it sufficient?
Assume toward contradiction that $f$ is differentiable at $0$.
Then by definition we know that $f$ is continuous at $0$. Therefore
$\lim _{x\to 0}f\left(x\right)=f\left(0\right)$
We know that
$\lim _{x\to 0}\frac{\left(f\left(x\right)\right)}{\left|x\right|}=1$
Therefore we can conclude
$\lim _{x\to 0}\frac{\left(f\left(x\right)\right)}{\left|x\right|}\cdot \left|x\right|=1\cdot 0=0$
But we can also rewrite this as
$\lim _{x\to 0}\left(f\left(x\right)\right)\cdot \frac{\left|x\right|}{\left|x\right|}=f\left(0\right)\cdot 1=0$
Therefore $f(0) = 0$.
Since $f$ is differentiable at $0$ we have
$\lim _{x\to 0}\frac{\left(f\left(x\right)-f\left(0\right)\right)}{x-0}=\lim _{x\to 0}\frac{\left(f\left(x\right)-0\right)}{x}=\lim \:_{x\to \:0}\frac{\left(f\left(x\right)\right)}{x}\cdot \frac{\left|x\right|}{\left|x\right|}=\lim \:\:_{x\to 0}\frac{\left(f\left(x\right)\right)}{\left|x\right|}\cdot \:\frac{\left|x\right|}{x}$
Since the one sided limits of $\frac{f\left(x\right)}{\left|x\right|}$ exist, and are both equal to 1, we have
$\lim \:_{x\to 0^+}\frac{\left(f\left(x\right)\right)}{\left|x\right|}\cdot \:\:\frac{\left|x\right|}{x}=\lim \:_{x\to \:0^+}\frac{\left(f\left(x\right)\right)}{x}\cdot \:\:\:\frac{x}{x}=1\cdot 1=1$
$\lim \:_{x\to 0^-}\frac{\left(f\left(x\right)\right)}{\left|x\right|}\cdot \:\:\frac{\left|x\right|}{x}=\lim \:_{x\to \:0^-}\frac{\left(f\left(x\right)\right)}{-x}\cdot \:\:\:\frac{-x}{x}=1\cdot -1=-1$
Since the limit doesn't exist, we have a contradiction to the fact $f$ is differentiable at $0$.
Therefore $f$ is not differentiable at 0.
Comment: Nee nor nee nor spelling police here. Please change all your "differential"s to *differentiable*.
Comment: Please do [not use pictures for critical portions](//math.meta.stackexchange.com/a/20529/290189) of your post. Pictures may not be legible, cannot be searched and are not viewable to some, such as those who use screen readers. [Scanned pages from books are discouraged on SE network](//meta.stackexchange.com/q/155600/259305). Questions should contain sufficient context so that it is [answerable with the text alone](//math.meta.stackexchange.com/a/1807/290189).
Comment: Please use more specific, informative titles, like the one I have supplied. "Proof regarding differentiable functions" is very vague and generic.
Answer: Your proof looks almost perfect to me. There's a couple of minor things I would change in the last few lines. You wrote:

Since the one sided limits of $\frac{f\left(x\right)}{\left|x\right|}$
exist, and are both equal to 1, we have
$\lim \:_{x\to
 0^+}\frac{\left(f\left(x\right)\right)}{\left|x\right|}\cdot
 \:\:\frac{\left|x\right|}{x}=\lim \:_{x\to
 \:0^+}\frac{\left(f\left(x\right)\right)}{x}\cdot
 \:\:\:\frac{x}{x}=1\cdot 1=1$
$\lim \:_{x\to
 0^-}\frac{\left(f\left(x\right)\right)}{\left|x\right|}\cdot
 \:\:\frac{\left|x\right|}{x}=\lim \:_{x\to
 \:0^-}\frac{\left(f\left(x\right)\right)}{-x}\cdot
 \:\:\:\frac{-x}{x}=1\cdot -1=-1$
Since the limit doesn't exist, we have a contradiction to the fact $f$
is differential at $0$.
Therefore $f$ is not differential at 0.

I don't see the need to remove the absolute value signs in the following places in red:
$f'(0)= \lim _{x\to 0}\frac{\left(f\left(x\right)-f\left(0\right)\right)}{x-0} = \lim \:_{x\to 0^+}\frac{\left(f\left(x\right)\right)}{\left|x\right|}\cdot \:\:\frac{\left|x\right|}{x}=\lim \:_{x\to \:0^+}\frac{\left(f\left(x\right)\right)}{\color{red}{|}x\color{red}{|}}\cdot \:\:\:\frac{x}{x}=1\cdot 1=1$, but
$f'(0) =\lim _{x\to 0}\frac{\left(f\left(x\right)-f\left(0\right)\right)}{x-0} =  \lim \:_{x\to 0^-}\frac{\left(f\left(x\right)\right)}{\left|x\right|}\cdot \:\:\frac{\left|x\right|}{x}=\lim \:_{x\to \:0^-}\frac{\left(f\left(x\right)\right)}{ \color{red}{|}x\color{red}{|}} \cdot \:\:\:\frac{-x}{x}=1\cdot -1=-1$
Since $\lim \:_{x\to 0}\frac{\left(f\left(x\right)\right)}{\left|x\right|}$ only exists if both
$\lim \:_{x\to 0^+}\frac{\left(f\left(x\right)\right)}{\left|x\right|}$ and $\lim \:_{x\to 0^-}\frac{\left(f\left(x\right)\right)}{\left|x\right|}$
exist and are equal - which they aren't - we have a contradiction to the fact $f$ is differentiable at $0$.
Therefore $f$ is not differentiable at $0$.
Comment: Just because you changed $\frac{\left|x\right|}{x}$ to $\frac{x}{x}$ does not mean you are obliged to change $\frac{\left(f\left(x\right)\right)}{\left|x\right|}$ to $\frac{\left(f\left(x\right)\right)}{x}$.
Comment: Thanks for the response! At the beginning I thought about leaving the absolute value, but since I replaced the absolute value in the other expression I felt that I'm obliged to also do it in the main expression.. I thought it was the correct thing to do
Answer: You are right. Assuming $f$ is differentiable at $x=0$ and since $f\sim \lvert x\rvert$ in a neigborhood of $0$, necessarily $f(0)=0$. Then taking the derivatives from both sides, you get the contradiction.


Performance issue while groupby.shift

Question: Test code:
SIZE_MULT = 5
data = np.random.randint(0, 255, size=10**SIZE_MULT, dtype='uint8')
index = pd.MultiIndex.from_product(
            [list(range(10**(SIZE_MULT-1))), list('ABCDEFGHIJ')],
            names = ['d', 'l'])
test = pd.DataFrame(data, index, columns = ['data'])
test.head()
test['data'].dtype

Output:
        data
d   l
0   A   137
    B   156
    C   48
    D   186
    E   170

dtype('uint8')

And suppose we want group by 0-level of index and shift each group (shift step = 2, for example).
%%time
shifted = test.groupby(axis=0, level=[0]).shift(2)
print(shifted['data'].dtype)

Output:
float64
CPU times: user 9.43 ms, sys: 56 µs, total: 9.49 ms
Wall time: 8.29 ms

Now to the problem: if we want to preserve our dtype 'uint8', we have to get rid of Nones, and set our fill value with 0, for example. But we will get HUGE time of code execution now:
%%time
shifted = test.groupby(axis=0, level=[0]).shift(2, fill_value = 0)
shifted.head()
print(shifted['data'].dtype)

Output:
uint8
CPU times: user 5.9 s, sys: 38.4 ms, total: 5.94 s
Wall time: 5.89 s

So the question is why this is so long? If we take 1st shifted dataframe without fill_value, and add few code lines to achieve same result:
%%time
shifted = test.groupby(axis=0, level=[0]).shift(2)
shifted.fillna(0, inplace=True)
shifted = shifted.astype(np.uint8)
print(shifted['data'].dtype)

Output:
uint8
CPU times: user 9.64 ms, sys: 3.68 ms, total: 13.3 ms
Wall time: 11.3 ms

It will add only few ms, not 5 seconds.
EDIT: corresponding github issue
Answer: From the source code the issue is that with a fill value specified it uses a slow apply call. Without a fill value, it's able to use the much faster cythonized result:
Code from the link:
def shift(self, periods=1, freq=None, axis=0, fill_value=None):
    #...
    if freq is not None or axis != 0 or not isna(fill_value):
        return self.apply(lambda x: x.shift(periods, freq,
                                            axis, fill_value))

    return self._get_cythonized_result('group_shift_indexer',
                                       self.grouper, cython_dtype=np.int64,
                                       needs_ngroups=True,
                                       result_is_index=True,
                                       periods=periods)

So in this case, I would use .fillna() after.

Performance issue while groupby.shift


ORMLite and Other ORM Options for Android

Question: Been looking for an ORM for Android. Personally I think its a setback these days for an SDK not to have an ORM. In this aspect iOS SKD is ahead.
I came across ORMLite, which looks quite simple to use.
My concern is compatibility w/ various SDK levels in Android (have a requirement to stay reverse compatible down to 2.2 SDK LEVEL 9)
Any other ORMs I  should consider?
Any pitfalls I should watch out for?
Answer: I would suggest ORMlite its open source freeware.
It has good developer support & many application running on ORMlite.
another is greenDao library. Its very easy to use. Here is a comparison
Answer: ORMLite is great. You are able to do necessary database operations without writing sql. ORMLite works with older android versions such as gingerbread so I wouldn't be concerned about that.
This section of the documentation will help you get going, or if you prefer a video tutorial, this one is very helpful:
https://www.youtube.com/watch?v=beb-n2yq0kM
The only drawback to it that I can think of is that it's a small community so the support and documentation is a bit sparse at times. That said, the creator (Gray) is active on Stack Overflow and he is likely to be around to help if you have more advanced issues.


How to replace usage of static Entity::load method calls for better testability?

Question: In my method that I'm testing in UnitTestCase based class I have a statement:
<code>Term::load(self::HARDCODED_TID);
</code>
Any other way to load Term object to make it 'mockable'?
Comment: Use the term storage handler.
Comment: @Eyal could you provide an example of using TermStorage directly?
Comment: `\Drupal::entityTypeManager()->getStorage('term')->load(self::HARDCODED_TID);`
Comment: The storage class can be initiated with a container object so it can be easily mocked.
Comment: \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load(self::HARDCODED_TID);
Answer: My workaround is (without changing legacy code):
<code>   $entityManager = $this->getMockBuilder('\Drupal\Core\Entity\EntityManager')
      ->disableOriginalConstructor()
      ->getMock();

    $entityManager->expects($this->any())
      ->method('getEntityTypeFromClass')
      ->will($this->returnCallback(function ($class_name) {
        return $class_name == 'Drupal\taxonomy\Entity\Term' ? 'taxonomy_term' : '';
      }));

    $term = $this->getMockBuilder('Drupal\taxonomy\Entity\Term')
      ->disableOriginalConstructor()
      ->getMock();

    $termStorage = $this->getMockBuilder('\Drupal\taxonomy\TermStorage')
      ->disableOriginalConstructor()
      ->getMock();

    $termStorage->expects($this->any())
      ->method('load')
      ->willReturn($term);

    $this->termStorage = $termStorage;

    $entityManager->expects($this->any())
      ->method('getStorage')
      ->will($this->returnCallback(function ($type) {
        return $type == 'taxonomy_term' ? $this->termStorage : NULL;
      }));

    $this->container = new ContainerBuilder();
    $this->container->set('entity.manager', $entityManager);
    \Drupal::setContainer($this->container);
</code>


How to seal an overridden property

Question: Suppose I have a pair of obviously contrived C# classes like this:
public abstract class Foo {
    public abstract int[] LegalValues { get; }
    public virtual bool IsValueLegal(int val) {
        return Array.IndexOf(LegalValues, val) >= 0;
    }
}

and this:
public class Bar : Foo {
    static int[] _legalValues = new int[] { 0, 1 }; // whatever
    public sealed override int[] LegalValues
        { get { return _legalValues; } }
    public sealed override bool IsValueLegal(int val)
        { return base.IsValueLegal(val); }
}

How do I do this in F#?  The obvious code for the properties:
[<Sealed>]
override this.LegalValues with get() = // ...

[<Sealed>]
override this.IsValueLegal value = // ...

Triggers an error because the SealedAttribute apparently can't be applied to members.
I can, of course, seal the entire class and thereby seal all members, but (and this is a really important but) is that I have a goal of matching an existing class signature exactly and the base class has other virtual/abstract members that should, ideally, remain overridable.
Comment: Hm, I did not even know that sealing individual methods was possible in C#/CLR!
Answer: Looks like F# defines the Sealed Attribute is defined with its AttributeTargets property set to Class only, its probably not possible to seal members.
This is probably ok, since inheritance and overriding functions is generally less idiomatic in F# than C#. I don't think you can really get what you want without rewriting in more F# idioms. Start with this:
type foo =
    | Bar
    | Baz
    | Qux
        with
            member this.LegalValues =
                match this with
                | Bar -> [0; 1]
                | Qux -> [-1; 0; 1]
                | Baz -> [0 .. 10 ]
            member this.IsValueLegal value =
                match this with
                | Baz -> value >= 0 && value <= 10
                | _ -> List.exists (fun x -> x = value) (this.LegalValues)

You can say that Baz "overrides" the foo.IsValueLegal member, all other types use the "base" function.
Comment: Interesting approach, but I can't use it - the base class defines a particular inheritance so I cannot redefine Foo under any circumstances and I am required in Bar to prevent someone from overriding these methods.  If I have to seal the whole class, then so be it.  While this will cut off certain operations, they could be simulated in other ways (adapters, etc).
Answer: There are currently several limitations to F#'s support for OO, so you should not generally expect to be able to produce an F# class hierarchy which is identical to an arbitrary C# class hierarchy.  As far as I know, there is no way to override and seal a virtual method.

How to seal an overridden property


probability question

Question: I would like to calculate the following conditional probability:
I know that the probability of a BLUE ball being drawn is 0.3.
I receive a message from A or B who saw the ball that has been drawn.
This person tells me that the ball drawn is BLUE.
I know the probabilities:
A observing BLUE and sending BLUE- 0.16
B observing RED and sending BLUE - 0.09
A observing BLUE and sending BLUE- 0.05
B observing RED and sending BLUE- 0.17
I also know the probabilities:
A observing BLUE and sending RED - 0.019
B observing RED and sending RED- 0.323
A observing BLUE and sending RED-0.073
B observing RED and sending RED=0.106
I would like to calculate the conditional probability of the ball drawn actually being BLUE given that I received the message BLUE and the information I know about each player's probability of sending a given message.
Comment: @Daniel Please don't destroy your question only to ask a new variant of it.  Instead, you are able to edit your original question (this one) to reflect any improvements or changes you would like to make.
Comment: @Daniel That's a great improvement: well done.  However, it's difficult to decipher the last four lines.  What is "PRIOR"?  What do "d" and "h" represent?  Something seems to be missing in the last line.  What does "~0.45" mean?
Comment: @Daniel I'm struggling to make sense of this information.  To me, the first four assumptions imply the probability of somebody observing blue is 0.16 + 0.05 = 0.21, because (I presume) the two conditions are mutually exclusive (friends are not enemies) and exhaustive (one is either a friend or an enemy).  It therefore appears contradictory to assert that this probability equals 0.3.  Also missing from your account is any clear and full distinction between "observing" and "sending".  What is the error matrix for this channel?
Comment: @whuber to your previous comment: the probability of someone observing blue is different from the probability of the ball being drawn is blue given someone sending the message blue. Please look at the new modified version of the question above. The question is what is the probability that the ball drawn is BLUE given that I received the message BLUE and I know the probabilities with which the two players send RED or BLUE depending on what they observed.
Comment: @Daniel I'm sorry about being too busy to participate in a chat today.  As your question continues to be refined, I continue to think that the approach suggested by @Greg Snow is the right one: this is a standard (and simple) Bayesian calculation, a natural variant of the [binary symmetric channel](http://en.wikipedia.org/wiki/Binary_symmetric_channel) of coding theory.
Comment: @DBR If you would like the question removed, then simply flag it by following the "flag" link and explain the reason why.  If you continue damaging this thread, your access to this site will have to be suspended without any further warning.
Comment: @DBR In response to your flags: the replies are relevant to earlier versions of the question (which remain in the archive accessible to anyone) and appear to have helped resolve or clarify your question.  It has also has picked up some substantial trains of comments as well as a chat thread.  This site's moderators are reluctant to destroy all that or to make it incomprehensible by erasing your question.  If you are unhappy with how the question is specified, then by all means clarify it, but out of respect for the help others have provided, please don't eliminate it altogether.
Comment: your statement of the problem is vague. Please consider restating it more clearly.
Comment: @Daniel Hint: the situation determines four cases altogether: truth+yellow, etc.  Can you work out the chances where blue is involved?
Answer: If Truth/Lie and color are independent and everything is random, then you would have an 18% chance of an honest person seeing blue and a 28% chance of a lier seeing yellow (and therefore claiming to see blue), you also have a 12% chance of lier seeing blue and 42% chance of honest seeing yellow.  So the probability of an honest person seeing blue given that the person claimed to see blue is $\frac{0.18}{0.18+0.28} = 0.39$.
Comment: Please read the [wiki for the homework tag](http://stats.stackexchange.com/tags/homework/info), especially the section on answering homework questions.
Comment: @Daniel, It's probably a good idea for you to comment on why you think this answer is right or wrong. Maybe, you could draw a picture?
Comment: @Daniel, Your last sentence in your original post reads..."I would like to know the probability of an honest person observing the blue colour given that he told me that the colour is blue." Should that say...."I would like to know the probability of an honest person observing the blue colour given that __I was told__ that the colour is blue". In other words, you don't know if the person telling you is honest or not.
Comment: @Daniel, If someone tells you the colour is blue, how many different ways/combinations can you interpret that information, given your original post?
Comment: @Daniel let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/731/discussion-between-bill-080-and-daniel)
Comment: @Daniel I know, the site automatically creates that "exact duplicate label" after a merge.  That can't be helped.  But evidently your new question functions merely as a modification of this original one.   By continuing the conversation here, you respect the replies that were graciously offered by earlier respondents and you maintain a coherent record of how the question (and the replies) have been improved.  Obliterating your original question (and leaving the replies and the chat record behind) will only be confusing and destructive.
Answer: If the honest person said "blue", and we are not dealing with the possibility of a misperception (honestly getting confused about colors), then there's a 100% chance it's blue.
But I suspect this isn't the question you intended to ask.

probability question


apply a function over 2 consecutive images in an imageCollection in google earth engine

Question: the function .map applies a function to every individual image in an ImageCollection. And the function .iterate applies a function to one image and the output of the calculation done to the precedent image on an ImageCollection.
The first only works with one image each time, and the second implies modifying each image and utilize it to any calculation with the next one.
I need a function that works like .iterate, but does not modify the precedent image. I just need to do:
image (time -1) / image (time 0).
I can not find a way to do it,
thanks for your help
i have tried,
var first = ee.List([
  ee.Image(1).set('system:time_start', time0).select([0], ['pc1'])
]);

var changeDET = function(image, list) {
  var previous = ee.Image(ee.List(list).get(-1));
  var change = previous.divide(image.select('pc1'))
    .set('system:time_start', image.get('system:time_start'));

  return ee.List(list).add(change);
};

var cumulative = ee.ImageCollection(ee.List(imageCollection.iterate(changeDET, first)))
  .sort('system:time_start', false)

Answer: What you can do is to convert your imageCollection into a ee.List object, then map over that list with an index variable to access the previous image. Example code is below:
var length = yourImageCollection.size();
var list = yourImageCollection.toList(length);

var calculated_list = list.map(function(img) {
    var index = list.indexOf(img)
    img = ee.Image(img);
    var previousIndex = ee.Algorithms.If(index.eq(0), index, index.subtract(1));
    var previousImage = ee.Image(list.get(previousIndex)):
    var change = ee.Image(previousImage.divide(img)
                                       .copyProperties(img, ["system:time_start"]));
    return change;
})

I'm not sure what you want to do with the first image, so when map function reach the first image, previousIndex will equal to index. In other words, the first image will be divided by itself (as there is no image before it).
Hope this helps.
Comment: thanks, @Kevin. Before I try it, actually the problem that you mentioned was the next one. I always get an imageCollection with the first (or possibly the last if sorted backward) with an image I don't want. How can I filter the collection without that image? there is not an `ee.Filter.first` function. thanks
Comment: @javier, if the image you want to filter out does not share its date with other images, you can filter it using `filterDate` method of imageCollection. Note that this can only be done if that image is either the first or the last image by date.
Comment: thanks @Kevin, i have thought of that solution, but, i will filter also on the images of interest, since they share the date.


c7000 - 1GB Ethernet Pass-Thru

Question: I cant get the BL460c Gen 8 to work with the 1GB Ethernet Pass-Thru non of the ports are mapped or lighting up.
Comment: Do you have a cable in the port on the passthrough module?
Comment: yes but none of the lights are on
Answer: The blade server's NICs are hardwired to interconnect bays 1 and 2 on a C7000.
For your system, NIC1 in the blade will map to port 1 on the single passthrough module you have.

c7000 - 1GB Ethernet Pass-Thru