Primefaces gmap doesn't show after click on p:commandButton (ReferenceError: google is not defined )

Question: I see gmap just after update page. If I don't update page I get error in chrome console
Uncaught ReferenceError: google is not defined index.xhtml:1
Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.

<h:body>
    <ui:composition template="/WEB-INF/template/layout_template.xhtml">
        <ui:define name="windowTitle">
            Admin Panel
        </ui:define>
        <ui:define name="content">
            <h:form>

Map

            </h:form>

        </ui:define>
    </ui:composition>

</h:body>

My footer template

<ui:composition>

 2013 © by Me

    <h:outputScript name="lib/bootstrap.min.js" library="js" target="body"/>
    <h:outputScript name="app/smooth-sliding-menu.js" library="js" target="body"/>
</ui:composition>

I read in doc
But I don't want put gmap script in head of main template. Is it posiible to make it work without redirect. And is it possible to add script in head of child template
Comment: You can execute/call a JavaScript method at any time and you don't need a redirect to achieve it. For the second question, you can use `h:outputScript` in child templates.
Comment: @SujanSivagurunathan I can't put external url inside `h:outputScipt`
Comment: `` should work inside a child template wrapped by a form. What's wrong ?
Comment: @SujanSivagurunathan I get 'Uncaught ReferenceError: google is not defined'.
Comment: Try to load the script before loading gmap. Put the script tag before gmap.
Comment: @SujanSivagurunathan It doesn't help
Comment: Add `&callback=initialize` to the script's URL. You might have encountered this [issue](http://stackoverflow.com/questions/14184956/async-google-maps-api-v3-undefined-is-not-a-function/14185834#14185834)
Comment: @SujanSivagurunathan with 'callback' appears new exception http://i.imgur.com/8xWmacY.png
Answer: I found the solution for this problem. On previous page I have p:commandButton

I doesn't have ajax="false" attribute but page was changed I don't know why. Now, with non-ajax submit I don't get any problems.


Como usar Método Genérico com Dapper?

Question: Tenho 2 métodos de um repositório genérico
public TEntity ObterPorId(int id)
{
    return Db.Set<TEntity>().Find();
}

public IEnumerable<TEntity> ObterTodos()
{
    return Db.Set<TEntity>().ToList();
}

porém quero utilizar o Dapper, pra obter um pouquinho mais de performance, pois o método ObterTodos do Entity está demorando muito pra trazer os dados.
Como posso fazer isso utilizando o Dapper?
Comment: Talvez o link te ajude a seguir um caminho... http://www.bradoncode.com/blog/2012/12/creating-data-repository-using-dapper.html
Answer: Veja este artigo da Poliana Dias, elá está desenvolvendo um projeto no GitHub com Dapper, lá tem um exemplo de um metodo generico.
O projeto está bem no começo, fácil de entender e acompanhar..
https://polianadias.wordpress.com/2016/05/19/implementando-dapper-e-dapper-extensions-no-asp-net-mvc-usando-ddd-solid-di-ioc-crosscutting-e-selfvalidation/
OU diretamente no GH
https://github.com/polianadias/arquitetura-modelo

Como usar Método Genérico com Dapper?


Why were Javascript `atob()` and `btoa()` named like that?

Question: In Javascript, window.atob() method decodes a base64 string and window.btoa() method encodes a string into base64.
Then why weren't they named like base64Decode() and base64Encode()?
atob() and btoa() don't make sense because they're not semantic at all.
I want to know the reason.
Comment: It's because the 'b' in a `atob` stands for binary, not base64. ASCII is base64 encoded, and strings are binary.
Comment: I too was convinced that atob and btoa were named backwards, being A the original string and B the encoded string, it was an unfortunate conicidence Base64 shared the initial with the encoded string B. Piling up on the confusion is the fact that I started using Linux only during the last decade, Linux provided the base64 program so I never had to know that btoa did the same. I hardly question naming choices, but after many years I just had to know.
Comment: You could go function abes46neoced(a){return swab(swab(atob(a)))); but you would need to write your own swab function.
Comment: @janac ASCII is NOT base64, if anything, one could maybe argue base64 is a subset of ASCII. But that's not really true either, it just gets represented by alphanumeric symbols we all recognize. ASCII was originally designed with 7 bits aka base128 and the newer utf-8 format and now utf-16 are the most common. Base256 and base65536. But no one calls them that. Base64 was "created" and used to ensure older incompatible devices could talk, since some used 7bits and some used 6bits for network communication. Base64 is 6 bits so it worked on both.
Answer: I asked Brendan Eich (the creator of JavaScript) if he picked those names on Twitter and he responded:

Old Unix names, hard to find man pages rn but see
https://www.unix.com/man-page/minix/1/btoa/ …. The names carried over
from Unix into the Netscape codebase. I reflected them into JS in a
big hurry in 1995 (after the ten days in May but soon).

In case the Minix link breaks, here's the man page content:
BTOA(1)                                           BTOA(1)

NAME
       btoa - binary to ascii conversion

SYNOPSIS
       btoa [-adhor] [infile] [outfile]

OPTIONS
       -a     Decode, rather than encode, the file

       -d     Extracts repair file from diagnosis file

       -h     Help menu is displayed giving the options

       -o     The obsolete algorithm is used for backward compatibility

       -r     Repair a damaged file

EXAMPLES
       btoa a.btoa # Convert a.out to ASCII

       btoa -a a.out
               # Reverse the above

DESCRIPTION
       Btoa  is  a  filter that converts a binary file to ascii for transmission over a telephone
       line.  If two file names are provided, the first in used for input and the second for out-
       put.   If  only one is provided, it is used as the input file.  The program is a function-
       ally similar alternative to uue/uud, but the encoding is completely different.  Since both
       of  these are widely used, both have been provided with MINIX.  The file is expanded about
       25 percent in the process.

SEE ALSO
       uue(1), uud(1).

Comment: Well, this is the actual answer to OP's question.
Comment: In my head, I always expanded the functions to **a**scii**ToB**ase64 and **b**ase64**ToA**scii, which always confuses me, since they actually do the exact opposite of that. That answer _finally_ provides a good explanation that even makes some sense. Hope my brain will be able to pick that up :)
Answer: The atob() and btoa() methods allow authors to transform content to and from the base64 encoding.

In these APIs, for mnemonic purposes, the "b" can be considered to
  stand for "binary", and the "a" for "ASCII". In practice, though, for
  primarily historical reasons, both the input and output of these
  functions are Unicode strings.

From : http://www.w3.org/TR/html/webappapis.html#atob
Comment: But it's backward. `atob()` converts binary to ASCII, and `btoa()` converts ASCII to binary.
Comment: ascii is base64, and `atob` is ascii to binary. they kind of left this out of both answers. so it isn't reversed
Comment: So the `String` is `Binary`?! And I thought all the time, binary was something like 0 and 1. This is SO CONFUSING!
Comment: @StefanRein I agree with your opinion. `window.btoa` read its argument as **binary data** and split it into 6 bits of chunks in order to encode it; it's true, so the naming makes sense in a point of view. However, also, `window.btoa` only takes a **string** as its argument! :(
Comment: @K._ > "However, also, `window.btoa` only takes a **string** as its argument!" < That's true but the string here is only a representation of the data. Like if you try to open an image in a notepad it'll display as a string but it's still binary data. `btoa`'s main advantage is that it doesn't care what format the string is in, it just treats it as binary. It's only incidental that in most cases that string happens to be a regular string.
Comment: This is a typical Javascript approach. Even mnemonics are broken in this language.
Comment: No it's a browser / web standard API, not JavaScript. Node.js has better APIs and first-class binary support via `Buffer`, e.g. `buffer.toString('base64')` and `Buffer.from(base64string, 'base64')`
Comment: @StefanRein @AKnox Not only `String` is `Binary`, but also `jpg`,`mp4`,`avi`,`gif`……any binary file can encode into base64 ASCII array.
Comment: I think we can all agree these are the worst named functions in the standard. To my brain, "b" must be short for base64 and "a" must be short for ASCII, yet it's the *complete opposite* of that. I just… why?
Comment: @jtheletter It's not backward, though I agree it's confusing. The "binary" input refers to a _string representation_ of binary data, in which each character is interpreted as one byte (hence why codepoints above `0xff` aren't allowed). Not all of this range is ASCII compliant (for example, `btoa('ð\x9f\x92©')` doesn't throw, even though none of these characters are ASCII).The "ASCII", meanwhile, refers to Base64, which _is_ ASCII compliant. I agree it's a horrible naming system though.
Comment: This, and following the C tradition like `atoi()` etc.
Comment: The "Binary" isn't supposed to mean normal text strings, but actual blob data - think images or document files.

I guess it's use for text strings comes from the need to safely store web form data without the threat of code injection, or some similar reason.
Comment: strange mnemonic choice :)
Comment: ASCII is not the same as base64, it is a superset.
Answer: To sum up the already given answers:

atob stands for ASCII to binary

e.g.: atob("ZXhhbXBsZSELCg==") == "example!^K"

btoa stands for binary to ASCII

e.g.: btoa("\x01\x02\xfe\xff") == "AQL+/w=="

Why ASCII and binary:

ASCII (the a) is the result of base64 encoding. A safe text composed only of a subset of ascii characters(*) that can be correctly represented and transported (e.g. email's body),
binary (the b) is any stream of 0s and 1s (in javascript it must be represented with a string type).

(*) in base64 these are limited to: A-Z, a-z, 0-9, +, / and = (padding, only at the end) https://en.wikipedia.org/wiki/Base64
P.S. I must admit I myself was initially confused by the naming and thought the names were swapped. I thought that b stand for "base64 encoded string" and a for "any string" :D.
Comment: I think you basically just proved everyone's point: base64 is a *subset* of ASCII, therefore while you might argue that the output of `btoa` is still technically ASCII, there's **no** justification for the name `atob` which only accepts base64 as input.
Comment: It helps to think and remember 'a'(ascii) as base64 output and 'b'(binary) as stream of 0 and 1 which is string.
Answer: The names come from a unix function with similar functionality, but you can already read that in other answers here.

Here is my mnemonic to remember which one to use. This doesn't really answer the question itself, but might help people figure which one of the functions to use without keeping a tab open on this question on stack overflow all day long.
Beautiful to Awful btoa
Take something Beautiful (aka, beautiful content that would make sense to your application: json, xml, text, binary data) and transform it to something Awful, that cannot be understood as is (aka: encoded).
Awful to Beautiful atob
The exact opposite of btoa
Note
Some may say that binary is not beautiful, but hey, this is only a trick to help you.
Comment: This mnemonic seems far more confusing than just remembering what the name is _actually_ meant to stand for, which is "Binary to ASCII". It's pretty unintuitive that in your mnemonic, binary content that may literally not even contain printable characters is meant to be "beautiful" while the ASCII content is "awful".
Answer: I can't locate a source at the moment, but it is common knowledge that in this case, the b stands for 'binary', and the a for 'ASCII'.
Therefore, the functions are actually named:
ASCII to Binary for atob(), and
Binary to ASCII for btoa().
Alos, note that this is browser implementation and was left for legacy / backward compatibility purposes. In Node.js, you would use:
Buffer.from("Hello World").toString('base64')
Buffer.from("SGVsbG8gV29ybGQ=", 'base64').toString('ascii')

Comment: In Node you use `Buffer.from("Hello World").toString('base64')` & `Buffer.from("SGVsbG8gV29ybGQ=", 'base64').toString('ascii')`


mySQL adding functionality to search function

Question: This mySQL query searches for items in a wordpress database looking for similarities in the title.
SELECT ID, post_name, post_title, post_date
FROM wp_posts

WHERE wp_posts.post_type = 'post' AND wp_posts.post_status = 'publish' AND wp_posts.post_title LIKE '%$my_text%' ORDER BY wp_posts.post_date DESC

I have expanded it to include tags as well.
SELECT ID, post_name, post_title, post_date
FROM wp_posts
LEFT JOIN wp_term_relationships
ON        object_id = wp_posts.id
LEFT JOIN wp_terms
ON        term_id = wp_term_relationships.term_taxonomy_id

WHERE wp_posts.post_type = 'post' AND wp_posts.post_status = 'publish' AND wp_posts.post_title LIKE '%$my_text%'

OR wp_posts.post_type = 'post' AND wp_posts.post_status = 'publish' AND wp_terms.name LIKE '%$my_text%'

This too works but it adding to the query the number of times a post can be fetched. For example, if we type in a search term that appears only in the title, but the same post ID is in the tag table for four unrelated tags, it fetches the post from the title similarity four times not one. Obviously this query needs some tweaking but I am very new to mySQL and need a hand.
Comment: You may need the UNION clause.
Answer: Here is a helpful link for UNION selects: http://www.mysqltutorial.org/sql-union-mysql.aspx
Answer: ...  WHERE
wp_posts.post_type = 'post' AND wp_posts.post_status = 'publish'
AND (wp_posts.post_title LIKE '%$my_text%' OR wp_terms.name LIKE '%$my_text%')


Mostrar e ocultar DIV de acordo com o nível do usuário

Question: Preciso exibir alguns elementos div de acordo com o nível do usuário logado. Se o usurário for nível um só pode amostrar determinadas div's. Segue abaixo a exibição:

Administrativo

Requisição de equipamentos

Documentações

Cadastro

Faturamento

Honorário Médico

Lançar sessões

Lançar na conta

Fatura por unidades

Comment: No meu caso em .NET criava o HTML no back-end e renderizava conforme a regra do nível do usuário.
Comment: Postei uma solução bem genérica, podem existir inúmeras variações de acordo com o seu contexto específico. Se puder informar mais detalhes, posso refinar a minha solução.
Answer: Uma implementação bem genérica poderia ser:
function exibirDivDeAcordoComNivelDoUsuario(usuario) {
    if(usuario.nivel !== 1) {
        document.getElementById("hmn0").style.display = 'none';
    }
}

Comment: Tenho um sistema com níveis de usuário, que são três níveis e apos a tela de login entram na pagina de MENU, uma pagina que possui vários DIV's com links para outras paginas... mas gostaria que só aparecesse certos DIV's de acordo com o nível do usuário que logou  ...  Estou usando PHP e HTML ... Já consegui bloquear para que o usuário não acesse a pagina dependendo do nível dele, mas o DIV na pagina de MENU ainda aparece.
Answer: Como vc não especificou em que ambiente servidor é o seu site, vou dar um exemplo simples em ASP (VBScript):
Crio uma Session com o nível do usuário quando ele faz login:
session("user_nivel") = 1

No HTML, eu só mostro para o nível 1 o que eu quiser, assim:
<%if session("user_nivel") >= 2 then%>

  Esta div só é visível para nível 2 acima

<%end if%>

<%if session("user_nivel") = 1 then%>

  Esta div é visível somente para nível 1

<%end if%>

Se vc está utilizando PHP, a ideia é a mesma.

Não faça isso em JavaScript porque pode ser burlado. O melhor é que a
  div já venha ausente do servidor.
Comment: Acredito que estou fazendo algo errado, em php estou deixando assim


Splitting the plane to fit convexes

Question: I'm trying to show the following :
Let $K,L$ two closed convexes of $\mathbb{R}^2,O=(0,0)$

If $O\notin K$ then there exists a straight line $D$ going through $O$ such that $K$ is in one of the half of plane defined by $D$
If $K$ is bounded and does not intersect with $L$ then there exists a straight line $D$ such that $K$,$L$ are in two distinct halves of plan defined by $D$

Those two properties are really easy to understand intuitively or with a graph, but I haven't been able to find a proper mathematical proof.
Comment: By the way, it seems that this is a general situation not only for the plane, but for a locally convex space $X$, satisfying the Hahn-Banach Theorem. Since $K$ is closed, by [Hahn-Banach separation Theorem](http://en.wikipedia.org/wiki/Hahn%E2%80%93Banach_theorem#Hahn.E2.80.93Banach_separation_theorem) there exist a real number $\varepsilon>0$ and a linear functional $f$ on $X$ such that $f(O)=0$ and $f|K>\varepsilon$. Geometrically it should mean that there is a hyperplane strictly separating the point $O$ from the set $K$.
Comment: Are the sets assumed open or closed? If not, you have to be careful: Consider the example where $K$ consists of points with $x^2+y^2<1$ and either $y>0$ or $y=0$ and $x>0$. Then let $L=-K$ (i.e., the reflection of $K$ through the origin).
Comment: @HaraldHanche-Olsen They're closed, thanks, I forgot to add that.
Comment: @AlexRavsky Absolutely. However, the Hahn–Banach separation theorem is *much* easier in Hilbert spaces! The proof outlined by me and elaborated by Mike Miller works equally well in that more general setting.
Answer: Two hints for the price of one: For the first one, consider the point $P\in K$ closest to the origin, and take $D$ to be normal to the line from $O$ to $P$.
For the second one, apply the first one to the set $K-L=\{u-v\colon u\in K, v\in L\}$.
Answer: Here's a solution to the first problem. (For these sorts of problems I suggest drawing pictures - it's amazing how helpful blobs on a page can be.) Harald's gives you the second.
Because $K$ is closed, there's a point in $K$ of minimal distance to the origin; call it $v=(x,y)$. Then consider the normal line $D = \text{span}(-y,x)$. It suffices to show that $K \cap D = \varnothing$. Suppose not; say $(-ty,tx) \in K$. Because $v$ had minimal distance to the origin, $t \geq 1$. By convexity, every point of the form $s(-ty,tx) + (1-s)(x,y) \in K$ for $0 \leq s \leq 1$. Let's take the norm of this point. After some algebra, we obtain $$\sqrt{(1-s)^2+s^2t^2}\|v\|.$$
But for $s$ sufficiently small (pick $0 < s < \frac{2}{1+t}$), the first term is less than 1; this contradicts that $v$ was the point of $K$ of least norm. So $K \cap D = \varnothing$ as desired.

Splitting the plane to fit convexes


Xcode analyzer ignores autorelease

Question: I am using latest Xcode, and trying to find memory leaks.
When i use 'Analyze'
It shows following as potential leak:
<code>+ (UITableViewCell *) method {
UITableViewCell *cell = [[TestX alloc]init];
... do some stuff
return [cell autorelease];
}
</code>
Should i just ignore it ?
Comment: This is a sample code, how to release 'Cell' object ???
Answer: No, you shouldn't ignore warnings.  Sometimes Xcode is buggy and forgets you've changed the code.  Try restarting Xcode.  Remove do some stuff so that it's just the two lines and see if the analyser stops warning you.  It could be the case that you're affecting the retain count in that code somewhere without realising it.
Answer: You need to name the method properly to show that it's returning an autoreleased object.  I forget the preferred name.  Try something like 'newObject'.
Comment: No, that's the exact opposite of what he should do.  A method name with `new` in it indicates that the method passes ownership back, i.e. that it's *not* autoreleased.

Xcode analyzer ignores autorelease


Combine users social feeds

Question: I'm trying to figure out a way of displaying my user's personal social feeds on my site.
I know an application will have to be made to use the API etc, but I'm having trouble figuring out how to display the users personal feeds. Here's an example of how I'd like it to work:
User clicks to connect to Facebook/Twitter/(Other) >
User allows authorisation of app >
Users personal feed that they would see on Facebook or Twitter is now being shown on the site.
It has to be personalised for every user.
Answer: If you are looking just for aggregators of user feeds from different social networks, you might try to give a look to http://pavelk2.github.io/social-feed/, which works with Facebook, Google+, Instagram and VK. It is open-source and you can get the code here: https://github.com/pavelk2/social-feed

Combine users social feeds


How add drive to array using LSI Megaraid Storage Manager

Question: I have an LSI 1068E raid card, with 4 disks, configured as 2 RAID1 pairs.  I'm not sure how, but I've ended up with a pair in a degraded state, and one of the disks from that pair shows as unconfigured (spare).
I've been through every option on the screen but can't figure out how to add this physical drive to virtual drive 0.
Can any offer step-by-step how to do this?  (Don't post general answers, since I've already done the 'general' stuff).  Do I have to do it from the BIOS?  (That would seem silly given the intent of the Storage Manager tool, but maybe they're punishing me for buying the entry level 1068E product and only let me make changes via the bios?)
Answer: I think the problem is the capacity (0 Bytes). It seems that the controller can't talk properly to the disk (no serial number, no vendor or product. Maybe the disk is defective.
Try to reconnect the disk and/or reboot the server. Try to connect the disk alone to another computer to see whether the problem is the disk, the cable or the controller.
Comment: drive is ok - works fine on other sata system.  if I wipe out the raid then controller sees disk fine
Comment: My problem is that I can't the Java UI to work, so I can only use the command line. My next step would be to use `storcli /c0 /fall show` to see whether the controller thinks the disk still has RAID headers on it. `storcli /c0 /fall import` would fix that.
Comment: What exactly do you mean by "wipe out the raid"? Have you tried to buy another disk and see if that works?


Defining cutoff point for logistic regression

Question: I am experimenting with logistic regression to predict a binary target variable.
Using Stata, I have generated predicted probabilities between 0 and 1.
Now, I am trying to think about how to translate these probabilities into the binary classification. Using a rule like "<50%==0 and >=50%==1" feels arbitrary, but I haven't found a better solution so far.
Any ideas?
Comment: I updated the answer! Hope the last paragraph will help more!
Comment: See [Why isn't Logistic Regression called Logistic Classification?](https://stats.stackexchange.com/questions/127042/why-isnt-logistic-regression-called-logistic-classification/127044#127044)
Answer: ROC (Receiver operating characteristic) curve (http://en.wikipedia.org/wiki/Receiver_operating_characteristic) is one way of finding best cutoff and is widely used for this purpose. From http://www.stata.com/manuals14/rroc.pdf :

ROC analysis quantifies the accuracy of diagnostic tests or other
  evaluation modalities used to discriminate between two states or
  condition

You can use roctab, roccomp, rocfit, rocgold, rocreg, and rocregplot in stata for this purpose.
The cutoff that gives curve with maximum area under it is the best, as shown in following figure from http://www.adscience.eu/uploads/ckfiles/files/html_files/StatEL/statel_ROC_curve.htm
Comment: but the different curves here are not results of different cutoffs, but different models. Rather, each curve is plotted out by changing cutoff values from 0 to 1. So ROC cannot be used to determine the best cutoff, because ROC itself is generated by changing cutoff over its possible values.
Answer: In STATA you can compute the cutoffs by typing in the shell:
lsens, genprob('var_name')

after the logistic command; the var_name is arbitrary and it corresponds to the name of the cutoff variable you are going to generate. The variable you will create contains a set of cutoff points you can use to test the predictability capacity of your model.
Alternatively, once you got the vector of possible cutoff points in STATA, you can find the optimal (theoretically) cutoff by computing the Youden's index, that summarize the performance of the diagnostics test.
Here, you can find the link to the command guide and example on using the lsens command.


L2 Regularization in CatBoost

Question: I am studying the CatBoost paper https://arxiv.org/pdf/1706.09516.pdf (particularly Function BuildTree in page 16), and noticed that it did not mention regularization.
In particular, split selection is based on minimizing the loss of a new candidate tree, measured by cosine distance between previous iteration gradients and tree outputs. I don't see a "lambda" parameter goes in to penalize new splits.
However, in the CatBoost package there is the parameter of l2_leaf_reg, which is for "Coefficient at the L2 regularization term of the cost function". How does that parameter work?
Comment: As a comment: `catboost` formal documentation is messy (at best). I would suggest you read the code. It might do exactly what `xgboost` is doing by penalising the leaf weights' $l_2$ norm or they might have done something slightly different.
Answer: The value of the parameter is added to Leaf denominator for each leaf in all steps. Since it is added to denominator part, the higher l2_leaf_reg is the lower value the leaf will obtain.
It is quite intuitive though, when you think how L2 Regularization is used in typical linear regression setting.
https://github.com/catboost/catboost/blob/560e1dbcb2fb960f1eb40f4b3102b269a8d15257/catboost/private/libs/documents_importance/tree_statistics.cpp#L75
Comment: So, if I tried catboost model with all default value except the `eval_metric = MAE` and `error_metric = MAE` , AND the resulting model mostly underfits, does adding `l2_leaf_reg=0.1-0.5` help?

L2 Regularization in CatBoost


How to display a form in a panel page?

Question: My goal is to display a form in a page made with panels. The form will be between content panes.
The single page (made with page manager & panels) will be like below:

Content Pane
Form
Content Pane

How can I achieve that, and display the form in a page made with panels ?
Update 2-4-2014:
I found this article and created the following block that doesn't work (I am getting an error when trying to add that to panels). can sombody help make this thing work?
<code><?php
function my_answer_form_block_info() {
    $blocks = array();
     $blocks['my_answer_form'] = array(
            'info' => t('My-Answer-Form'),
            'cache' => DRUPAL_CACHE_GLOBAL,
    );

    return $blocks;
}

function my_answer_form_block_view($delta = '') {
    $block = array();
    switch($delta) {
            case 'my_answer_form':
                    $block['subject'] = t('My Answer Form');
                    $block['content'] = drupal_get_form('answer_node_form');
            break;
    }
     return $block;
}
  ?>
</code>
Note: Form ID is: "answer_node_form"
I am using the Answers Module. The form I want to put on the panel page is the Answer Form, that was created by the Answers Module. Is that a node form or a custom form?
Comment: is it node form or your custom form created using module?
Comment: Hey, I updated my question. I am using the Answers Module. The form I want to put on the panel page is the Answer Form, that was created by the Answers Module. Is that a node form or a custom form?
Comment: I think you might find your "My Answer Form" block listed under Miscellaneous in Panels' add content dialog?
Answer: If it is node form you could use Form Block. It will create form in block and you could add that in content panes.

Enables the presentation of user registration, site wide contact, or
  node creation forms in blocks. This is particularly useful for
  including forms on panels.
Comment: I am using Drupal 7, and there is no stable version of the form block module for Drupal 7. I tried to use the DEV version with panels, but then I have errors and some bugs (I can't add more panels after adding the form block).
I will be happy to get help here , or any other suggestions?
Answer: If you want a simple form for user submissions I would recommend using webform. With this module you can expose it as a block and add it to a panel page.
If it is a custom form, for generation nodes or entities for example, I would recommend writing your own form with the Drupal Form API and exposing it as a block to put it on your panel page.
A good starting point for writing your own modules is the Drupal examples module. This gives you really good insight into how forms need to be structured and also how to create your own blocks.
I hope this helps you.
Comment: Thank you for your answer. In this specific case my goal is to put the Answer Form of the Answers Module on my panel page. Do you have more insights for this specific case?

How to display a form in a panel page?


Prove that $\exists c>0$ s.t $\sum_{n\geq x}\frac{1}{n^2}\leq \frac{c}{x}$

Question: $\mathbf{Question:}$ Prove that there exists a constant $c>0$ such that for all $x \in [1, \infty)$, $\displaystyle\sum_{n \geq x}\frac{1}{n^2} \leq \frac{c}{x}$
$\mathbf{Attempt:}$ Evidently,
$\displaystyle\bigg[\displaystyle\sum_{n =1}^\infty\frac{1}{n^2}-\sum_{j=1}^{\lfloor x \rfloor} \frac{1}{j^2}\bigg]{\lfloor x \rfloor}\leq x\displaystyle\sum_{n \geq x}\frac{1}{n^2} \leq \displaystyle\bigg[\sum_{n =1}^\infty\frac{1}{n^2}-\sum_{j=1}^{\lfloor x \rfloor} \frac{1}{j^2}\bigg]{\lceil x \rceil} $.
This inequality arises since,
$\displaystyle\bigg[\sum_{n =1}^\infty\frac{1}{n^2}-\sum_{j=1}^{\lfloor x \rfloor} \frac{1}{j^2}\bigg]=\displaystyle\sum_{n \geq x}\frac{1}{n^2}$.
Now, let $\lfloor x\rfloor=m$
$\displaystyle\lim_{m \to \infty}\bigg[\sum_{n =1}^\infty\frac{1}{n^2}-\sum_{j=1}^m \frac{1}{j^2}\bigg]m$
$=\lim_{{m \to \infty},{r\to \infty}}\bigg[\frac{m}{(m+1)^2}+\frac{m}{(m+2)^2}+\frac{m}{(m+3)^2}+...+\frac{m}{(m+r)^2}+...\bigg]=$
$\lim_{{h \to 0},{r\to \infty}}h\bigg[\frac{1}{(1+h)^2}+\frac{1}{(1+2h)^2}+\frac{1}{(1+3h)^2}+...+\frac{1}{(1+rh)^2}+...\bigg]=\displaystyle\int_{x=0}^\infty\frac{1}{(1+x)^2}dx=1$
We have, $\lceil x\rceil=m+1$ and $\displaystyle\lim_{m \to \infty}\bigg[\sum_{n =1}^\infty\frac{1}{n^2}-\sum_{j=1}^m \frac{1}{j^2}\bigg](m+1)=\lim_{m \to \infty}\bigg[\sum_{n =1}^\infty\frac{1}{n^2}-\sum_{j=1}^m \frac{1}{j^2}\bigg]m$
Thereby, we conclude, $\displaystyle \lim_{x\to \infty}x\sum_{n \geq x}\frac{1}{n^2}=1 $.
Therefore, from the definition of limit, $\forall \varepsilon>0$, $\exists G>0$ such that $\bigg|x\displaystyle\sum_{n \geq x}\frac{1}{n^2}-1\bigg|<\varepsilon$ $\forall x>G$. Choosing $\varepsilon =1$, we get $G=G_0$ such that $x\displaystyle\sum_{n \geq x}\frac{1}{n^2}<2$, for any $x> G_0$.
We set $\displaystyle c=\max\bigg\{2, \sup_{x\in [1,G_0]}x\sum_{n \geq x}\frac{1}{n^2} \bigg\}$
Is this procedure valid? Kindly verify.
Comment: Possible duplicate of [Prove that there exists a constant $c>0$ such that the following happens](https://math.stackexchange.com/questions/2222626/prove-that-there-exists-a-constant-c0-such-that-the-following-happens)
Comment: Also: https://math.stackexchange.com/q/2591225/42969
Comment: Since part of the question is a critique of the approach in the question, I don't see this as a duplicate of either question mentioned so far.
Answer: Comments
I had initially thought that, although $x$ is usually a real variable, $x$ was intended to be an integer. However, if $x$ is intended to take on any real value, one needs to be clear on exactly what is meant, since this is not a standard use for $\sum$. Here are two that come to mind at first:
$$
\sum_{n\ge x}\frac1{n^2}=\sum_{n=\lceil x\rceil}^\infty\frac1{n^2}
$$
and
$$
\sum_{n\ge x}\frac1{n^2}=\sum_{n=0}^\infty\frac1{(n+x)^2}
$$
That point aside, your approach of finding the limit and using that for all $x$ past a finite value, and then handling the initial finite range of $x$ separately, is quite valid.

Slick Answer
For $m\ge1$,
$$
\begin{align}
\sum_{n\ge m}\frac1{n^2}
&\le\sum_{n\ge m}\frac1{\left(n-\frac12\right)\left(n+\frac12\right)}\\
&=\sum_{n\ge m}\left(\frac1{n-\frac12}-\frac1{n+\frac12}\right)\\
&=\frac1{m-\frac12}\\[3pt]
&\le\frac2m
\end{align}
$$

Less Slick Answer
For $m\ge2$,
$$
\begin{align}
\sum_{n\ge m}\frac1{n^2}
&\le\sum_{n\ge m}\frac1{(n-1)n}\\
&=\sum_{n\ge m}\left(\frac1{n-1}-\frac1n\right)\\
&=\frac1{m-1}\\[3pt]
&\le\frac2m
\end{align}
$$
For $m=1$,
$$
\begin{align}
\sum_{n\ge m}\frac1{n^2}
&\le1+\sum_{n\ge 2}\frac1{(n-1)n}\\
&=1+\sum_{n\ge 2}\left(\frac1{n-1}-\frac1n\right)\\
&=2\\[6pt]
&=\frac2m
\end{align}
$$
Comment: The notation seems unambiguous to me: $n$ ranges over all integers that are $\ge x$.
Comment: That is the first of the two possibilities I listed, but then why allow $x$ to be real other than to make the bound a bit more difficult to compute? The second interpretation, which is similar to that used to extend [Harmonic Numbers](https://math.stackexchange.com/a/506068) continuously to all real (or complex) limits, at least gives a reason for considering real limits.
Answer: I think you would be better off starting with an integral from the start:
$$\frac 1{n^2} \le \int_{n-1}^{n} \frac 1{t^2} \, dt.$$
For any integer $k$ [edited to address complaint] integer $k \ge 2$ you have
$$\sum_{n=k}^\infty \frac 1{n^2} \le \int_{k-1}^\infty \frac 1{t^2} \, dt = \frac 1{k-1}$$
From here it is not too difficult.
Comment: What constant can you get for $k\ge1$ for $\frac1{k-1}\le\frac{c}{k}$?
Comment: Don't be dense. If $k = 1$ the sum is bounded. If $k \ge 2$ then $$\sum_{n=k} \frac{1}{n^2} \le \frac 1{k-1} = \frac 1k \frac{k}{k-1} \le \frac 2k.$$
Comment: No need for name calling. I am simply pointing out that $\frac1{k-1}$ does not answer the question as it stands. For $k\ge2$, a constant of $2$ works, but one needs to handle $k=1$ separately.
Comment: Of course it didn't answer the question. Hence the last sentence "From here it is not too difficult".
Comment: I already upvoted, but I appreciate the edit.
Comment: It is a better idea. Anyways, is my proof correct? A review of what I have done would be really helpful :)


bar graphs with nested groupings for repeated measures

Question: For a bar graph of repeated measures on different devices I need to plot something similar to this minimal example: 4 tests on 3 different devices, with settings 'high' and 'low' (missing tests are 0):
df = data.frame(test     = c(rep('test 1', 6), rep('test 2', 6),
                             rep('test 3', 6), rep('test 4', 6)),
                settings = c(rep(c('high', 'low'), 12)),
                device   = c(rep(c(rep("device 1", 2),
                                   rep("device 2", 2),
                                   rep("device 3", 2)), 4)),
                values   = c(5, 4, 3, 2, 4, 3,
                             3, 2, 0, 0, 0, 0,
                             4, 3, 5, 3, 0, 0,
                             0, 0, 4, 1, 6, 4)
     )

I have managed to plot this:
p <- ggplot(data = df, aes (x = device, y = values, fill = settings)) +
  geom_col() +
  facet_grid(.~test)

p + theme(axis.text.x = element_text (angle = 60 , hjust = 1),
          strip.text.x = element_text (angle = 90))

but I would like to

have different colours for the different devices (so grouping by settings and device)
have the bars of the 'high' and 'low' measurements next to each other, not stacked

Would that be possible with ggplot?
I also have tried this
q <- ggplot(data = df, aes (x = device, y = values, group = device,
            fill = test, alpha = settings)) +
  geom_bar(stat = "identity",  color = "black") +
  facet_grid(~test)

which almost does the job, definitely for the colours, but:

the bars are still on top of each other, not side by side / half overlapping
the lighter colour is at the bottom, which is the other way round from previous examples?
Comment: Try `position = "dodge"` in the `geom_bar()`. Is that what you want?
Answer: I am not yet 100% sure about your expected outcome, but it seems that the following is what you aim to accomplish.
q = ggplot ( data = df, aes ( x = device,
                              y = values,
                            group = settings,
                            fill = device,
                           alpha = settings)) +
  geom_bar(stat = "identity", color = "black", position = "dodge") +
  facet_grid(~test)

with outcome
Comment: Yes! "dodge" is the answer, thanks. I'm still looking if I can make the transparent less transparent (say 50%) and swap the colouring of 'high' and 'low' but that should be doable.


SSH tunnel with xinetd; bind Address already in use

Question: I'm having an ssh tunnel connection which works fine from the command-line;
ssh -f -N -L 4444:to.somewhere.com:80 firstname.lastname@example.com -p 22
Now I'm trying to make this connect to connect on demand with xinetd. I've put this custom port in /etc/service (tool 4444/tcp), and made a config file in /etc/xinetd.d;
<code>service tool
{
   socket_type     = stream
   instances       = 1
   wait            = no
   user            = root
   server          = /usr/bin/ssh
   server_args     = -f -N -L 4444:to.somewhere.com:80 email@example.com -p 22
   port            = 4444
   disable         = no
}
</code>
After restarting xinetd I try to connect to this poort with a wget and get the message;
bind: Address already in use
lsof -i nor netstat -a don't show any open 4444 on forehand.
Answer: The reason is that xinitd will bind to the port, and when ssh tries to use it, the port is already in use. To use xinetd, you should communicate with stdin/stdout with the child process.
You can find a pointer how to manage a ssh tunnel with xinetd here:
http://www.debian-administration.org/articles/487
Comment: Yes, thank you, that did the trick! Although I knew that the problem was that the port was already in use I couldn't figure out how to setup the connection without the tunnel. When using the command="etc.etc." in de authorized_keys on the remote host it works flawlessly.
Comment: Would you please post a plot of the solution. URL is not working any more.
Comment: @BorisBrodski https://web.archive.org/web/20190503084658/https://debian-administration.org/article/487/SMTP_via_a_SSH_tunnel


How do I remove double quotes from string PHP?

Question: I use this but not working, returns same value ($teamdatarow['color1'])
$color1 = str_replace('"', '', $teamdatarow['color1']);
Comment: Do you want to remove `"` or `"` ?
Comment: Most likely it's being sent `"` than `"`
Comment: ...I'm actually suspicious of this question: Why do you think you need to remove them and why are they there in the first place? Can you give some context?
Answer: Just try with:
$color1 = str_replace('"', '', $teamdatarow['color1']);


Is this proof that $\sqrt 2$ is irrational correct?

Question: Suppose $\sqrt 2$ were rational.  Then we would have integers $a$ and $b$ with $\sqrt 2 = \frac ab$ and $a$ and $b$ relatively prime.
Since $\gcd(a,b)=1$, we have $\gcd(a^2, b^2)=1$, and the fraction $\frac{a^2}{b^2}$ is also in lowest terms.
Squaring both sides,
$2 = \frac 21 = \frac{a^2}{b^2}$.
Lowest terms representations of rational numbers are unique, so we have $a^2 = 2$ and $b^2=1$.
But there is no such integer $a$, and therefore we have a contradiction and $\sqrt 2$ is irrational.
I am not interested in the pedagogical value of this purported proof; I am only interested in whether the logic is sound.
Comment: It's fine. You are essentially reducing to the Rational Root Test and then noting that there is no integer root. Of course, you might want to *prove* that there is no such $a$ (and your argument depends on the claim that "lowest term representations are unique"; that's only true if you require the denominator to be positive as well, though of course here you can assume $a,b$ are both positive).
Comment: This seems OK, the only question being what is hidden in the statement that "lowest terms representations of rational numbers are unique" (which is true if everything in sight is positive, but needs qualification in general), and whether you need further justification of that step.
Comment: @Mark The polynomial $x^2 -2$ is irreducible over $\Bbb{Q}$ by Eisenstein which implies that $2$ is irrational.
Comment: The same proof appears [in this MathOverflow thread](http://mathoverflow.net/a/48780/44852).
Answer: Your proof is correct. Quicker, from $\rm\:\color{#0a0}{(a,b)\!=\!1},\ 2\:\!b^2 = a^2\:$ we deduce by Euclid's Lemma ($\color{#c00}{\rm EL}$) that $\rm\:\color{#0a0}{b\:|\:a}\:\!a\:\Rightarrow\:b\:|\:a\,\ $ so  $\rm\:\sqrt{2} = a/b\in \mathbb Z.\:$

In your proof, the only "uniqueness" result we need on reduced fractions is the following:
$\rm{\bf Lemma}\  \ (a,b)\!=\!1,\ \dfrac{a}b = \dfrac{A}B\:\Rightarrow\:b\:|\:B\ \ $ Proof $\rm\ \ Ab=aB\:\Rightarrow\:b\:|\:aB\:\Rightarrow\:b\:|\:B\:$ by $\rm\color{#c00}{EL}.\ \small\bf QED$
$\rm Hence\quad\ \, (a,b)\!=\!1,\ \dfrac{a}b = \dfrac{2b}{a}\ \Rightarrow\:b\:|\:a\ \Rightarrow\ \sqrt{2}=\dfrac{a}b\in\mathbb Z.\ $ So you don't need  $\rm\:(a^2,b^2)=1.$
This method of proof generalizes to arbitrary square roots, e.g. see here.
The converse of the Lemma is also true, i.e. Euclid's Lemma is equivalent to this uniqueness property of reduced fractions. For more on this topic see my posts on unique fractionization.
Comment: @alexqwx Because, back then, MathJax had problems with italic fonts, which complicated intricate alignments, etc.
Comment: Out of curiosity, why do you `\rm` all of your letters?
Answer: Hhmmm ... Here is a short one.
We all know that $\sqrt{2}$ is a root of $x^2-2 = 0$
Apply Rational Root Theorem and you're done
It goes something like this : if $\sqrt{2} = \dfrac{p}{q}$, then $q=1$ and $p$ is a factor of $2$. Hence the only possible rational root of $x^2-2=0$ would be $-2,-1,1,-2$.
A quick check shows that this is not the case. Therefore $\sqrt{2}$ is irrational.
A bit further now : using the same Theorem, shiw that $\sqrt{n^2+1}$ is irrational.
Comment: To apply RRT requires assuming $\,p/q\,$ is in lowest terms. The question is not about other proofs such as this well-known one but, rather, *only* about the logic of the OP's proof, cf. "I am only interested in...".
Answer: Here's a proof that a rational algebraic integer is an integer, using matrices. An algebraic integer occurs as an eigenvalue of a matrix with integer entries. Let $A$ be an $n \times n$ matrix with integer entries. Suppose that $Av = \lambda v$ for some rational number $\lambda$ where $v$ is a non-zero rational column vector. Multiplying through by a suitable integer, we may suppose that $v$ has integer entries. Dividing through if necessary, we may suppose that the entries of $v$ have no common divisor greater than $1.$ Write $\lambda = \frac{r}{s},$ where $r$ and $s$ are relatively prime integers. Then $sAv = rv.$ However, all entries of the column vector on the left are integer multiples of $s$. On the other hand, since the entries of $v$ have gcd 1, the gcd of the entries of the column vector on the right is $r$ (more precisely, we may write $r$ as an integer combination of the entries of $rv$). Hence $s$ divides $r.$ But ${\rm gcd}(r,s) =1,$ so $s = \pm 1,$ and $\lambda$ is an integer. (Background: An algebraic integer, $\alpha$ say, is a root of a monic polynomial with integer coefficients. There is a unique such polynomial of minimal degree called the minimum polynomial of $\alpha.$ Then $\alpha$ is an eigenvalue of the companion matrix of its minimum polynomial).


win32 API SearchPath fails

Question: The win32 API SearchPath API fails to find the "telnet.exe" binary path even though its present in system32.
However when I did a search for notepad.exe, with the same code it returns the file path. What puzzles me here is that both notepad.exe and telnet.exe lies in the same directory i.e C:\windows\system32.
This is the code I have written
char path[MAX_PATH] = {0};
LPSTR* ptr = NULL;

DWORD dwRet = SearchPathA(NULL, "telnet.exe",
    NULL, MAX_PATH, (LPSTR)path, ptr);

This would always return 0 and the GetLastError is 2 ( File not found)
Any idea what is happening here?
I am using windows 2008 R2 enterprise edition on an x64 machine
Thanks & Regards
Sunil
Answer: It's not working because you application is 32 bit and is being affected by the File System Redirector.  Your application is not looking in C:\Windows\System32 but is instead being redirected to C:\Windows\SysWow64.
notepad.exe exists in both System32 and SysWow64, but telnet.exe only exists in System32.  So you application does not find it when it searches the path.
You can disable this behavior for your application by calling Wow64DisasbleWow64FsRedirection.  But note the warnings in the documentation links that indicate that this should only be disabled temporarily and then re-enabled.
Comment: *looking*, not *locking*.
Comment: Or pass the non-redirected System32 folder in the first parameter of `SearchPath()` using the `sysnative` alias, which the [file system redirector](http://msdn.microsoft.com/en-us/library/windows/desktop/aa384187.aspx) does not redirect: "32-bit applications can access the native system directory by substituting %windir%\Sysnative for %windir%\System32. WOW64 recognizes Sysnative as a special alias used to indicate that the file system should not redirect the access. This mechanism is flexible and easy to use, therefore, it is the recommended mechanism to bypass file system redirection."

win32 API SearchPath fails


Use of data from ROC curve

Question: In order to find an optimal time for initiation of treatment post surgery (oncologic patients) I created a ROC curve with death defined as event.
The AUC was not significant. However, I decided to use the time that provided the best specificity and sensitivity in cox regression as a binary variable.
The Cox parameter was significant.
I was wondering whether I am committing a sin using data from ROC curve with p-value > 0.05 and by using the data obtained from exploratory analysis to analyse the same training data.
I would be very interested in hearing feedback and suggestions (maybe for validation?)
Thanks in advance,
Liran
Answer: I can't see how you could find the optimal time without using utilities and incorporating uncertainty.
Answer: If you define a binary variable based in the "best" cutpoint (best sens. and spec.) is not surprising you have a Cox regression with a significant P-value, but the issue this test is not correct now. The selection of the best cutpoint is a similar idea to analysis the máximum of all the statistics over all possible cutpoints.
A suggestion is test the significance by permutations, where the censored label and survival times are permuted and the whole analysis is repeated ( search of the best cutpoint and Cox regression with the binary variable )

Use of data from ROC curve


Manipular Date no ASP.NET

Question: Estou começando a aprender ASP.NET e não consigo achar solução para o caso abaixo:
Tenho uma instância do DateTime onde eu faço a conversão para o formato "ddMMyyyy" usando o ParseExact(), pra mostrar a data sem máscara. O problema é que no Oracle esse campo não é DATETIME, é só DATE. Quando rodo o programa, recebo o erro "A cadeia de caracteres não foi reconhecida como valor DateTime válido."
Não encontrei nenhum objeto só do tipo Date no ASP.NET pra usar. Alguem tem ideia de como posso resolver isso? Não queria ter que alterar o tipo do campo na tabela.
Segue o trecho do código:
else if (field.TYPECODE == 4)
                        {
                            DateTime _date = DateTime.ParseExact(field.VALUE, "ddMMyyyy", CultureInfo.InvariantCulture);

                            field.VALUE = JsonConvert.SerializeObject(_date);
                        }

Answer: O que está acontecendo é que você inicialmente tem essa data em string, provavelmente recebida por input, porém por algum motivo você precisa trabalhar com ela deserializada em DateTime, para isso você está dando parse.
O problema está exatamente aí, a api do ParseExact pede para você o valor a ser parseado, porém ele precisa saber como fazer isso para que possa trabalhar, no caso o formato.
Para que o parse ocorra, o formato que a data em string esta tem que corresponder exatamente com o do formato informado, senão ele não vai conseguir realizar, pois não saberá o formato correto e como trabalhar.
Quando isso acontece, ele lança uma exceção com a seguinte característica:

FormatException: s does not contain a date and time that corresponds to the pattern specified in format.

Vamos para um exemplo errado e correto:
Errado:
    ...
    field.VALUE = "10/10/2020";
    var _date = DateTime.ParseExact(field.VALUE, "ddMMyyyy", CultureInfo.InvariantCulture);

Ira falhar, pois o formatado da data não ira corresponder a informada para ele parsear.
-
Certo:
    ...
    field.VALUE = "10102020";
    var _date = DateTime.ParseExact(field.VALUE, "ddMMyyyy", CultureInfo.InvariantCulture);

Ira retornar a data serializada em DateTime, pois o formatado da data corresponde
com o formato informado para ele parsear.
Então o seu problema esta na diferença do formato da data recebida com o qual você quer que o parser utilize para deserializar.
Para aprofundamento sobre a api do mesmo, acesse a documentação.
Abraços.

Manipular Date no ASP.NET


solve Equations with Modulus(%)

Question: I have been working on this for a while now and not seem to solve this equation. The part that tripping me off is the mod. How do I take it to the other side so I can solve for $x$.
Suppose: $X = 10, a=20, z=30$, how to solve for smaller $x$.
$X=a^x \bmod z$
I tried using logs but answer is wrong. Could someone please guide me on how to do this?
Comment: You want to solve $10=20^{x}\pmod{30}$. This means that $20^x-10=30k$ for some integer $k$. That's the meaning of the $\pmod{30}$ notation. But $20^{x}-10=(30-10)^x-10=(-10)^x-10+30K$ for some integer $K$. If you put $x=1$ you get $(-10)^x-10=-20$, which is not divisible by $30$. But if you put $x=2$, you get $(-10)^x-10=100-10=90=3\times 30$.
Answer: Hint:
 Calculating the first powers of $20$ mod.$30$, you can conjecture (and prove) that
$$20^n\equiv 20\quad\text{if $n$ is odd}, \qquad 20^n\equiv 10\quad\text{if $n$ is even.} $$
Answer: $x$ is even is a solution.
 $10\equiv20^x(mod30)$
10,20,30 all are divisible by 10
 $10\equiv 1(mod3)$
$20^x\equiv2^x(mod 3)$
But 30 is a multiple of 3
Therefore $20^x\equiv1(mod 3)$
 This is possible for $x$ is even

solve Equations with Modulus(%)


In function `_start': init.c:(.text+0x30): undefined reference to `main'

Question: I'm working on a C project with around 30 source files (.c). I'm building this project on a 32 bit micro-controller(i.MX515) running on Ubuntu using GNU tools.
The compilation phase completes successfully, however when the linking process starts I get this error (For full error at the end of the quesiton):
In function `_start': init.c:(.text+0x30): undefined reference to `main'

I have a main() function which does a simple printf().
My Makefile line for linking, looks like this.
final: $(OBJDIR)/main.o $(OBJDIR)/TchClaKnn_BuildKdtreeInt.o $(OBJDIR)/TchClaKnn_FreeKdtreeInt.o.... (Go upto 30 files like this)
    @echo ".Linking"
    $(CC) $(LFLAGS) -o $(OBJDIR)/main.o $(OBJDIR)/TchClaKnn_BuildKdtreeInt.o $(OBJDIR)/TchClaKnn_FreeKdtreeInt.o..... (Go upto 30 files like this)

Help!!!
Regards
Vikram

Complete linking error
/usr/lib/gcc/arm-linux-gnueabi/4.3.3/../../../crt1.o: In function `_start':
init.c:(.text+0x30): undefined reference to `main'
collect2: ld returned 1 exit status
make[1]: *** [final] Error 1
make[1]: Leaving directory `/home/ubuntu/Documents/Project/IMX_Project_v1'
make: *** [all] Error 2

Comment: Is main() in main.c (compiled to main.o) ?
Answer: final depends on main.o (and a bunch of others), but, your makefile is taking all the 'others' and outputting them in main.o (that's what -o does in most compilers)
edit your link line to : -o final $(OBJDIR)/main.o
Comment: Hi Kevin, YES!!! My makefile was erroneous, I introduced what you suggested and it worked. I do this mistake quite often, when I went through one of my very old makefile I see that I had - "$(CC) $(LFLAGS) -o $@" in the linking command line. Well, in both the cases the final gets generated. Thank you!!!
Comment: You're welcome, it's why another set of eyes almost always finds the problem right away - they don't know what to 'skip over' ;)
Answer: The linker cannot find the object code for the source that has main() defined in it. Probably its not getting compiled. Check that whichever of the 30 files it is that has main() in it, is getting compiled to .OBJ.
Comment: Hi RM, yes you were right. The object file for my main.c was not getting generated, because I had a mistake in my makefile I fixed it and now my final is getting generated. Thank you!!!


Determining the standard error of a ratio of means

Question: I hope that this request will make sense. I am not extremely proficient in these kinds of stats, so please also excuse my limited vocabulary.
I have two datasets, we'll call A and B, and for each dataset I am calculating a statistic that is the ratio of two means, i.e. $\%_A=\bar{x}_A/\bar{y}_A$ and  $\%_B=\bar{x}_B/\bar{y}_B$. What I want to figure out is whether the ratio for dataset A is statistically distinguishable from the ratio for dataset B (that is, looking at the ratios visually, they seem to be different, but can I actually say with any confidence that they are different based on the number of observations I have for each dataset?).
My understanding is that if I calculated the error for each mean, I could simply look to see if the error bars overlap - if they don't overlap then the difference might be real, but if they do overlap then I can't say if the difference is real or not. I would normally determine error by simply calculating standard error iof the mean (STDDEV/SQRT(num_obs) ), but I do not know how, or if, standard error would propogate when taking the ratio of two means this way.
Perhaps I am taking completely the wrong approach. I would appreciate any guidance you can offer.
Comment: The relationship between datasets is important. Are the independent (for example, A for male, B for female) or dependent (such as A for year 2018 and B for year 2019 from the same people)?
Comment: If you have the data, you can perform a bootstrap test.
Comment: @Noah, I do have the data the means are based on. Would you mind elaborating on performing a boostrap test, or do you have any resources I could turn to? I am familiar with the concept of bootstrapping, but not how to apply it here.
Comment: @user158565, I believe the datasets are independent, (the same observations being made in two different US States).
Comment: To bootstrap: draw sample with replacement from your data and compute the relevant statistic (e.g., the difference between the ratios). Do this ~1000 times. The 2.5th and 97.5th percentiles of the distribution of computed statistics are a confidence interval for the original estimate. If the interval excludes the null value of the statistic, you can reject the null hypothesis that the ratios are equal in the population.
Answer: You could set up your data in the following way: have a variable, $Z$, be your outcome variable, and have two columns, $X$ and $A$. Column $X$ is equal to 1 if the observation is in group $X$ and 0 otherwise, and Column $A$ is equal to 1 if the observation is in group $A$ and 0 otherwise.
You can run a generalized linear model with a log link, as follows:
$$log(\mu_{Z|X,A}) = \beta_0 + \beta_1 X + \beta_2 A + \beta_3 XA$$
which is equivalent to
$$\mu_{Z|X,A} = e^{\beta_0 + \beta_1 X + \beta_2 A + \beta_3 XA}$$
$ \mu_{Z|X=1, A=1}$ is the same thing as $\bar{x}_A$, $\mu_{Z|X=0, A=1}$ is the same thing as $\bar{y}_A$, and so on. So, we can rewrite the means in terms of the coefficients form this model:
\begin{align}\bar{x}_A &= e^{\beta_0 + \beta_1 + \beta_2 + \beta_3}\\
\bar{x}_B &= e^{\beta_0 + \beta_1}\\
\bar{y}_A &= e^{\beta_0 + \beta_2}\\
\bar{y}_B &= e^{\beta_0} \end{align}
So, we can reexpress the ratios of these means as ratios of the coefficients:
\begin{align} \frac{\bar{x}_A}{\bar{y}_A}&=\frac{e^{\beta_0 + \beta_1 + \beta_2 + \beta_3}}{e^{\beta_0 + \beta_2}}=e^{\beta_1 + \beta_3}\\
\frac{\bar{x}_B}{\bar{y}_B}&=\frac{e^{\beta_0 + \beta_1}}{e^{\beta_0}}=e^{\beta_1} \end{align}
So, testing $\frac{\bar{x}_A}{\bar{y}_A}=\frac{\bar{x}_B}{\bar{y}_B}$ is equivalent to testing if $e^{\beta_1 + \beta_3}=e^{\beta_1}$, which is equivalent to testing whether $e^{\beta_3}=1$ or $\beta_3=0$. This is a test that is given in the model output and doesn't require any additional calculation.
If all four means come from independent observations, this will work as written. If there is dependence among some units (e.g., all each unit in the sample has both an $x$ and a $y$ value), add an extra column for unit ID and add that as a cluster and use a cluster-robust standard error.


Multiple Linear Regression using interactive terms in python

Question: I am predicting a model using interactive terms:
est = smf.ols(formula='mdvis ~ hlthp * logincome', data=df).fit().

I get pretty good score when used with linear regression around 97%- R square.
So, my question is:
While predicting using interactive terms, how to evaluate by using the test/train data and also calculate stats significance using cross validation?
Answer: Using interaction terms is only an easy way to build the exog matrices for the regression. It doesn't change the logic of the cross validation.
Split your dataframe into train and test samples :
train = df.sample(frac=0.8)
test  = df.drop(train.index)

Then fit the model on the train data :
res = smf.ols(formula='mdvis ~ hlthp * logincome', data=train).fit()

Predict on the whole data (train and test)
df['predict']=res.predict(exog=df)
df['delta']  = df['predict']-df['mdvis']

Finaly make statistics on each train and test sample separated as needed (here I calculate standard deviations on the residuals) :
std_train=df.loc[train.index]['delta'].std()
std_test =df.loc[test.index]['delta'].std()

Comment: Thank you for answering
Comment: Just a quick question if this df/train/test dataframes should include 'mdvis' or to be removed.
Comment: No, you can keep it.
Comment: How can i to check out residuals and their statistical patterns and normal distribution?


Dynamics crm + plugin logic to update zero values

Question: I need to perform the sum of each field across multiple records of the same entity and update the values on the same entity. Along with this I also need to store its formula.
AttributeList = { "price ", "quantity", "contact.revenue", "opportunity.sales"}

Below is the logic
foreach (var attribute in attributeList)
{
    Decimal fieldSum = 0;
    string computedNote = string.Empty;
    foreach (var entity in mainEntityList)
    {
        if (entity.Contains(attribute))
        {
            if (entity.Attributes[attribute] != null)
            {
                string type = entity.Attributes[attribute].GetType().Name;
                Decimal attrValue = 0;

                if (type == "AliasedValue")
                {
                    AliasedValue aliasedFieldValue = (entity.GetAttributeValue<AliasedValue>(attribute));
                    attrValue = aliasedFieldValue.Value.GetType().Name == "Decimal" ? (Decimal)aliasedFieldValue.Value : (Int32)aliasedFieldValue.Value;
                }
                else
                {
                    attrValue = entity.Attributes[attribute].GetType().Name == "Decimal" ? entity.GetAttributeValue<Decimal>(attribute) : entity.GetAttributeValue<Int32>(attribute);
                }
                fieldSum += attrValue;
                computedNote += $"+{Convert.ToInt32(attrValue).ToString()}";

            }
        }
        else
        {
            computedNote += $"+0";
        }
    }
    Entity formula = new Entity("formula");
    if (fieldSum != 0)
    {
        if (attribute.Contains("opportunity"))
        {
            opportunity[attributeName] = fieldSum;
            entityName = Opportunity.EntityLogicalName;
            attributeName = attribute;
            recordId = Id;

        }
        else if (attribute.Contains("contact"))
        {
            contact[attributeName] = fieldSum;
            entityName = Contact.EntityLogicalName;
            attributeName = attribute;
            recordId = Id;

        }
        else
        {
            mainentity[attribute] = fieldSum;
            entityName = mainEntity.EntityLogicalName;
            attributeName = attribute;
            recordId = Id;

        }

      formula.Attributes["ice_entity"] = entityName;
      formula.Attributes["ice_attribute"] = attributeName;
      formula.Attributes[entityName + "id"] = new EntityReference(entityName, recordId);
      formula.Attributes["ice_computednote"] = computedNote.Remove(0, 1);
        requestsCollection.Entities.Add(formula);
    }
}

requestsCollection.Entities.Add(opportunity);
requestsCollection.Entities.Add(contact);
requestsCollection.Entities.Add(mainentity);

Values in both records could be as follows
Record 1
Price = 500
Quantity = 25
Revenue = 100
Sales = 10000
Volume = 0

Record 2
Price = 200
Quantity = 10
Revenue = 100
Sales = -10000
Volume = 0

Record 3 (Values after calculation that are to be updated in the third entity and Formula to be stored mentioned in brackets)
Price = 700 Formula = (500+200)
Quantity = 35 Formula = (25+10)
Revenue = 200 Formula =(100+100)
Sales = 0 Formula =(10000 + (-10000))
Volume = 0 No Formula to be created

I am checking if the fieldsum is not equal to zero (to update both positive and negative values) and then updating the values in the respective entity. However for values that became zero after the calculation. I also need to update them and create formula for the same. Avoiding the values that were zero by default.
As shown in above example, I want to update sales field value and create formula record for the same as '10000+-10000' but do not want volume field value to be updated or the formula to be created for it. How can i embed this logic in my code?
Answer: Add a flag (updateFormula) to indicate whether checksum and formula required to update in related entities. Then, instead of checking fieldSum != 0, check updateFormula is true to update the related records.
attributeList = { "price", "quantity", "contact.revenue", "opportunity.sales"}
    foreach (var attribute in attributeList)
    {
        Decimal fieldSum = 0;
        string computedNote = string.Empty;
        bool updateFormula = false;
        foreach (var entity in mainEntityList)
        {
            if (entity.Contains(attribute))
            {
                if (entity.Attributes[attribute] != null)
                {
                    string type = entity.Attributes[attribute].GetType().Name;
                    Decimal attrValue = 0;

                    if (type == "AliasedValue")
                    {
                        AliasedValue aliasedFieldValue = (entity.GetAttributeValue<AliasedValue>(attribute));
                        attrValue = aliasedFieldValue.Value.GetType().Name == "Decimal" ? (Decimal)aliasedFieldValue.Value : (Int32)aliasedFieldValue.Value;
                    }
                    else
                    {
                        attrValue = entity.Attributes[attribute].GetType().Name == "Decimal" ? entity.GetAttributeValue<Decimal>(attribute) : entity.GetAttributeValue<Int32>(attribute);
                    }
                    fieldSum += attrValue;
                    computedNote += Convert.ToInt32(attrValue).ToString();
                    updateFormula = true;
                }
            }
            else
            {
                computedNote += 0;
            }
        }
        Entity formula = new Entity("formula");
        if (updateFormula)
        {
          // Logic to update formula and checksum
        }
    }

Comment: hey thank you for your help. Really appreciate it


Can I modify the type of an object in python

Question: specifically I want to change a StringType to a NoneType. I know how to use int() and str()
to convert between IntType and StringType, but I can't find a similar solution for NoneType. Is there a simpler solution besides using built in functions like int and str?
Sorry that was very ambiguous, I have a program that enters the string 'print("check")' into the python shell and I need it converted to a function. I assumed that because functions have the type NoneType that simply converting the string to NoneType would make it usable. Any ideas?
eval() works perfectly for my purposes Cairnarvon, thanks!
Comment: How could you convert a variable to be `NoneType`? There is only one `None`- it's not like "hello" converted to `None` would be different than "goodbye" converted to `None`.
Comment: There's only one (sane) value of `NoneType`, which is `None`. The only result of that conversion can be `None` itself, so just use that value directly.
Comment: Are you looking to convert the string `"None"` to `None`?  Have a look at `ast.literal_eval()` then.  Otherwise clarify your question.
Comment: what is the usecase ?
Comment: Also, `str(None) == 'None'` but to go backwards you have to use @Alok's comment.
Answer: If you want to remove a variable then just delete it.
>>> a = 10
>>> print a
10
>>> del a
>>> print a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined

If you want your variable to be None then just assign None to it.
>>> a = 10
>>> print a
10
>>> type(a)
<type 'int'>
>>> a = None
>>> print a
None
>>> type(a)
<type 'NoneType'>

Hope this helps.
Answer: You can trivially define your own function to do this:
def none(*args):
    """Converts any arguments to None."""
    return None

But that's pretty pointless. Just use a literal None whenever you need one.

As for your clarification, what you're looking for is probably eval or the ast module, though you should seriously consider what you're hoping to accomplish; eval, in particular, will create more problems for you than it is likely to solve.


What is the correct term for referring to a path and filename?

Question: I want to use the correct term to make my API as intuitive as possible, so when a parameter is expected to be a full path and filename (ex "C:\Users\Max\Documents\MyDocument.txt") what is the correct term?

filename - that would just be MyDocument.txt, right?
path - that would just be C:\Users\Max\Documents, right?

What should I use for the parameter name? Would "file" be the appropriate name?
I feel kind of dumb asking this, but I want to make sure it's right.
Comment: +1 - I like that you're taking the time to make your API intuitive.
Comment: +1... if you're using Java or C# you can always punt and then javadoc it.
Comment: i would reuse the term from java.io.File: absoluteFilePath
Answer: My suggestion would be "Absolute file path" for some path pointing to a file, where as i would use "Absolute directory path" for a path pointing to a directory
In case of relative paths the change should be obvious.
If nothing else, you can always make a section in your documentation where you describe the meaning of certain terms you use.
Answer: The correct term is "Fully Qualified Name" (sometimes "FQN").
The term you should use in your API is "QualifiedName" or "QualifiedFilename"
Wikipedia has an entry for "Fully qualified file name" and defines it as "a file on a computer whose exact name is completely specified such that it is unambiguous and cannot be mistaken for any other file on that system."
Comment: Really? I've heard of FQDN for domain names, but never for files. Show me a piece of code in actual use somewhere that uses the term QualifiedName or QualifiedFilename.
Comment: I wonder how many programmers would balk at that because of the "Qualified" and the answer makes me sad.
Comment: Something in the back of my head says there's a Java API call for 'getQualifiedName' but I'm not recalling which class off the top of my head.
Comment: Even money says that getQualifiedName referred to a class and not a file.
Comment: Google suggests you are thinking of XML node names, when dealing with namespaces.
Comment: OK, I concur that Java's use of "Qualified Name" is with respect to classes. And certainly, "qualified" refers to XML node names and domain names. But, Wikipedia does have that entry on "Fully qualified file name" and it seems to fit the need expressed by the original question.
Comment: I've unaccepted the answer for now hoping for more discussion, but I think this is probably the correct answer. Wikipedia does concur with David and it does make sense. If nothing else, I think it's definitely intuitive.
Comment: +1. I've used the term fully qualified in reference to file names (as distinct from domains) for a great many years. Can't remember where I first heard it, but my programming history pre-dates the internet.
Comment: @Bob what exactly do you call the parameter for fully qualified file name? qualifiedFileName like David suggests? or actually fullyQualifiedFileName?
Answer: A term often overused for this is URI, though your example isn't really one of those. I think you'll be perfectly clear if you just use "filepath" or "pathname."
For example, Java's file object uses "pathname" as the parameter name for the constructor on their File object.
Answer: Usually path is the full C:\Users\Max\Documents\MyDocument.txt while the C:\Users\Max\Documents\ part is usually known as the base directory or just directory.
You'll see in a lot of example code people write: C:\path\to\the\document.txt
Answer: I'd go with fullPath like you said path would be C:\Users\Max\Documents but reading fullPath would suggest path + filename.
Answer: I don't think there is One True Answer, maybe some consensus, but that's all we can hope for. I usually try to follow the conventions of the library I'm using (e.g., Cocoa, Java, or PHP). If I've got nothing to go by, I'd say:

File: the abstract thing being referred to by a name: the file handle
Path: a string indicating the location of a file or directory, either absolute or relative: /Users/Max/Documents/FooBar, ../Sibling/Zardoz
Name: the name of the file or directory, without location: FooBar, Zardoz, Documents
Answer: One easier solution you may have considered already is telling the consumer of the API what is expected in the XML documentation, which will also appear in Visual Studio intellisense if your compile the assembly with documentation, and distribute the .xml file.
///
/// Saves the provided file to disk.
///
/// <param name="filePath">The full path, including the filename of the file.</param>
public void SaveFile(string filePath)
{

}


How do you count many bars of silence (rests)?

Question: Playing in a jazz band there are often 5, 6, or 8 bars of silence. This is no problem as I can count them on my fingers. But how do I count larger rests, for example 52, 112, or even longer rests, as in classical pieces?
What techniques do you have to count a large numbers of silent bars?
Comment: Does this answer your question? [Counting long rests in music](https://music.stackexchange.com/questions/70274/counting-long-rests-in-music)
Answer: In an orchestral situation, it is a terrible idea to rely on the conductor - they may not be able to cue you or instead are going to give a more important cue.  Just because you are not playing does not mean you're allowed to sit and wait for a bus.  Scores that have been edited well will have "cues" written in the parts, so, say you zone out accidentally or lose your place after 200 measures, you see the cue for an oboe solo in your part and you know where you are.
Also, here are a couple good habits to get into:

raise a finger or flick your leg each time you get to a rehearsal mark - this is a great way to keep a section together (trombones in Mahler, for example.)
when counting measures, give one number to the entire measure, and take the measure's duration to say the number to yourself.  Ex: Ooonnnnneeeee  Twwwooooooo  Threeeeee  etc etc.  Counting this way greatly reduces counting confusion.
Like others have mentioned - listen to others around you; know what they are doing.  Just like in a play, it's good to know everyone's lines around your lines so that if someone else screws up you're still good to go.
Comment: I find it easier to count "one,two,three; two,two,three; three,two,three,..." to keep track of both the beat and the measure count.
Comment: @CarlWitthoft - that type of counting is better than others, but quickly becomes impractical with fast tempi, asymmetrical time signatures, or large spans of rests.  It also increases the chance of getting verbally tripped up by having to keep track of so many numbers.
Comment: Well, sure, just count once per Presto measure; and if you've got varying time sigs then just restart the count.  Maybe it's 'cause I'm in that group of (musician && mathematician) that big numbers don't bother me :-)
Answer: Adding to Dom's answer,  the key is often in listening for cues in other people.   Find out what other parts are doing around the time you come back in and before,  so you can listen for that sign that you're about to come back in.
Answer: You don't actually have to count every bar that you don't play especially if you go many bars without playing anything. Most large form pieces and even Jazz pieces are broken down into smaller parts i.e. an A section, a B section, C section, ect. So you could have sections  A, B, and C be 32 bars each and you many not start playing until 4 bars into section C and instead of just counting 68 bars you could listen for the start of the C section and then count 4 bars.
If you know the song inside and out you may not even need to count the 4 bars you may just be able to "feel" when you come in.
Also the conductor in an orchestra will cue the instruments coming in as it is what they do.
Comment: Don't rely on the conductor.  He MAY assist you at the moment you start playing.  He almost certainly won't give you a "pick your instrument up now" warning a few bars earlier.  Your entry may be part of a tutti section where everyone plays after a lightly-scored passage.  You won't get an individual cue, and there may have been previous tuttis not involving you, during your long rest.
Answer: In an orchestra, let the conductor do the work for you - they should let you know your moment is coming.
In a smaller group, say a string quartet, you wouldn't expect such long rests (after all, you're 25% of the ensemble) - but learn what the other parts sound like and use that to time your return. So instead of "Now I count 64 bars", it's "I'll come back in after the third repetition of the main melody".
Comment: Part one is badbadbad, see jjmusicnotes' answer.  Part two is good for any ensemble: if there aren't cuenotes in your part, go ahead and write them in.
Answer: I count bars 1-2-3-4  2-2-3-4  3-2-3-4 etc. in my head and simultaneously keep track on my fingers. On one hand, each finger denotes 1, the thumb denotes 5, so I can count up to nine on one hand. So with two hands I can keep count up to 99. Major benefit of this is that I can multi-task - I keep counting whilst picking up mutes, pointing at music and so on. After a while you can preset a count, so if the conductor says start at bar 8 you put down thumb and three fingers and start counting from there.
One advantage of designating fingers as 1 and thumb as 5 over binary is that it's much easier to preload a count on your fingers. The disadvantage is that you can only count up to 100 on two hands, rather than 1000...
So say the conductor says "we're going from bar 67" and you have an entry at bar 80, you just preload 67 onto your fingers and start counting bars. Compare this with having to preload 67 in binary onto your fingers.
Answer: Back in my orchestra days I played oboe, so I often had long rests.  Until you know when to come in based on what's happening in the other parts, as others have already said, you need to count bars of rest.  I used to count on my fingers, but in binary, from left thumb to right thumb.  That way, you can count to 2^10 or 1024, which is probably enough for most pieces.  It starts like this:
(all fingers are in except those noted)
1- left thumb;
2- left index;
3- left thumb and index;
4- left middle;
5- left thumb and middle;
6- left index and middle;
7- left thumb, index, and middle;
8- left ring;
etc. It's fun and easy to learn.
Comment: You are never going to have to count beyond 1000.  Rarely beyond 100.  There will be a rehearsal letter or other marker long before that number of bars is reached.
Comment: @LaurencePayne- yes, I realize that.  In practice, I rarely needed more than one hand, which got me up to 2^5 or 32.  But the method does work and it's fun.
Comment: Just enjoyed learning how to count in binary on my fingers, but realized that you exaggerated by 1-- ten fingers only counts to 1023 -- then you'd need an 11th finger... would come in handy paying the oboe!  More realistically 5 fingers counts to 31 so you could pretty quickly need two hands.
Comment: @StephanLuis- Zero fingers is 1024.
Answer: I also recommend counting in the way Brian THOMAS has explained (1-2-3-4-2-2-3-4). However as mentioned this gets really complicated with 20+ bars rest.
Now from my experience with sheet music in orchestras you often already have long rests seperated whenever the key, general theme or athmosphere changes or new instrumental groups are introduced. Try to pay attention to such separations and listen to the music. Try to listen to the piece and figure out what happens at those seperations and use them as markers. Generally listening to the piece you play a couple of times is a good idea. I've had some long rests in certain pieces that were really hard to count but after listening to the music for a while I memorized my entranced by heart.
If your sheet doesn't have any seperations during long rests (or has seperations that don't make any sense) then make them yourself. I usually look at the sheets of other instruments that I can visually see or hear well and when they suddenly start playing I mark their entrance in my rest. Solos also work great for this.
What also helps is looking for fermatas. These are often really easy to hear and are a great means of orientation.
Answer: I have a fool-proof way of counting up to 100 using just my two hands:
Right hand: count 1 - 5 by tapping one thumb/finger at a time on any surface (?leg?); count 6-10 by keeping thumbs and fingers down, ie:
1 = thumb
2 = index
3 = middle
4 = ring
5 = pinky
6 = thumb + pinky
7 = thumb + index
8 = thumb + index + middle
9 = thumb + index + middle + ring
10 = thumb + index + middle + ring + pinky

at which point, start counting "10s" in the left hand, using the same scheme:
11 - 20 = left thumb + one of the above in the right hand
21 - 3- = left index, + ...

100 = all fingers in both hands down, start again if necessary!
Answer: As a trombonist, I often had VERY long sections of rest.  Obviously I'm not going to sit there counting "one-two-three-four, two-two-three-four.....six-hundred-and-seventy-three-two-three-four...  The composer or copyist must supply me with landmarks, including a prominent cue played by another instrument a few bars before my entry.   Previous players of the part might leave me further pencilled-in information like "time for two pints here!".


Verificar continencia lista python

Question: Gostaria de ajuda com um código.
lista1 = [5, 6, 7]
lista2 = [4, 'a', 9, 5, 6, 7]

Verificar se a lista1 (a lista toda) está contida em lista2
e se
lista2 = [4, 9, 5, 'a', 6, 7]

fazer a mesma verificação, mas agora é negativo.
Answer: Crie dois set's (conjunto de elementos sem repetições) e use o método issubset.
lista1 = [5, 6, 7]
lista2 = [4, 'a', 9, 5, 6, 7]

set1 = set(lista1)
set2 = set(lista2)

if(set1.issubset(set2)):
    print('lista1 está contida em lista2')
else:
    print('lista1 não está contida em lista2')

Veja funcionando no repl.it.
Comment: Mas quando eu substituo lista2 = [4, 9, 5, 'a', 6, 7], continua dizendo que a lista pertence e não deveria.
Comment: @fnetto Deveria sim, ora. Ainda tem 5, 6, 7 na lista.
Comment: Pelo comentário, acredito que ele queira que a verificação seja se o conteúdo da lista1 está na lista2 na mesma sequência
Comment: Pois é, @Fabiano. Mas eu precisaria ter certeza pra responder sobre.
Answer: Sobre verificar se todos os elementos da lista 1 estão contidos na lista 2, você pode criar um for para andar por todos os elementos da lista 1 e usar um in para analisar se eles estão na lista 2, caso eles não estejam, você pode sinalizar.
Da uma olhada nesse código
#-*- coding:utf-8 -*-

# Listas que serão comparadas
lista1 = [1,2,3,4]
lista2 = [1,2,3,4,5]

# Variável de referência
estaContido = 1

# Vamos andar por todos os elementos da lista 1
for n in lista1:
 # Se o elemento N da lista 1 estiver contido na Lista 2
 if n in lista2:
  # Passe direto
  pass
 # Se não(Algum elemento da lista 1 não está contido na lista 2)
 else:
  # Mudamos o valor da referência
  estaContido = 0

# Se todos os elementos da lista 1 estavam contidos na lista 2
if estaContido == 1:
 print("Lista 1 está contido na lista 2")
else:
 print("Lista 1 NÃO está contida na lista 2")

Verificar continencia lista python


Analise de Dados com python

Question: Eu tenho um arquivo cvs com duas colunas, uma de mes (Janeiro, fevereiro, etc) e outra com valor(relativo a cada mês), e quero criar um gráfico(de barras por exemplo), mas dá o seguinte erro: "TypeError: Empty 'DataFrame': no numeric data to plot"
Arquivo:

Segue meu código (estou usando Jupyter):
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('ggplot')

licitacoes = pd.read_csv("licitacoes.csv")

licitacoes.plot(kind='bar', x='Mes', y='valor')
plt.title('Valores por mes')
plt.xlabel('Mes')
plt.ylabel('valor')
plt.show()

Comment: Você poderia, por favor, colocar um trecho do arquivo para que nós possamos analisar? E se possível, uma parte maior do código, desde a leitura do conjunto de dados
Comment: Coloquei o resto do código e o arquivo
Answer: Aparentemente o pandas não está reconhecendo a segunda coluna como dado numérico.
Supondo que o pandas deve reconhecer o "." (ponto) como separador decimal, ao invés da vírgula, talvez você só precise informar a formatação correta dos seus números ao fazer a importação.
Não sou um grande conhecedor de Pandas, mas na documentação do método read_csv existe um parâmetro decimalstr que pode ser usado para configurar qual o caractere será usado como separador decimal.

decimalstr, default '.'
Character to recognize as decimal point (e.g. use ',' for European data).

Teoricamente bastaria importar usando:
licitacoes = pd.read_csv("licitacoes.csv", decimalstr=",")

E o pandas reconheceria automaticamente como dados decimais.
Answer: Tente isto antes de plotar novamente:
licitacoes.valor = licitacoes.valor.astype(float)

Edit:As variáveis da coluna 'valor' estão como strings, para plotar o gráfico você precisa de um valor numérico, ou seja, int ou float. O outro erro que aconteceu depois de tentar executar o código acima é devido ao Python não conseguir transformar o valor das strings em float, devido a linguagem usar o ponto para decimais. Para resolver o resto das questões sobre o uso de virgulas, recomendo olhar a pergunta que já foi feita neste fórum:
https://pt.stackoverflow.com/questions/221876/como-usar-vírgula-em-python-em-vez-de-ponto/222098#222098
Espero ter conseguido te ajudar em algo :)
Comment: Deu o seguinte erro: invalid literal for float(): 3235405819,22
Comment: O que acontece se você formatar o arquivo e trocar as vírgulas da coluna "valor" por pontos?

Analise de Dados com python


Separate frontpage per domain?

Question: I have two sites, built in tanden but launched at completely separate points.
Both of them need access all content from both sites in some form, so that for example auto-completing references can be used across the two sites. For sake of brevity, I suggest exactly how that is done is kept out of this question.
The real difference between the sites, is that

One domain shows content types W and X, while the other domain shows Y and Z, they
Each domain has a completely separate front page.

How would you go about solving the above two problems?
Comment: I'm posting my own initial suggestion below, but I would like to hear about others.
Answer: In my mind, the big advantage of using Panels is so that you can extend/alter sites like this in the future, without needing a lot of rework.  In a lot of ways, Panels provides a framework for futureproofing sites.
While I am not sure if I have used Domain CTools,that is the first approach I would take.  I essentially use a similar approach using Mobile Tools in combination with Domain Access for providing split desktop/mobile sites that share some, but not all, content and features.
The access rules that Domain CTools provides will show up in the visibility and selection rules inside Panels.
For the node pages, I would enable the default node override page inside Panels, and then make variants for each of my content types.  I would then assign access rules to each, based on the domain.
For the home page, I would make a new custom page and set it as the home page.  I would then make two variants, and make a selection rule based on the domain for each.
The other thing to think about is how nodes get used in places other than the node view page.  For example, if you should double check your views and add access controls as needed.  Assuming the approach outline above, you could also use the Domain CTools access rules.  Depending on what other uses there are, you may need to investigate whether you need a custom hook_node_access() for your site.
Comment: Sorry for essentially the dup answer, but there was more to address than a comment would allow.
Comment: No problem, +1 :) FYI, Ctools has access plugins, Panels calls them either selection rules or visibility rules depending on where you use them, but they are all the same thing. :)
Comment: @Letharion, thanks.  I always get the ctools/panels/views terminology get mixed up.
Answer: One answer, requiring Panels (Everywhere), is to use an access plugin on content types as well as the site template and <front>, to provide varying experience depending on the domain.
There appears to exist a plugin called Domain ctools which provides this functionality.

Separate frontpage per domain?


Declaring static const variables in functions

Question: If declaring static variables inside functions is an error then why declaring implicitly static const variables in functions not an error in c#
class Hello{
   public void hello(){
       static int h;  //error
   }
}

class Hello{
   public void hello(){
       const int h=33;   //const implicitly static
   }
}

Comment: There's a lengthy discussion of why C# doesn't support static variables inside functions [here](https://blogs.msdn.microsoft.com/csharpfaq/2004/05/11/why-doesnt-c-support-static-method-variables/).
Comment: `static` variables in functions are not allowed. `const` variables are. `const` variables are not "implicitly static" except in your imagination, because `static` variables in functions are not allowed. You're looking at this through C-colored glasses.
Answer: I assume you mean something like
void Main()
{
  const int c = 1;

  Console.WriteLine (c == 1);
}

Which is legal because it limits the scope of c to that function.  All the compiler does with the constant local is replace all instances of that reference with the constant value.  So if you decompile the code you'll see:
void Main()
{
  Console.WriteLine (1 == 1);
}

There is no such thing as static locals in C#.  Static locals in C++ are local variables that retain their values across calls to that method.  In C# you'd use a static member instead.  Constant class members are implicitly static because there's no reason to make them instance properties.  But that doesn't mean that const varaibles are "static" in the same sense.
Answer: You can use static variables inside your main method (or any other method), but you need to declare them in the class:
This is totally fine:
public Class YourClass
{
  static int anyNumber = 5;

  static void main(String[] args)
  {
    Console.WriteLine(anyNumber);
  }
}

This is fine too, but in this case, anyNumber is a local variable, not a static one.
public Class YourClass
{

  static void main(String[] args)
  {
    int anyNumber = 5;
    Console.WriteLine(anyNumber);
  }
}


The difference of cubed diffrence of Wiener processes

Question: Problem
I need to calculate the limit of $X_n$ in mean squared when $n$ tends to infinity. $X_n$ is given as
$$X_n = \sum_{i=1}^n (W_{ti/n} - W_{t(i-1)/n})^3$$
where $W$ is Wiener process.
My attempt
If we prove that $E(X_n) = 0$ and $Var(X_n) \to 0$, we are done.
However, I get stuck at the very beginning when I try to calculate the expectation.
Issues
If we denote $W_{ti/n}$ as $Y_i$, I struggle evaluating $E(Y_i^2Y_{i-1})$ after rising the difference to cube. Even though I showed that $\sum_{i=1}^n Y_i \text{ and } \sum_{i=1}^n Y_{i-1}$ are almost the same with the exception of $Y_n$ and $Y_0$, I don't know how to get that $0$.
Answer: Use the fact that $Y_i-Y_{i-1}$ is independent of $Y_{i-1}$ and $\mathsf{E}Y_i^k=0$ for odd $k$, i.e.,
\begin{align}
\mathsf{E}Y_i^2Y_{i-1}&=\mathsf{E}[(Y_i-Y_{i-1})^2Y_{i-1}]+2\mathsf{E}[(Y_i-Y_{i-1})Y_{i-1}^2]+\mathsf{E}Y_{i-1}^3 \\
&=\mathsf{E}[(Y_i-Y_{i-1})^2]\mathsf{E}Y_{i-1}+2\mathsf{E}[Y_i-Y_{i-1}]\mathsf{E}Y_{i-1}^2+\mathsf{E}Y_{i-1}^3=0.
\end{align}

Alternatively, notice that $Z_i:=Y_i-Y_{i-1}\sim N(0,t/n)$ so that $\mathsf{E}Z_i^k=0$ for odd $k$, which implies that $\mathsf{E}X_n=\sum_{i=1}^n\mathsf{E}Z_i^3=0$. Next, since the increments of $(W_t)$ are independent,
$$
\operatorname{Var}(X_n)=\sum_{i=1}^n \mathsf{E}Z_i^6=5!!\cdot\sum_{i=1}^n \left(\frac{t}{n}\right)^3=\frac{15 t^3}{n^2}.
$$


Subqueries In The Select Clause

Question: I am new to MySQL and still learning. I am trying to figure out the error code, "1241, Operand should contain 1 column," in my queries below. I just can't figure out what I am missing.
SELECT
    o.employeeid,
    lastname, (
        SELECT employeeid, COUNT(*)
        FROM orders
        ) AS allorders, (
        SELECT employeeid, COUNT(*)
        FROM orders
        WHERE requireddate <= shippeddate
) AS lateorders
FROM employees
JOIN orders o
   USING (employeeid)
GROUP BY o.EmployeeID, LastName
ORDER BY o.EmployeeID;

Comment: Welcome to SO. Please see: [Why should I provide an MCRE for what seems to me to be a very simple SQL query?](https://meta.stackoverflow.com/questions/333952/why-should-i-provide-a-minimal-reproducible-example-for-a-very-simple-sql-query)
Answer: The problem with your queries is that each subquery in the SELECT clause should be scalar (that is, they should return just one row and one column), which is not the case.
I suspect that you actually want conditional aggregation:
SELECT
    employeeid,
    e.lastname,
    COUNT(*) AS allorders,
    SUM(o.requireddate <= o.shippeddate) AS lateorders
FROM employees e
INNER JOIN orders o USING (employeeid)
GROUP BY employeeID, e.LastName

For each employee, this counts the total number of orders, and the number of orders whose required date is not greater than the shipped date.
Comment: The queries that you posted worked it just that on the lateorders column, it included "0". I would just like to return employees who have lateorders?
Answer: You can't have multiple value return where single value is expected such as:
SELECT (SELECT 0 AS Num, 'Hi' AS Str);

Instead make use of joins and if not possible get the values separately:
SELECT (SELECT 0 AS Num), (SELECT 'Hi' AS Str);

Subqueries In The Select Clause


Proof by induction: $n^{n+1} > (n + 1)^n$, $(1 + x)^n \ge 1 + nx$, other inequalities

Question: I'm struggling around my homework. I hope someone will point me the right direction for solving following examples:

Prove that $n^{n+1} > (n + 1)^n$ for $n > 2$;
Prove that $(1 + x)^n \ge 1 + nx$; $x \in\Bbb R$; $n \in\Bbb N$;
Prove that $(2n)! < 2^{2n}(n!)^2$; $n \ge 1$;
Prove that $2^n > n$:

Thank you a lot.
Comment: Show us what you did and where you are stuck.
Comment: So, do you not know what induction is?  What do you know about induction?
Answer: For the first note that the inequality is equivalent to $n>(1+\frac1n)^n$
For the second note that $(1+nx)(1+x)=1+(n+1)x + n x^2\ge 1+(n+1)x$ and use this in an induction proof at least for the case $x\ge -1$. Think about it: Is the claim true at all if we allow very negative $x$? What about $x=-3$ and $n=5$?
For the third: Replace each odd factor $k$ in $(2n)!$ by $k+1$ and extract $2n$ factors of $2$ from the $2n$ (now) even factors.
The third is a very trivial induction.
Comment: While I realize the word has a (soft) mathematical meaning, it's kind of mean to call others' problems trivial.
Comment: Did you mean *fourth* in that last line?
Comment: It is not mean if it is indeed trivial, which it is.


Is there a successor module for 'Upload Image'?

Question: I have 'inherited' a d5 site that I would like to relaunch on d7. It made heavy use of the module Upload Image, turning attached images into nodes.
I'm now looking for a solution to implement that functionality – but so far I couldn't find a proper successor to the Upload Image module. Why I need the attached images to be nodes: the user uploading the images should only fill in 1 form – but users viewing the pages should be able to vote on every image separately (fivestar). I'm currently a bit lost. Maybe I'm overthinking this?
Any pointers / suggestions appreciated. Thank you!
Answer: Maybe try Image module, it has similar functionality
Notes:

I looked in code of this module. Unfortunately it contains some legacy code and obsolete functions. In this case try the Image Attach module.
Quote from Image Attach README.txt:

You should use Image Attach if:

You want images that you attach to content to also be pieces of content in their own right, that can be viewed separately.
You want reusable images (note that other ways of doing this exist).
You want images that have meta-data, such as a title, description, author, and so on.
You want to be able to change the file for an image, while keeping it attached to other content and keeping the rest of its data.
Comment: Thank you for your answer – I tried that because the module description looked promising (although it is marked "absolete") but trying to install the *image* module I get "*Error: ImageMagick Advanced Options is already installed*" – so I can't install the *Image* module atm… :/
Comment: I looked in code of this module. Unfortunately it contains some legacy code and obsolete functions. In this case try https://www.drupal.org/project/image_attach module
Comment: Quote from Image attach Readme
You should use Image Attach if:

* You want images that you attach to content to also be pieces of content in
  their own right, that can be viewed separately.
* You want reusable images (note that other ways of doing this exist).
* You want images that have meta-data, such as a title, description, author,
  and so on.
* You want to be able to change the file for an image, while keeping it attached
  to other content and keeping the rest of its data.
Comment: It seems to do the trick.


Italian for concerto

Question: I am watching an Italian TV series which prompted this question.
In English, concert and concerto are quite distinct.  The TV show made it apparent that the Italian concerto corresponds to English concert. So, what is Italian for English concerto?
Answer: The English 'concerto' comes from the Italian 'concerto' which can mean both concert and concerto. There are other languages that use the same word for both e.g. German 'Konzert'.
Comment: It seems so but I expected that the sense might distinguished in some more subtle way.

Italian for concerto