Restriction of scalars from $\Bbb C$ to $\Bbb R$ for vector spaces

Question: Let $X$ be a linear space over the complex field.
Let $X_{\Bbb R}$ be the space obtained from $X$ by restricting the scalars to the real field.
I proved that $X_{\Bbb R}$ is a real linear space.
But is it true that every real linear space is of the form $X_{\Bbb R}$ for some complex vector space?
Comment: It seems false since the restriction of scalars of a $\Bbb C$-vector space of dim. $n$ is a $\Bbb R$-vector space of dim. $2n$.
Comment: So what do you call "restriction of scalars"? Because the usual definition (https://en.wikipedia.org/wiki/Change_of_rings) gives $\Bbb R^2$ for restriction of scalars of $\Bbb C$. Maybe do you think of "real form", i.e. vector space $Y$ s.t. $Y\otimes_{\Bbb R}\Bbb C=X$. In this case, see http://math.stackexchange.com/questions/23470/realification-and-complexification-of-vector-spaces
Comment: @paf Why is this true? A one-dimensional $\mathbb{C}$-vector space is just the field of scalars $\mathbb{C}$, and restricting to real scalars just gives $\mathbb{R}$, which is a one-dimensional real vector space.
Comment: @paf Thanks for the references, I did not know about this.
Comment: @angryavian Doesn't that give $\mathbb{C}$ again (I am taking the "restriction" as simply the restriction of the scalar: you have still the set $\mathbb{C}$, and the scalars are in $\mathbb{R}$; as such, it is a two-dimensional real vector space)
Comment: @ClementC. I thought "restricting the scalars to the real field" just meant throwing away all non-real scalars, and didn't realize it meant something different.
Answer: No; if $V$ is a $\Bbb{C}-$vector space of finite dimension $n$, then $V_\Bbb{R}$ is of dimension $2n$, so an odd-dimensional real vector space cannot be realized as a restricted version of a complex vector space. However, every $2n$-dimensional real vector space is isomorphic to $\Bbb{R}^{2n}$, which in turn can be viewed as $\Bbb{C}^n$, restricting  its scalars to the reals.


Isn't there any other way to convert bson objects to case class and the vice-versa rather than the implicit conversion in scala?

Question: I have went through some of the reactive mongo example and find the conversion of the model and the bson object as below.
<code>  case class Artist(
  name: String,
  slug: String,
  artistId: Int,
  albums: Vector[Album] = Vector(),
  id: ObjectId = new ObjectId())

object ArtistMap {
  def toBson(artist: Artist): DBObject = {
    MongoDBObject(
      "name"     -> artist.name,
      "slug"     -> artist.slug,
      "artistId" -> artist.artistId,
      "albums"   -> artist.albums.map(AlbumMap.toBson),
      "_id"      -> artist.id
    )
  }

  def fromBson(o: DBObject): Artist = {
    Artist(
      name = o.as[String]("name"),
      slug = o.as[String]("slug"),
      artistId = o.as[Int]("artistId"),
      albums = o.as[MongoDBList]("albums").toVector
        .map(doc => AlbumMap.fromBson(doc.asInstanceOf[DBObject])),
      id = o.as[ObjectId]("_id")
    )
  }
}
</code>
Is there any other way to get rid of this overhead of mapping each field of the case classes, maybe some framework over reactivemongo or any utility for this?
Comment: ReactiveMongo offers Macros which create this boilerplate for you. http://reactivemongo.org/releases/0.9/api/index.html#reactivemongo.bson.Macros$
Comment: But Macros is not useful when nested object references lies. Macros only does half part.
Comment: What exactly do you mean? Macros can cope with nested classes?!
Answer: I don't understand your comment too, but my assumption you want functionality like that.
(I haven't written on scala for a few month, so sorry for any stupid mistake.)
<code>case class Album(name: String, year: Int)
/*
then you may implement serialization interface(trait) or use macros
*/
implicit val albumHandler = Macros.handler[Album]
/*
I'm not sure is there build in implementation for the Vector[].
*/
object VectorHandler[T](implicit handler: BSONHandler[BSONValue, T]) extends BSONHandler[BSONArray, Vector[T]]{

 def  read(bson: BSONArray): Vector[T]{
 /*
iterate over array and serialize it in a Vector with a help of the handler,
or just persist Vector[] as List[]
*/
 }
def write(t: Vector[T]): BSONArray {

 }
}

implicit val albumVectorHandler = VectorHandler[Album]()
implicit val artistHandler = Macros.handler[Atrist]
</code>


Definition simply connected in $\Bbb C$

Question: I recently saw a different definition for simply connected which I had never seen before. A connected subset $\Omega\subset\Bbb C$ is called simply connected if the boundary is the image of a simple closed curve. Is this equivalent to the usual definitions?
Thanks
Comment: could you provide an example, reference? Thanks
Comment: This does not coincide with the usual definition, because the boundary of a simply connected open set of $\Bbb R^2$ could be much more complicated than a simple closed curve.
Comment: Imagine an $8$-shaped area. It's interior is not simply connected, but it's boundary can be an image of a simple closed curve, like a circle, and even a continuous image of it.
Comment: But this curve would not be simple. It would self intersect.
Comment: @Mike: You may see the pictures in page 15-1 [here](http://www.math.sunysb.edu/preprints/ims90-5.pdf). Pictures $(b)$, $(c)$, $(d)$ are counter-examples. There are more pathological counter-examples, but let me leave the answer to others.
Comment: @Mike: it isn't a simple curve, but it's the *image* of a simple curve. Nevertheless, you require the set to be connected - and in my example it's not.
Answer:
image of a simple closed curve

Interpretation 1: the word "image" refers to the fact that a curve is really a map (parametrization), and the geometric shape that we think of as a curve is the image of that map. Some people, including me, would omit the words "image of" in this case.
With this interpretation, we have the definition of a Jordan domain, which is a  smaller class of domains than  simply connected. For example, the slit disk $\{z:|z|<1\}\setminus [0,1]$ is a simply connected domain but is not a Jordan domain.

image of a simple closed curve

Interpretation 2: the word "image" means continuous image. A set is a continuous image of a simple closed curve if and only if it is compact, connected, and locally connected (this follows from the Hahn-Mazurkiewicz  Theorem. Again, we have a more restrictive definition that simple-connectedness:

the boundary of a simply connected domain need not be compact (consider the halfplane)
the boundary of a simply connected domain need not be locally connected. To construct an  example, remove the vertical line segments from $1/n$ to $1/n+i$, $n=1,2,\dots$ from the open quadrant $x>0,y>0$.

Remarks:

I guess the first interpretation was the intended one.
It is true that a connected subset of $\Omega\subset\mathbb C$ is simply connected if and only if the set $\overline{\mathbb C}\setminus \Omega $ is connected in the topology of the Riemann sphere $\overline{\mathbb C}$. In the special  case when $\Omega$ is bounded, this amounts to  $\partial \Omega$ being connected.
Comment: Thank you very much for the response. Yes, the first was the intended.

Definition simply connected in $\Bbb C$


why the image doesn't take the full height of the page?

Question: I want the image (any image) height equal the window height even when I resize, I want to do it by jquery.
I used resize method in jquery but I don't get the results I need.
html:

css:
.container {
       width: 1200px;
       margin: auto;
}

.header {
background: url('https://preview.ibb.co/cu9YyH/download.jpg');
background-repeat: no-repeat;
}

jquery:
$(function () {
        $(".header").height($(window).height());

        $(window).resize(function () {

            $(".header").height($(window).height());
        });
});

Comment: Share your HTML as well?
Comment: And your CSS if you have any.
Comment: okay @void and amflare
Answer: There's no need for JS here. CSS alone will do the job, and is preferable for two reasons. Firstly this is a UI concern, so you shouldn't use JS as a crutch for that. Secondly, it performs better and you don't need to rely on  the resize event to update the settings on the element.
To achieve what you need use vh (viewport height) units, like this:

html, body {
  padding: 0;
  margin: 0;
}
header {
  background-color: #ccc;
  height: 100vh;
}
div {
  min-height: 50px;
}

  I am the full-height header...

  Some content here...

Comment: I want to use jquery because I'm practicing
I edited the question
Comment: In that case you'll need to use `background-size: cover`: https://jsfiddle.net/qpud68m0/2/. Although I'd strongly suggest you always do this in CSS in a production environment


Mudança de altura suave

Question: Estou fazendo um Navbar onde ele vai diminuir a altura e mudar a cor no evento de scroll. Meu problema está em deixar essa transição suave. Consegui fazer para para a cor, mas não para a altura. Como posso deixar a mudança de altura suave?

$(window).on('scroll', function(event) {
  if ($(window).scrollTop()) {
    $('.navbar').addClass('bg-dark');
    $('.navbar').removeClass('bg-primary teste');
  } else {
    $('.navbar').removeClass('bg-dark');
    $('.navbar').addClass('bg-primary teste');
  }
  if ($(window).scrollTop() > 100) {
    $('.navbar').removeClass('teste');
  } else {
    $('.navbar').addClass('teste');
  }
});
nav {
  transition: 2s all ease-in-out;
}

.navbar.teste>.container {
  min-height: 54px;
}

.navbar.teste>.container>.navbar-brand {
  padding: 0 15px;
  height: 54px;
  line-height: 54px;
}

.navbar.teste>.container>.navbar-brand>.navbar-toggle {
  margin-top: 18px;
  padding: 9px 10px !important;
}

@media (min-width: 768px) {
  .navbar.teste>.container>div>.navbar-nav>li>a {
    padding-top: 16.5px;
    padding-bottom: 16.5px;
    line-height: 16px;
  }
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">

    Marca
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarContent" aria-controls="navbarContent" aria-expanded="false" aria-label="Toggle navigation">

    </button>

Projetos

Notícias

Eventos

Biblioteca

Teste

Teste

Teste

Teste

Teste

Teste

Teste

Teste

Teste

Teste

Answer: A altura não diminui suave porque apenas o navbar estava com a transition de 2s. A classe .teste não estava alterando o style do nav, estava alterando outras tags dentro do nav (como o container e a logo) e eles nao tinham o atrabuto transition, que era exatamente o que fazia o nav diminuir.
O que eu fiz foi definir o tamanho do nav e com a classe .teste, ele diminui o tamanho do mesmo. Olha como ficou:

$(window).on('scroll', function(event) {
  if ($(window).scrollTop() > 100) {
    $('.navbar').addClass('bg-dark');
    $('.navbar').removeClass('bg-primary');
    $('.navbar').addClass('teste');
  } else {
    $('.navbar').removeClass('bg-dark');
    $('.navbar').addClass('bg-primary');
    $('.navbar').removeClass('teste');
  }
});
nav {
  transition: 1s all ease-in-out;
}

.navbar {
  height: 65px;
}
.navbar.teste {
  height: 50px;
}

.navbar>.container>.navbar-brand {
  padding: 0 15px;
  line-height: 54px;
}

.navbar>.container>.navbar-brand>.navbar-toggle {
  margin-top: 18px;
  padding: 9px 10px !important;
}

@media (min-width: 768px) {
  .navbar>.container>div>.navbar-nav>li>a {
    padding-top: 16.5px;
    padding-bottom: 16.5px;
    line-height: 16px;
  }
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">

    Marca
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarContent" aria-controls="navbarContent" aria-expanded="false" aria-label="Toggle navigation">

    </button>

Projetos

Notícias

Eventos

Biblioteca

Teste

Teste

Teste

Teste

Teste

Teste

Teste

Teste

Teste

Teste

Comment: eu indicaria você definir a transition com 0.5s, por que 1 segundo demora muito
Comment: Muito obrigado. Coloquei esse valor alto só para ficar mais fácil visualizar. Valeu pela resposta
Answer: Jovem a transição com a cor acontece pq vc está trocando uma classe por outra. Mas com a classe .teste que vc colocou a altura não ocorre pq não tem uma referência de valor.
Inclui uma classe nova .testex apenas pare vc ver que o problema é a transição entre um valor e outro. Aparentemente o script está ok...
Fiz o exemplo com a NavBar aumentando e com a transição, mas vc pode fazer como quiser customizando o .textex, deixei um comentário no CSS

$(window).on('scroll', function(event) {
  if ($(window).scrollTop()) {
$('.navbar').addClass('bg-dark testex');
$('.navbar').removeClass('bg-primary teste');
  } else {
$('.navbar').removeClass('bg-dark testex');
$('.navbar').addClass('bg-primary teste');
  }
  if ($(window).scrollTop() > 100) {
$('.navbar').removeClass('teste');
  } else {
$('.navbar').addClass('teste');
  }
});
nav {
  transition: 2s all ease-in-out;
}

.navbar.testex>.container {
  transition: 2s all ease-in-out;
  min-height: 74px; /* valor de referência pro valor da altura da NavBar */
}

.navbar.teste>.container {
  transition: 2s all ease-in-out;
  min-height: 54px;
}

.navbar.teste>.container>.navbar-brand {
  padding: 0 15px;
  height: 54px;
  line-height: 54px;
}

.navbar.teste>.container>.navbar-brand>.navbar-toggle {
  margin-top: 18px;
  padding: 9px 10px !important;
}

@media (min-width: 768px) {
  .navbar.teste>.container>div>.navbar-nav>li>a {
    padding-top: 16.5px;
    padding-bottom: 16.5px;
    line-height: 16px;
  }
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">

    Marca
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarContent" aria-controls="navbarContent" aria-expanded="false" aria-label="Toggle navigation">

    </button>

Projetos

Notícias

Eventos

Biblioteca

Teste

Teste

Teste

Teste

Teste

Teste

Teste

Teste

Teste

Teste

Teste

Teste

Teste

Teste

Teste

Teste

Teste

Teste

Teste

Teste

Teste

Teste

Teste

Teste

Teste

Teste

Teste

Teste

Teste

Teste

Mudança de altura suave


Got root, now how should I configure my server?

Question: I've been a developer for years and by trade I had to know a little bit of server side configuration. But now I find myself needing to manage my own VPS instance (Amazon EC2) and I'm lost. I'd like to know what are the common ways to configure an Apache and MySQL server that is secure and efficient.
For example right now I'm doing everything as root but I doubt that's the best way at all. My whole Apache is configured to serve 1 site when I'd like it to be able to serve multiple sites.
Where do I start?
Comment: Try to stick to one question at a time and keep them narrow enough that they won't fill an entire book.  Pick one of the "should I be root" or "Apache vhosts" questions and split them into two.  If you're looking to become a full time sysadmin, [this question would be a good place to start](http://serverfault.com/questions/1046/what-is-the-single-most-influential-book-every-sysadmin-should-read).
Comment: Ladadadada thanks but while I understand your remark my question is really broad in its nature. Frank understood it with his answer which contains very good pointers for me.
Answer: First of all you need to know some basic Bash commands, you can find them here:
http://maketecheasier.com/basic-bash-command-for-new-linux-users/2008/01/22
Here is another tutorial for LAMP(Linux,Apache,MySQL,PHP).....
http://www.lamphowto.com/
Basic Apache website(Virtual hosting) configuration:
http://www.linode.com/wiki/index.php/Configure_apache_to_use_virtual_hosts_on_ubuntu_server
http://ubuntu-tutorials.com/2008/01/09/setting-up-name-based-virtual-hosting/
and for MySQL
http://library.linode.com/databases/mysql/ubuntu-10.04-lucid


Problem providing intro text in blog application (using cake php)

Question: Background
I am developing my blog application in Cake PHP. I aim to provide an intro text for each post on the home page. The user can then click on the "Read more" link to read the entire post. Following is my posts table.
 $query = 'CREATE TABLE posts (
              id INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
              name VARCHAR(255) DEFAULT NULL,
              date DATETIME DEFAULT NULL,
              summary TEXT,
              content TEXT,
              user_id INT(11) DEFAULT NULL,
              PRIMARY KEY(id))
              ENGINE=MyISAM';

Following is the index.ctp file
<?php foreach($posts as $post): ?>

    <?php echo $html->link('
'.$post['Post']['name'].'
', '/posts/view/'.$post['Post']['id'],null,null,false); ?>

Posted  <?php echo date('M jS Y, g:i a', strtotime($post['Post']['date'])); ?>

By:  <?php echo $post['User']['firstname']; ?>  <?php echo $post['User']['lastname']; ?>

<?php echo $post['Post']['summary']; ?><?php echo $html->link('
Read More
', '/posts/view/'.$post['Post']['id'],null,null,false); ?>

<?php endforeach; ?>

Similarly,I have also added the summary field in add.ctp, edit.ctp and view.ctp
Problem
Now the problem is that when I try to create a new post, the summary field is not getting committed to the database. There is no problem with other fields. Moreover,  even when I manually add text into the summary field from phpMyAdmin, I still can't view it in my home page. No errors have been reported.
What am I missing??
Comment: Do you have a Post model? The issue may be there.
Comment: ya...i do have a post model..but no probs there...what should i do??Should I create an altogether different table for storing summaries??Although I do think that this will not be approporiate
Answer: Did you already have a version of the "posts" table that didn't have a "summary" field, then went back and added it?  If so, you may need to delete your model cache.
rm -rf app/tmp/cache/models/cake_model_*

Comment: I did what you suggested...just deleted the cache files from app\tmp\cache\models directory and it worked :)
Comment: ya...that is what I did...can you please elaborate on this point?or if you have some link providing more information??
Comment: Glad you figured it out.  Was this the trick that solved your problem?  If not, mind sharing what you did for others who come across this post with the same issue as you? :)


child node in MBR (R-Tree Implementation)

Question: I am new to R-Tree concept. Sorry If I ask a very basic question related to Rtree. I have read a few literature on R-Tree to get the basic concept of R-Tree. However, I could not understand the clustering or grouping steps in MBR. What's bothering me is:
How many points or object could fit in each MBR? i could see that the number of object stored in each MBR is varies. So is there any condition or procedure or formula or anything to determine how many objects will be stored in each MBR?
Thanks for your help! Gracias!
Answer: Read the R-tree publication, or a book on index structures.
You fix a page size (because the R-tree is a disk-oriented data structure, this should be something such as e.g. 8kb).
If a page gets too empty, it will be removed. If a page is too full, it will be split.
Just like with pretty much any other page-based tree, actually (e.g. B-tree).


Como identificar o número da página de um .pdf por algo escrito nela?

Question: Eu tenho um .pdf com 120 páginas, cada página é um certificado e a única diferença entre eles é o nome do participante.
Eu também tenho um .csv com a lista de nomes e o e-mail dos participantes (usei esta lista para gerar o .pdf e vou tentar usar os e-mail para mandar pelo R)
Como eu consigo separar cada página (certificado) em um novo .pdf e salvar com o nome do participante?
Vi funções como pdf_subset da library(pdftools), mas como eu consigo identificar o número da página por algo escrito nela?
library(pdftools)

# extair paginas de 1
pdf_subset('certificados.pdf',
           pages = 1, output = "Carlos dos Santos.pdf")

É um trabalho bastante repetitivo, não gostaria de fazer manualmente.
Também pensei em separar página por página e depois procurar o nome no .pdf e alterar o nome do arquivo. Mas também não sei como fazer isso ainda.
Segue modelo de certificado:
https://drive.google.com/file/d/1iwgW6kMT7C9Xee5SM65vz-D8B26bpavz/view?usp=sharing
Exemplo de .csv:
nome,email
Prof. Dr. Thiado Souza,firstname.lastname@example.com
Prof. Dr. Marcelo José,mjose@gmail
Ricado Augusto,firstname.lastname@example.com
Carlos José,email@example.com

Comment: Fala @RxT, blz? Vc tem o `.pdf`  para disponibilizar? Pode ser um fake (ou com nomes omitidos), aí posso tentar algum código. Só que como você quer "separar cada página (certificado) em um novo .pdf", eu penso que é mais fácil fazer via terminal de comando. Vc usa ubuntu? O Ubuntu tem o ImageMagick que deve fazer isso de forma fácil (eu só não sei como faria esse loop de cada página, mas é questão de pesquisar). E dps disso, imagino que o resto é mais fácil.
Comment: @GuilhermeParreira obrigado pela atenção! Adicionei o arquivo na pergunta ! Sim, uso o Mint na verdade, mas não deve ser diferente, né?!
Answer: Tendo em vista que os certificados seguem a mesma ordem do arquivo csv:
library(pdftools)

arq <- read.csv('./rxt.csv')
nomes <- as.character(arq$nome)

cria_pdf <- function(n, i){
  pdf_subset('certificado-teste.pdf',
             pages = i, output = paste(n[i],'.pdf'))
}

lapply(seq_along(nomes),cria_pdf, n = nomes)

Este cria no diretório arquivos separados baseado na listagem dos nomes do csv.
Answer: Creio que a função seguinte divide o pdf de entrada em páginas, guardando cada página num ficheiro e renomeia esses ficheiros com os nomes do ficheiro csv. A entrada da função é

file - o nome do ficheiro pdf;
nomes - o data.frame com uma coluna 'nome'

Precisa do pacote pdftools para processar os ficheiros pdf e do pacote stringi para remover acentos e letras especiais, tal como etá nesta resposta.
library(pdftools)

rename_file <- function(from, to){
  out <- tryCatch(file.rename(from, to),
                  error = function(e) e
  )
  if(inherits(out, "error")){
    out <- tryCatch(file.copy(from, to),
                    error = function(e) e,
                    warning = function(w) w
    )
    if(inherits(out, "error")){
      stop(e)
    }
    if(inherits(out, "warning")){
      warning(out)
      out <- FALSE
    }
    if(file.exists(to)) {
      if(file.exists(from)) unlink(from)
      out <- TRUE
    } else out <- FALSE
  }
  out
}

fun_split_pdf <- function(file, nomes){
  # ler os dados do pdf para uma lista de data.frames
  data_list <- pdf_data(file)
  # ficar com a coluna 'text' de cada data.frame da lista
  # e convertê-la em um único vetor com paste()
  Text <- unlist(lapply(data_list, function(x) paste(x[['text']], collapse = ' ')))
  # se tiver acentos, removê-los
  Text <- stringi::stri_trans_general(Text, "Latin-ASCII")
  # agora ver quais nomes do csv estão em qual página do pdf
  i <- sapply(nomes[['nome']], function(x){
    x <- stringi::stri_trans_general(x, "Latin-ASCII")
    j <- grep(x, Text)
    if(length(j) > 1) j[1] else j
  })
  # ordenar a coluna 'nome' do csv pela ordem do grep
  nms <- nomes[['nome']][i]
  # nomes finais dos ficheiros de saída
  nms <- paste0(nms, '.pdf')

  # fazer o split para um diretório temporário
  tmp <- tempfile()
  pdf_split(file, output = tmp)

  # renomear os ficheiros temporários
  pattern <- paste0(basename(tmp), "_.*\\.pdf")
  tmp_fls <- list.files(path = dirname(tmp), pattern = pattern)
  tmp_fls <- file.path(dirname(tmp), tmp_fls)
  sapply(seq_along(tmp_fls), function(i){
    rename_file(tmp_fls[[i]], nms[[i]])
  })
}

fl <- list.files(pattern = '\\.pdf')
fl
#[1] "certificado-teste.pdf"

nomes <- read.csv("pdf_teste.csv")

fun_split_pdf(fl, nomes)
#[1] TRUE TRUE TRUE TRUE

Comment: @RxT Pode ser. Talvez `i <- unique(unlist(i))` resolva o problema. Não pode postar um link para um ficheiro com essa situação de cadastros repetidos?
Comment: @RxT Isso é uma mensagem de erro do sistema. Uma solução é copiar para o arquivo destino e depois `unlink` o arquivo original. Neste momento não posso postar código, amanhã de manhã (Portugal é GMT) de certeza que posso.
Comment: Estou tendo esse erro: `Error in nomes[["nome"]][i] : tipo de subscrito inválido 'list'` mas a coluna "nome" é charactere.
Comment: @RxT O que é que `print(i)` logo a seguir ao `sapply` dá? Se der uma lista e não um vetor, faça `i <- unlist(i)` logo a seguir ao `sapply`.
Comment: Ele retorno o nome e as posições $`Nome e sobrenome`
[1] 1

$`Outro nome e sobrenome`
[1] 2    -------- se colocar o `i<-unlist(i)`, eu tenho esse erro: `Error in file.rename(tmp_fls, nms) :
  'from' and 'to' are of different lengths` e eu percebi, que algumas pessoas se cadastraram duas vezes. Esse pode ser o erro?
Comment: Removendo os repetidos ou utilizando o `unique()` o resultado está sendo `FALSE` para todos os valores.
Comment: Aplicando sua resposta nos exemplos que postei, tive a mensagem: `Warning messages:
1: In file.rename(tmp_fls, nms) :
  não foi possível renomear o arquivo '/tmp/RtmpwzCKgS/file7e8e15c01a2e_0001.pdf' para 'Prof. Dr. Thiado Souza.pdf', motivo 'Link entre dispositivos inválido'`
Comment: @RxT Afinal não foi ontem, veja agora.


Invalid argument when trying to bind python socket to IPv6 address

Question: I'm trying from my virtual machine to bind my socket in python to the address of my other virtual machine so that I could sniff the frames that are exchanged by the two. So here's my code
    import socket

UDP_IP = "fe80:849b:21f4:624c:d70b"
UDP_PORT = 61627

sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
sock.bind((UDP_IP, UDP_PORT))

while True:
    data, addr = sock.recvfrom(1024)
    print(data)

When I try to execute my python, I get an error message :
sock.bind((UDP_IP, UDP_PORT))
socket.error: [Error 22] Invalid argument

What am I doing wrong, thanks in advance !
Comment: That IPv6 address is not valid.
Comment: Because it doesn't have the mandatory scope ID.
Comment: why is it not valid?
Answer: I bet, you had found the answer already, but nevertheless on the first glance I see two issues with your code:

In IPv6 fe80::/10 address block is reserved for Link-local addresses. These addresses are valid for local subnet only, therefore they are used with scope suffixes like %eth0 to specify proper scope. Where eth0 is a name of the network interface for which the IPv6 address is valid.

So for my MacOS laptop UDP_IP address could look like:
UDP_IP = "fe80:849b:21f4:624c:d70b%en0"

Next, specifying (UDP_IP, UDP_PORT) tuple is absolutely valid for IPv4 but for IPv6 this tuple should also contain flow_info and scope_id fields. Sometimes, flow_info and scope_id could be omitted or missed: (UDP_IP, UDP_PORT, 0, 0). It may work sometimes, but it's not the right way to use in the code.

So, these fields can be fetched via socket.getaddrinfo(IP, PORT) which returns a list of tuples for each address family and socket_kind. Filter them with something like that:
for ainfo in socket.getaddrinfo(UDP_IP, UDP_PORT):
    if ainfo[0].name == 'AF_INET6' and ainfo[1].name == 'SOCK_DGRAM':
        target_address = ainfo[4]
        break

sock.bind(target_address)

I'm not sure, if I wrote the sample code right, as I didn't test it, check it before usage.


Mover div para outra div e atualizar banco de dados

Question: Possuo o seguinte jQuery
$(function() {
    $( "#sortable1, #sortable2, #sortable3, #sortable4, #sortable5, #sortable6").sortable({
        connectWith: ".connectedSortable",
        receive: function( event, ui ){
            jQuery("#carregando").html('
 carregando..
').delay(2000).fadeOut("slow");
            setTimeout(function(){

                $.ajax({
                    url: '<? echo base_url("vendas/pipeline/ajax"); ?>',
                   success: function(data) {
                        $('.pipeline').html(data);
                   }
                });
            }, 2000);
        },
    }).disableSelection();
});

E o seguinte HTML com PHP

        <? $i=1; foreach($lista_negocios_dashboard as $valor){ ?>
        <div class="col-md-2 pipeline-base connectedSortable" id="sortable<?=$i;?>">

                <? echo $valor->set_setor; ?>

            <? foreach($valor->negocios as $negocios){ ?>

<a href="<? echo base_url()."vendas/pipeline/negocios/editar/".$negocios->neg_cod; ?>"><? echo $negocios->neg_nome; ?>

<? echo $negocios->neg_descricao; ?>

            <? } ?>

        <? $i++;} ?>

Nisso, eu consigo mover uma div para uma outra div. Funcionando 100%.
Porém, eu preciso atualizar o banco de dados, com a categoria que eu passar por esta div nova. Eu preciso recuperar pelo jQuery - cod_categoria e o cod_negocio, e setar este negocio nesta nova categoria, que foi arrastada...
Comment: O cod_negocio e cod_categoria no seu código seriam $negocios->neg_cod e $negocios->neg_nome?
Comment: Código do negócio: neg_cod, cod da categoria (pipeline class) set_cod
Answer: Utilizando JQuery sortable você pode adicionar um atributo update e a partir daí fazer as alterações no banco.
$("#foo").sortable({
    update: function(event, ui){
        // a posição do item reposicionado
        var indice = ui.item.index();
    }
});

O atributo CHANGE é chamado para qualquer alteração e um item, ja o atributo UPDATE é chamado somente no fim da ultima alteração feita. Vale lembrar que todos os items que foram alterados, não somente o selecionado, vão disparar este evento.
Como exemplo:
Cito um Post já existente aqui no stack com o seguinte exemplo:
$(function() {
$('#sortable').sortable({
    start: function(event, ui) {
        var start_pos = ui.item.index();
        ui.item.data('start_pos', start_pos);
    },
    change: function(event, ui) {
        var start_pos = ui.item.data('start_pos');
        var index = ui.placeholder.index();
        if (start_pos < index) {
            $('#sortable li:nth-child(' + index + ')').addClass('highlights');
        } else {
            $('#sortable li:eq(' + (index + 1) + ')').addClass('highlights');
        }
    },
    update: function(event, ui) {
        $('#sortable li').removeClass('highlights');
    }
});

});
No exemplo ele usa dois atributos, change e update, como eu mencionei na minha resposta. No change, ele adiciona a classe css highlights, que altera o fundo do item para a cor amarela (sendo originalmente cinza) e no update ele remove esta classe (voltando a cor para a original). Com este link você pode ver o exemplo na pratica e entender quando cada um desses eventos sao disparados e entender qual o melhor momento de atualizar o seu banco de dados, você vera também que o evento é disparado para todos os items.
Comment: Você teria um exemplo prático pra eu conseguir entender melhor?
Comment: Posso sim, editei minha resposta.
Comment: Sim, mas de que forma eu consigo atualizar meu banco de dados, conforme os ids?
Comment: O melhor momento de atualizar o banco de dados, é a hora que ele chegou na div, ai sim, atualiza
Comment: Usa o console do navegador e adiciona o seguinte log no codigo console.log(ui.item); veja se você consegue acessar os dados de categoria e negocio.


Razor C# fazer lista e sublista com List (originalmente "como verificar se um elemento HTML já existe")

Question: Preciso saber se um elemento HTML já existe, no meu loop, se ele existir eu uso ele, se ele não existir eu crio um.
Como faria isso dentro de um
@foreach (var item in Model){ ... }

Seguindo o comentário do Cigano, como não é possível eu queria uma lógica assim:

Tenho um List<String> ordenado alfabeticamente.
Todas as strings que começam com A eu quero que fiquem abaixo de um
A

Quero um
 com os
s organizados desse forma. Alguém tem alguma dica?
Preciso disso dinâmico porque está sempre mudando os valores.
Comment: O Razor não avalia elementos HTML: apenas elementos dentro do MVC. Creio que é impossível fazer o que você quer.
Comment: Então, como não é possível eu editei a pergunta colocando outra solução possível. Obrigado.
Comment: Melhorou muito. Agora já posso responder.
Answer: Estou supondo que Model é List<String>, logo posso ordenar alfabeticamente e agrupar os valores pela primeira letra de cada String:

@foreach (var item in Model.OrderBy(s => s).GroupBy(s => s[0]))
{

        @item.Key
        @if (item.ToList().Count > 0) {

            @foreach (var subitem in item.ToList())
            {

@subitem

            }

        }

}


I keep getting FATAL EXCEPTION : main

Question: Log Cat :
02-23 18:47:36.399: E/AndroidRuntime(25571): FATAL EXCEPTION: main
02-23 18:47:36.399: E/AndroidRuntime(25571): Process: com.example.calculator, PID: 25571
02-23 18:47:36.399: E/AndroidRuntime(25571): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.calculator/com.example.calculator.MainActivity}:    java.lang.NullPointerException
02-23 18:47:36.399: E/AndroidRuntime(25571):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
02-23 18:47:36.399: E/AndroidRuntime(25571):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
02-23 18:47:36.399: E/AndroidRuntime(25571):    at android.app.ActivityThread.access$800(ActivityThread.java:135)
02-23 18:47:36.399: E/AndroidRuntime(25571):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
02-23 18:47:36.399: E/AndroidRuntime(25571):    at android.os.Handler.dispatchMessage(Handler.java:102)
02-23 18:47:36.399: E/AndroidRuntime(25571):    at android.os.Looper.loop(Looper.java:136)
02-23 18:47:36.399: E/AndroidRuntime(25571):    at android.app.ActivityThread.main(ActivityThread.java:5017)
02-23 18:47:36.399: E/AndroidRuntime(25571):    at java.lang.reflect.Method.invokeNative(Native Method)
02-23 18:47:36.399: E/AndroidRuntime(25571):    at java.lang.reflect.Method.invoke(Method.java:515)
02-23 18:47:36.399: E/AndroidRuntime(25571):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
02-23 18:47:36.399: E/AndroidRuntime(25571):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
02-23 18:47:36.399: E/AndroidRuntime(25571):    at dalvik.system.NativeStart.main(Native Method)
02-23 18:47:36.399: E/AndroidRuntime(25571): Caused by: java.lang.NullPointerException
02-23 18:47:36.399: E/AndroidRuntime(25571):    at com.example.calculator.MainActivity.onCreate(MainActivity.java:39)
02-23 18:47:36.399: E/AndroidRuntime(25571):    at android.app.Activity.performCreate(Activity.java:5231)
02-23 18:47:36.399: E/AndroidRuntime(25571):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
02-23 18:47:36.399: E/AndroidRuntime(25571):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
02-23 18:47:36.399: E/AndroidRuntime(25571):    ... 11 more
02-23 18:47:48.010: D/AndroidRuntime(25647): Shutting down VM

activity_main.xml :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/screen"
    android:textSize="60sp"
    android:id="@+id/screen" />

<Button
    android:id="@+id/num0"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:text="@string/num0" />

<Button
    android:id="@+id/num1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/screen"
    android:layout_marginTop="16dp"
    android:text="@string/num1" />

<Button
    android:id="@+id/num2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/num1"
    android:layout_alignBottom="@+id/num1"
    android:layout_marginLeft="16dp"
    android:layout_toRightOf="@+id/num1"
    android:text="@string/num2" />

<Button
    android:id="@+id/num3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/num2"
    android:layout_alignBottom="@+id/num2"
    android:layout_marginLeft="20dp"
    android:layout_toRightOf="@+id/num2"
    android:text="@string/num3" />

<Button
    android:id="@+id/num4"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_toLeftOf="@+id/num2"
    android:text="@string/num4" />

<Button
    android:id="@+id/num5"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/num4"
    android:layout_alignBottom="@+id/num4"
    android:layout_alignLeft="@+id/num2"
    android:text="@string/num5" />

<Button
    android:id="@+id/num6"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/num5"
    android:layout_alignBottom="@+id/num5"
    android:layout_alignLeft="@+id/num3"
    android:text="@string/num6" />

<Button
    android:id="@+id/num7"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/num4"
    android:layout_marginTop="65dp"
    android:layout_toLeftOf="@+id/num2"
    android:text="@string/num7" />

<Button
    android:id="@+id/num8"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/num7"
    android:layout_alignBottom="@+id/num7"
    android:layout_alignLeft="@+id/num5"
    android:text="@string/num8" />

<Button
    android:id="@+id/num9"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/num8"
    android:layout_alignBottom="@+id/num8"
    android:layout_alignLeft="@+id/num6"
    android:text="@string/num9" />

<Button
    android:id="@+id/add"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/num3"
    android:layout_alignBottom="@+id/num3"
    android:layout_alignParentRight="true"
    android:text="@string/add" />

<Button
    android:id="@+id/subtract"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_alignTop="@+id/num9"
    android:text="@string/subtract"
    android:textSize="30sp" />

<Button
    android:id="@+id/multiply"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/num7"
    android:layout_alignParentRight="true"
    android:text="@string/multiply" />

<Button
    android:id="@+id/divide"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:text="@string/divide" />

<Button
    android:id="@+id/clear"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_toLeftOf="@+id/num3"
    android:text="@string/clear" />

<Button
    android:id="@+id/equal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/num9"
    android:layout_alignParentBottom="true"
    android:text="@string/equal" />

</RelativeLayout>

MainActivity.java :
package com.example.calculator;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

Button zero, one, two, three, four, five, six, seven, eight, nine, clear, add, subtract, multiply, divide, equal;
double num1, num2, answer;
String operation;
int twoDigit;
TextView screen;
@Override
protected void onCreate(Bundle savedInstanceState) {
    zero = (Button) findViewById(R.id.num0);
    one = (Button) findViewById(R.id.num1);
    two = (Button) findViewById(R.id.num2);
    three = (Button) findViewById(R.id.num3);
    four = (Button) findViewById(R.id.num4);
    five = (Button) findViewById(R.id.num5);
    six = (Button) findViewById(R.id.num6);
    seven = (Button) findViewById(R.id.num7);
    eight = (Button) findViewById(R.id.num8);
    nine = (Button) findViewById(R.id.num9);
    clear = (Button) findViewById(R.id.clear);
    add = (Button) findViewById(R.id.add);
    subtract = (Button) findViewById(R.id.subtract);
    multiply = (Button) findViewById(R.id.multiply);
    divide = (Button) findViewById(R.id.divide);
    equal = (Button) findViewById(R.id.equal);

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    screen.setText("0");
    num1 = 0; num2 = 0;
    firstNumberEntry();
}

public void firstNumberEntry() {
    one.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            num1 = 1;
            screen.setText("" + num1);
            if(add.isPressed()){
                operation = "add";
                operations(num1, operation);
            } else if(subtract.isPressed()){
                operation = "subtract";
                operations(num1, operation);
            }else if(multiply.isPressed()){
                operation = "multiply";
                operations(num1, operation);
            }else if(divide.isPressed()){
                operation = "divide";
                operations(num1, operation);
            }
        }

    });

}

public void operations(double num1, String operation) {

}
}

Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.calculator"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="19" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

</manifest>

I'm a beginner at android development and I'm trying to make a double - digit calculator. I'm still far from finishing, but I thought of testing what I already have coded. Whenever I open the app on a device, I get the message "Unfortunately, Calculator has stopped". I've attached all my code, including the LogCat. Since I'm a newbie at this stuff, I don't really understand whats wrong. Any help?
Comment: Keep reading through the log a bit further down. It has a "Caused by: java.lang.NullPointerException at com.example.calculator.MainActivity.onCreate(MainActivity.java:39)"
Comment: Move all of your `findViewById` statements underneath `setContentView`.
Comment: Ah yes, for this particular problem, it is because of the uninitialized `screen` variable. I would still advise you move each of these initializations under `setContentView` to resolve future problems. +1 to @jprofitt and @Abrackadabra
Comment: possible duplicate of [What is a Null Pointer Exception?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception)
Answer: You don't set the screen variable to anything, so it is initialized to null and you get an exception when you try to call a null's method.
You should add
screen = (TextView) findViewById(R.id.textView);

before this statement.

I keep getting FATAL EXCEPTION : main


C# Command-Line Parsing of Quoted Paths and Avoiding Escape Characters

Question: How is it possible to parse command-line arguments that are to be interpreted as paths?   args[] contains strings that are automatically joined if they are quoted, e.g.:
example.exe one two "three four"
args[0] = one
args[1] = two
args[2] = three four

However, args[] will not property parse "C:\Example\" as an argument.  Rather, it will supply the argument as "C:\Example""  (with the extra quote included.)  This is due to the backslash in the path being treated as an escape character and thus the end quotation that the user supplied on the command-line becomes part of the argument.
.e.g:
example.exe one "C:\InputFolder" "C:\OutuptFolder\"
args[0] = one
args[1] = C:\InputFolder"
args[2] = C:\OutputFolder"

An easy kludge might be:
_path = args[i].Replace("\"", @"\");

However, I'm sure there is a best-practice for this.  How might one correctly parse a command line that inlcudes paths, preventing the args[] array from improperly being populated with stings that have been parsed for escape characters?
NOTE: I would not like to include an entire command-line parsing library in my project!  I need only to handle quoted paths and wish to do so in a "manual" fashion.  Please do not reccomend NConsoler, Mono, or any other large "kitchen sink" command-line parsing library.
ALSO NOTE:  As far as I can tell, this is not a duplicate question.  While other questions focus on generic command-line parsing, this question is specific to the problem that paths introduce when parts of them are interpreted as escape sequences.
Comment: Where exactly are you seeing this extra character? I am using snippet compiler. Here is the main.. string s=args[0];   Console.WriteLine(s); And it works as it should.
Comment: @shahkalpesh: Dunno about your snippet compiler, but try running it from the command line, and supply your program with an argument ending in \" (backslash-doublequote).  As ebwi said, opened my eyes.
Comment: I get it now. Sorry that I didn't understand the input argument correctly.
Comment: Change your job stream to use escaped backslashes for the input parameters on the command line.  "\\\\machine\\share\\path\\filename\\" as an alternative to avoid the issue.
Answer: Not an answer, but here's some background and explanation from Jeffrey Tan, Microsoft Online Community Support (12/7/2006):

Note: this is not not a code defeat
  but by design, since backslashe are
  normally used to escape certain
  special character. Also, this
  algorithm is the same as Win32 command
  line arguments parsing function
  CommandLineToArgvW. See the Remarks
  section below:
  http://msdn2.microsoft.com/en-us/library/bb776391.aspx

Also makes reference to the FX method Environment.GetCommandLineArgs for further explanation of the slash handling behavior.
Personally I think this is a drag, and I'm surprised I haven't been bit by it before.  Or maybe I have and don't know it?  Blind replacement of quotes with slashes doesn't strike me as a solution, though.  I'm voting the question up, because it was an eye opener.
Answer: I like your idea:
_path = args[i].Replace("\"", @"\");

It is clean, and will have no effect unless the problem exists.
Comment: But this won't work if you have: example.exe one "C:\InputFolder\" "C:\OutuptFolder\" as the two paths will get concatinated as arg[1]=C:\InputFolder" C:\Outpurfolder"
Answer: I had the same frustration. My solution was to use regular expressions.  My expected input is a list of paths, some of which may be quoted.  The above kludge doesn't work unless all the last arguments are quoted.
// Capture quoted string or non-quoted strings followed by whitespace
string exp = @"^(?:""([^""]*)""\s*|([^""\s]+)\s*)+";
Match m = Regex.Match(Environment.CommandLine, exp);

// Expect three Groups
// group[0] = entire match
// group[1] = matches from left capturing group
// group[2] = matches from right capturing group
if (m.Groups.Count < 3)
    throw new ArgumentException("A minimum of 2 arguments are required for this program");

// Sort the captures by their original postion
var captures = m.Groups[1].Captures.Cast<Capture>().Concat(
               m.Groups[2].Captures.Cast<Capture>()).
               OrderBy(x => x.Index).
               ToArray();

// captures[0] is the executable file
if (captures.Length < 3)
    throw new ArgumentException("A minimum of 2 arguments are required for this program");

Can anyone see a more efficient regex?


Variable with high number of categories

Question: I would like some help with my analysis. I have an outcome variable that represents average number of errors somebody experiences per hour. It has about 26% zeros. 85% of values are smaller than 1. There are some outliers going up to >700.
My explanatory variables are only categorical variables. One has 3 categories, one has 2 categories, one has six categories and one has 91 categories (area within a country).
My question is whether anyone has some tips analyzing this dataset. I want to know the effects of the variables and potential interaction effects on the outcome.
I would like to know as well if there are some locations that experience significantly high numbers of errors.
Can anybody help me going in the right direction? I am just starting in statistics.
Comment: I wouldn't use the average number of errors per hour as my outcome variable if I could avoid it. Do you have information on the actual number of errors, & the number of hours for each person?
Comment: Yes, I have information about the actual number of errors. Per person, in which hour he watched television, how long he watched and how many errors he experienced.
Comment: I'd reconsider your title. Is having one variable with a high number of categories central to your question?
Comment: I would like to include it in the analysis, but the other variables are important too. I don't know how to handle the variable with such a high number of categories
Comment: For the variable with 91 categories, look into fused lasso. Search this site.
Answer: There are at least two issues here:
1) The distribution of the dependent variable and
2) The number of categories in one of the independent variables
Regarding 1) Since the variable is the average number of errors, it is essentially continuous, albeit very skewed. OLS regression makes no assumptions about the shape of the dependent variable, only about the residuals. But it is likely that they will be non-normal and you may need to transform the DV.
Regarding 2) There is no special reason you cannot have a variable with so many categories, provided that you have enough data. You will want to have enough cases in every region. You may need to combine regions.
Answer: I would suggest the following:
1) Inspect the assumption of a Poisson variable
2) Inspect overdispersion
3) Inspect excessive zeros
If 1) is not rejected, then proceed with Poisson regression in a generalized linear model.
If 1) is rejected then
If 2) is true and 3) is not, then proceed with Negative Binomial model.
If 2) is false and 3) is true, then proceed with Zero-Inflated Poisson model.
If both 2) and 3) are true, then proceed with Zero-Inflated Negative Binomial model.
Comment: I think you need extra cautions given that the response is measured, not counted. That doesn't rule out these kinds of models, but at least some of the software available may expect integers only. (@Peter Flom's answer is pertinent too.)
Comment: The dependent variable is not a count, so why use such a model? Or are you suggesting that the dependent variable be changed?
Comment: @page An average is not a count.  A count is a non-negative integer.  Averages can be fractional.
Comment: @PeterFlom "Average number of errors" looks like a count - or the average of several counts, that is just the rescaled count in a longer period. Can't it be seen as a Poisson variable? Counting of errors is a usual elementary textbook example of a Poisson process.

Variable with high number of categories


Tobit panel data or panel data with truncated dependent variable

Question: Does anyone know if it is possible to use the Tobit model and the data panels model together, especially in the R language?
I tried the censReg package, but it didn't address the inherent testing of models in data panels.
Comment: Maybe Honoré (1992) Trimmed LAD and least squares estimation of truncated and censored regression models with fixed effects. Implemented in R's plm `pldv` function.
Answer: You can estimate Tobit regresssions with random intercepts with the censReg package and with the pldv command of the plm package.
Comment: Thank you. Do you have any document about It?
Comment: @VitorDeVasconcelosLima You may want to check out the package documentation. If you have the `plm` package installed, run: `?plm::pldv`


While loop until time is reached

Question: I have an application that loops reading a big text file and runs for at least 48 hours.
I would like to stop its execution from 23.00 to 08.00 (11pm to 8am) and then continue its loop during the day.
I tried the following code, but it doesn't exit from the loop.
Edit after Dave Cross' reply
my $min = (localtime)[1];
my $hour = (localtime)[2];

while ( $hour > 18 and $min > 0 ) {
    sleep(1);
    $hour = (localtime)[2];
    $min = (localtime)[1];
}

This doesn't work as expected. Now it's 18:48 and the loop exits immediately unless I use one hour before:
while ( $hour > 17 and $min > 0 )

Comment: `$hour = (localtime)[2]; $min = (localtime)[1];` is a very expensive version of `($hour, $min) = (localtime)[2,1];`
Comment: Also - consider using `alarm`.
Comment: Thank you, edited my code according to Dave' reply.
Comment: @LucasRey: Yes, that should be `$hour >= 18`. Sorry about that.
Answer: You need to check the time more than once :-)
And rather than calling strftime(), why not just use the return value from localtime()?
my $hour = (localtime)[2];

while ($hour >= 23 or $hour < 8) {
  sleep(1);
  $hour = (localtime)[2];
}

Update: A more efficient approach might be to work out how long to sleep() in order to wake up at 8am. A naive approach would be something like this:
if ((localtime)[2]) >= 23) {
  sleep(9 * 60 * 60); # sleep for nine hours
}

Comment: @DaveCross: That would be `$hour >= 23 or $hour < 8`
Comment: @Borodin: Yeah, I was just about to fix that. Thanks.
Comment: Thank you Dave, this works, but with a side effect. $hour > 23 mean I have to wait midnight. I reported my edited code in the first post, but seems doesn't work as expected

While loop until time is reached


Ruby Hash classs method has_key? vs method member?

Question: Is there any difference between the two methods for the Ruby Hash, or is it just "there is more than 1 way to do it"?I could not see any measureable difference between the two.
Thanks,
Comment: FYI `Hash.instance_method(:has_key?) == Hash.instance_method(:member?) #=> true`
Comment: As per https://apidock.com/ruby/Hash/has_key%3F and http://ruby-doc.org/core-2.4.0/Hash.html#method-i-member-3F, they look to return the same results.
Answer: According to the Ruby source, has_key?, key?, include? and member? are the same implementation.
Answer: To see the method definition's source code see documentation, find the method you're looking for then click on the method to expand to see the actual source code:
https://ruby-doc.org/core-2.5.0/Hash.html#method-i-member-3F
    rb_hash_has_key(VALUE hash, VALUE key)
    {
        if (!RHASH(hash)->ntbl)
            return Qfalse;
        if (st_lookup(RHASH(hash)->ntbl, key, 0)) {
            return Qtrue;
        }
        return Qfalse;
    }

https://ruby-doc.org/core-2.5.0/Hash.html#method-i-has_key-3F
    rb_hash_has_key(VALUE hash, VALUE key)
    {
        if (!RHASH(hash)->ntbl)
            return Qfalse;
        if (st_lookup(RHASH(hash)->ntbl, key, 0)) {
            return Qtrue;
        }
        return Qfalse;
    }


Display output from custom module in a panel

Question: How would I output data from a custom module to be displayed in a panel pane?
Comment: http://drupal.org/files/issues/manual_drupal_panels.pdf
Answer: I would recommend using hook_block_info() and hook_block_view() to expose your custom content in a block. This gives you Panels support + contextual links should the need for a form arise, and you can set caching settings for the block.
Comment: But no data can be sent to the code, can it ?
Comment: Certainly it can! Are you getting data from the URL (i.e. ?foo=bar) or from the database or what?
Answer: For my part I create a function that prints or echoes what I want and I simply call it in a PhP block (by using "Add custom content" in Panels) and use PhP filter.
You can call any function defined in your module and send it args the normal way, like
<?php myfunction(%node:nid); ?>
Panels is very handy there, because it gives you all sorts of data to use as arguments. You can do the same with blocks and PhP filter, but without access to data.
Comment: At the shop I work at, we avoid putting PHP into the database wherever possible. Sometimes it's the path of least resistance and it happens, but with version control (everything is in Git) it can prove problematic to split functionality between the codebase and the database.
Comment: thanks. Is this an 'official' way of doing things?
Comment: Yep, but frequently the solution of getting data from URL is irrelevant... :(
Comment: Explain what you mean by getting data from the URL in your original question and I can update my answer. $_GET variables, $GLOBALS, the active menu object (i.e. a node), the current user – all of this and more is available to you.


Polar coordinates injective intervals, help.

Question:
Polar coordinates in plane. Consider the following open set of $\mathbb{R}^2$:
$M=\mathbb{R}^2-\{0,0\}$.
Let $\psi:\mathbb{R}_+\times\mathbb{R}\to M\\(\rho\cos(\theta),\rho\sin(\theta))$

a)
i)$\psi$ is of $C^\infty$ class
ii)$\psi$ is not injective
iii)$\det\nabla(\psi,(\rho\theta))=\rho^2>0$, so $\psi$ is an immersion
b)
Let:
$I_1=]-\pi,\pi[,\:\:\:A_1=\mathbb{R}_+\times I_1,\:\:\:\psi:A_1\to M,(\rho,\theta)\to\psi(\rho,\theta)\\I_2=]0,2\pi[,\:\:\:A_2=\mathbb{R}_+\times I_2,\:\:\:\psi:A_2\to M,(\rho,\theta)\to\psi(\rho,\theta)$.
Therefore:
i)$\psi(A_1)=U_1=\mathbb{R}^2-\{(x,0):x\leqslant 0\}$ is an open set of $M$.
ii)$\psi(A_2)=U_2=\mathbb{R}^2-\{(x,0):x\geqslant 0\}$ is an open set of $M$.
Questions:
1) Why is (0,0) excluded from $\mathbb{R}^2$? If I take $\psi((0,0))=0$. What is the problem? Why $M=\mathbb{R}^2-\{0,0\}$?
2) I do not understand $\psi(A_1)=U_1=\mathbb{R}^2-\{(x,0):x\leqslant 0\}$.
Why is the negative x axis excluded? In the interval $]-\pi,\pi[$, $cos(\theta)$ can be zero. Why exclude the negative part of the x-axis?
Thanks in advance!
Answer: 1) The point $(0,0)$ is excluded because $\psi((0,\theta))=(0,0)$ for each $\theta\in\mathbb{R}$, while we would like that $\psi$ is injective as a map defined on $\mathbb{R}^{+} \times ]0,2\pi[$ (or similar intervals with length $2\pi$, so you can consider for example $]-\pi,\pi[$, if you prefer).
2) The negative axis $\{x\leq 0\}$ is the image of $\mathbb{R}^+ \times \{\pi+2k\pi\}_{k\in\mathbb{Z}}$, but $\pi+2k\pi\notin I_1$ for each $k\in\mathbb{Z}$. A similar argument can be used for $A_2$.
Comment: $\cos(\frac{-4\pi}{3})=-\frac{1}{2}$ and $\frac{-4\pi}{3}\in ]-\pi,\pi[$. How can $x\leqslant 0$ be excluded?
Comment: Actually $-\frac{4\pi}{3}\notin ]-\pi,\pi[$. However, I think I understand your mistake: look, the set you are excluding is $\{x\leq 0, y=0\}$, namely the half-line made of pairs of real numbers which the first coordinate is not positive and the second coordinate is zero. In fact the only $\theta\in\mathbb{R}$ for which their images are on this half-line are actually $\pi+2k\pi$, that are not included in $]-\pi,\pi[$.


Wamp and PhpMyAdmin not working

Question: Following up from this question : Mod Rewrite is giving me a hard time
I'm trying to access phpmyadmin now in Wamp. It gives me a 404 that it isn't even there. I've tried and tried to research this. I don't have skype or anything like it on.
I do have an .htaccess file in my localhost/rs folder from that other question. I've read to change the ports, but it doesn't seem to help.
Thanks!
Answer: I once had an issue where changing the ports would result to not finding phpmyadmin.
turned out, when I tried to surf towars it, it would automatically insert the wrong portnumber after  "127.0.0.1::". Make sure this is the port you set it on in your configuration files.
Make sure your htaccess' rewrite base is ok too. if it's in your "rs" folder, the rewrite base is "/rs/".
and next time, add your .htaccess's codes please.
also make sure it's .htaccess (with the dot)
Comment: But see, I didn't change the ports.
Comment: when I didn't it still happened to me. so your URL doesn't change to 127.0.01::8080?

Wamp and PhpMyAdmin not working


Detecting Clusters of "similar" source codes

Question: Assume I have 400 students (that's in a big university) that have to do a computer science project, and that they have to work alone (no group of students). An example of project could be let "implementing a fast fourier transform algorithm in fortran"  (I know, that doesn't sound sexy but that makes my question simpler). I am the correcter and I want to sent routines to check if there are groups of student that have proposed implementation that are "too similar to be truly independently written".
This is unsupervised search for clusters. I think the question is more about which attributes to use rather than the which clustering algorithm to use. The first thing I would do is a letter by letter histogram. Ideally, since cheaters are smarter than that, I would eventually try well chosen random permutations of letters to see if a good matching of letter's histogram (with permutation) exists. Also that those not explore the structure of the code, only the marginal distribution of letters... what solution do you have ? are there existing software or packages dedicated to that problem ? (actually in my old days computer science teachers claimed they had that type of tool, but I now suspect that they had something very simple)
I guess lawyer from software developments have that type of issues also (not with 1000 students, but with 2 large codes... which makes things harder) ?
Answer: The obvious pre-processing step is to merge files that are truly identical.
After that the key is normalization. At some point, students will start refactoring the code, renaming variables and such. Or reword the comments. A letter histogram is too much affected by this (plus it will capture a lot of the language properties).
A common technique is to use a language-specific parser and transform the source code into an abstract syntax tree. Then extract features from this. And maybe analyze the comments separately in parallel.
Then there's the line-based "longest common subsequence" approach. If you have a reasonably good similarity on single lines, you can search for the longest common subsequence of any two files. This will also yield a number of matches.
Comment: Just wanted to add that the longest common subsequence can be found efficiently using [Suffix trees](http://en.wikipedia.org/wiki/Suffix_tree) or suffix arrays.
Comment: Thanks Anony, I really like the spirit of your answer (and upvoted it). It sounds like true high dimensional statistics with "data trasformation" and search for extreme patterns. What type of distance would you put on those trees ?
Comment: I'm not an expert for similarity of AST representations. I believe there is a notion of "simulation" in the sense that one tree is a special kind of subtree of the other. To compare the ASTs, you'd need to align them and count the relative differences, I guess. Maybe not taking order of branches into account, so trivial code reorderings do not change results. Be aware that you might get to the point where you get false positives because there just are n ways of solving the problem efficiently, and you get false positives just because they found the correct solution...
Answer: From the anti plagiarism world, I previously came across the notion of "Graph Isomorphism". Maybe you can take a look at that too.
LCS - Longest Common Subsequence is possible too. But try to compare all these solutions and see what's the best :)
Comment: Welcome to this site! Could you give some references on the aforementioned work, and maybe more details so that readers could get a better idea of how graph isomorphism or LCS might solve the problem at hand?


$[D,D']$ where $D$ is a derivation and $D'$ is skew

Question: This is a proposition in 33 page of Foundation in Differential Geometry - KN
   I need some detail.
Let $D^r(M)$ be a set of $r$-form. Then derivation (resp. skew-derivation) of degree $k$ is a linear mapping from $D^r(M)$ to $D^{r+k}(M)$
 s.t. $$ D(\omega \wedge \tau ) = D\omega \wedge \tau + \omega \wedge D\tau $$ (resp. $ D(\omega \wedge \tau ) = D\omega \wedge \tau + (-1)^r \omega \wedge D\tau $) where $\omega \in D^r(M)$
Note that ${\bf exterior\ differentiation}$ is skew of degree $1$.
${\bf Question}$ : I wanto prove that $[D,D']$ is skew of degree $k+k'$ where $D$ is derivation of degree $k$ and $D'$ is skew of degree $k'$
${\bf Try}$ : $$ DD' (\omega \wedge \tau ) = D\{ D'\omega \wedge \tau + (-1)^r\omega \wedge D'\tau \} $$ $$ = DD'\omega \wedge \tau + D'\omega \wedge D\tau +(-1)^rD\omega \wedge D'\tau + (-1)^r\omega \wedge D D'\tau$$
$$D'D(\omega \wedge \tau ) = D'\{ D\omega \wedge \tau + \omega \wedge D\tau \} $$ $$ = D'D\omega\wedge \tau +  (-1)^{k+r}D\omega \wedge D'\tau +D'\omega \wedge  D\tau + (-1)^r\omega \wedge D'D\tau
$$
So $$ [D,D'] (\omega \wedge \tau )=[D,D']\omega \wedge \tau + (-1)^r \omega \wedge [D,D']\tau + [(-1)^r - (-1)^{k+r}]D\omega \wedge D'\tau $$
Am I miss something ? Why do not the last term disappear ?
Comment: I have the same problem. I posted the same question, but I am not getting any answers. Did you solve the problem in the meanwhile?
Comment: I add my explanation.
Comment: Note that there is also a similar statement right below concerning DD' + D'D for two skew-derivations whose calculation similarly doesn't seem to yield a skew-derivation as claimed. A similar example shows the failure of that statement.
Answer: 1) When $M$ is Riemannian manifold, if $L$ is a derivation of degree $k$ from $\bigwedge^r(M)$ to
$\bigwedge^{k+r}(M)$, then
$$ L(fdx_i)=L(f)dx_i +f L(dx_i) $$
$$ L(dx_i f)=fL(dx_i) + dx_i L(f) =
f L(dx_i) + (-1)^k L(f) dx_i $$
When $k$ is even, then we are done. If $k$ is odd, then we have $L(f)=0$ for all function $f$.
\begin{align*}L(dx_1dx_2)&
=L(dx_1)dx_2+ dx_1L(dx_2) \\&= dx_2L(dx_1)+ L(dx_2) dx_1\\&=
L(dx_2dx_1)\end{align*} so that $L=0$ on $\bigwedge^{2m}(M)$ for all
$m$.
2) When $M=\mathbb{R}^3$, then assume that $L(f)=0,\ L
(dx_1)=dx_1dx_2,\ L(dx_i)=0,\ i>1$.
Hence $ \omega =dx_1,\ \tau=f$ so that $$ L(\omega) df=
f_{x_3}dx_1dx_2 dx_3 \neq 0 $$
That is, $[L,d]$ is not skew derivation.
Comment: I checked again my answer, I deleted because there are some problems with it. As regards your answer: suppose you work on $\mathbb{R}$. Then the exterior derivative $d$ is a derivation of order $1$, because $d(f(x)dx) = 0$ and $d(fg) = df\cdot g + fdg$. Then your argument does not give any information on $k$, which is actually odd.
Comment: The argument only shows that it is killed by any form of degree 1. Choosing it to be 0 was helpful in constructing a derivation with the required properties. It is still necessary to check that this indeed extends to a derivation (which it does)


For the variable traingle ABC with...

Question: For the variable triangle $ABC$ with fixed vertex at $C(1,2)$ and $A,B$ having co-ordinates $(cos t, sin t), (sin t, -cos t)$ respectively, what is the locus of its centroid?
My Approach:
The coordinate of centroid $O(x ,y )$ in triangle
having $A(a,d ), B(b,e), C(c ,f)$
$$x =\frac {a +b +c}{3}, y=\frac {d + e + f}{3}$$
So coordinate of given triangle is :
$$h=\frac {cost +sint +1}{3}, k =\frac {sint - cost + 2}{3}$$
I got stuck at here. Please help me to continue.
Moreover, What is meant by 'variable triangle'?
Comment: i think since the variable $t$ in the argument of the function this must be eliminated
Comment: Dr. Sonnhard Graubner, How should I do that? Please give some more hints.
Answer: you will get the system
$$3x-1=\sin(t)+\cos(t)$$
$$3y-2=\sin(t)-\cos(t)$$
adding these two equations we get
$$\sin(t)=\frac{3x+3y-3}{2}$$
thus you will get $t$
and analogously $\cos(t)$
and finally you have to calculate $$\sin(t)^2+\cos(t)^2=1$$ with the tems above
Answer: Alternatively, $$3x-1=\sin(t)+\cos(t)$$
$$3y-2=\sin(t)-\cos(t)$$
Squaring and adding gives $$(3x-1)^2+(3y-2)^2=2$$
btw, The triangle is variable because the coordinates change according to the value of $t$

For the variable traingle ABC with...


Kotlin/Native Cinterop With libxml2 - Corrupted XPath Expression

Question: Versions

Kotlin 1.9.22
libxml 2.9.14+dfsg-1.3
OS: Ubuntu 23.10

The Problem
In a small Kotlin/Native application I use cinterop with libxml2 to evaluate a set of XPath expressions to extract element text and attribute values. I thought I had it figured out but after several weeks one of my tests failed "out of the blue": libxml had complained about an invalid XPath. I added a loop around my test code and indeed, given enough iterations, the test always fails. And it always fails on the same XPath expression (out of a set of 4). This is the minimal code I can reproduce the error with:
@OptIn(ExperimentalForeignApi::class)
fun getElementTextFake(xml: String, xPathToNode: String): Either<XmlError, String> {
    val xPathCValues = xPathToNode.encodeToByteArray().toUByteArray().toCValues()
    val doc: xmlDocPtr? = xmlReadDoc(cur = xml.trim().encodeToByteArray().toUByteArray().toCValues(), URL = null, encoding = "UTF-8", options = 0)
    val xPathCtx: xmlXPathContextPtr? = doc?.let { xmlXPathNewContext(doc = it) }
    val xPathObj: xmlXPathObjectPtr? = xPathCtx?.let { xmlXPathEvalExpression(str = xPathCValues, ctxt = it) }
    val nodeSet: xmlNodeSetPtr? = xPathObj?.pointed?.nodesetval

    val result =
        if (nodeSet == null || nodeSet.pointed.nodeNr == 0) ElementNotFound(xPathToNode, xml).left() else "fakeElementText".right()

    xmlXPathFreeObject(xPathObj)
    xmlXPathFreeContext(xPathCtx)
    xmlFreeDoc(doc)

    return result
}

The error printed by libxml2 is
XPath error : Invalid expression

//*[local-name()='request']/*[local-name()='processing']P

The original XPath expression passed in is
//*[local-name()='request']/*[local-name()='processing']

Note the P at the end of the expression string, which makes it invalid. None of my other XPath expressions contain a capital P. The error almost always occurs within a couple hundred iterations.
The test runs single-threaded.
What could be causing the data corruption of the XPath expression string?
Comment: @MartinHonnen, the `*`after the slashes was eaten by the text formatting. I have reformated the question and added the original XPath expression for comparison. That XPath expression, when run in a loop against the same XML document, almost always yields a result, then fails with above error at a random point, but mostly before I reach 200 iterations.
Answer: The problem is be the byte array:
val xPathCValues = xPathToNode.encodeToByteArray().toUByteArray().toCValues()

The xmlChar array has to be 0-terminated so, in the absence of a length parameter in the libxml API, the length of the array can be determined. Adding a a zero element at the end of the array like so fixes the issue:
val xPathCValues = (xPathToNode.encodeToByteArray().toUByteArray() + 0u).toCValues()

The cstr extension property on String returns a CString instance, which extends CValues<ByteVar>. CString adds the trailing 0-byte to the array copied to native memory when asked for a native pointer. Unfortunately there does not seem to exist a CValues<UByteVar> equivalent which is required for libxml's xmlChar.


permitindo acesso ao webserver apenas com android

Question: Galera tenho uma pasta no meu site chamada webserver, dentro dela tenho vários arquivos php que montam o json que é enviado ao meu app que estou montando. Porém eu queria bloquear essa pasta para não ser acessado por nenhum navegador, apenas pelo android. Isso e possível de ser feito via htacess?
Hoje eu configurei o meu htacess para não listar nenhum arquivo dentro da pasta, fiz da seguinte forma:
Options -Indexes

Answer: Para deteção do android, usando htaccess tente:
RewriteEngine On

RewriteCond %{HTTP_USER_AGENT} "android" [NC]
RewriteRule ^(.*)$ /android/$1 [L,QSA] # redirect aqui

RewriteCond %{HTTP_USER_AGENT} "iphone|ipod|ipad|windows" [NC] # redirecao para os outros
RewriteRule ^(.*)$  http://YOU_SHALL_NOT_PASS/$1 [L,QSA]

Mas disse que tinha uns ficheiros php. Eu aproveitava isso, e colocava um primeiro ficheiro com isso, este ficheiro seria o primeiro a ser lido pelo servidor:
$useragent = $_SERVER['HTTP_USER_AGENT'];
$devicesAllowed = array('android' => 'http://www.android.com'); // aqui colocamos os 'aparelhos' admitidos, neste caso é só android com os respetivos url para redireção
foreach($devicesAllowed as $device => $url) {
    if(strpos($useragent, $device) !== false) {
        header('Location:' .$url);
    }
}
header('Location: YOU SHALL NOT PASS'); // redireção para os outros clientes (ios, desktop etc...)

Note que do lado cliente nós podemos falsear isso, existem até plugins/add-ons para navegadores para fazer isso. Não conte como sendo viável a 100%


function in onCreate

Question: i want to know how the function work in onCreate or onCreateView
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book);

        functionOne();
        functionTwo();
}

I want to know that functionOne and functionTwo work parallel or step by step.Thanks
Comment: You can get the answer by yourself by running the values with logcat or using debug  mode
Comment: What prompts you to ask this question? Why would you expect the program to run any other way than line by line?
Comment: you might be new in android , but you should know programmatically concepts. You might not have idea about android, but you must know other languages like java,C,C++ etc. If you know other languages then concepts and flow will be same, it doesnt matter what language you are using. It will be in flow only.
Answer: Clearly you don't quite understand how methods in Java work. functionOne and functionTwo are not "functions", they are methods. Java methods is generally executed one after another. That means when functionOne finishes (returns), functionTwo starts being executed. I said generally because you can create a new thread to execute functionTwo. That way functionTwo is executed asynchronously.

function in onCreate


ASP.NET 2.0 Gridviews and people doing stuff they arent supposed to.

Question: I have a page where a user can enter information into text boxes and upon submitting the information is saved to the database and the information is added to a gridview that they can select and edit the records from.
They shouldnt ever, but if they delete a record hit the back button in a browser and then select the record in the gridview again they are going to get out of range error because the record no longer exists in the database.
So I am looking for ideas on how to best keep this scenario from happening. Any suggestions are appreciated and i will be checking frequently to provide any additional information as I know this might be a little vague.
Answer: You should always handle the case where a user selects a record that does not exist because of the inherit nature of web applications...the data is stale as soon as the user sees it.
Even if the user just displayed the page for the first time it is possible another user deleted the record just after the results were retrieved.
I would suggest checking to see if the record exists, prompting the user in some manner that the data is stale and refresh the list automatically.
Answer: You could temporarily disable the back button with javascript?
http://csharpdotnetfreak.blogspot.com/2009/04/disable-browser-back-button-javascript.html


Content type menu links?

Question: I'm making a site that has three different content types.  I would like a Main-Menu link to each content type.  Additionally, I would like each of these three pages to list recent nodes for that content type, with a link to to that node.  I would think this is pretty standard.
So I've created the content types, and I can click directly to each content type, but I do not know what the "best practice" would be to create these pages.  I could create an override of node--mycontenttype.tpl.php but is this the right way to go?  How would I link to the general page (instead of the specific node)?
Answer: There are many ways to do this. A simple way would be to create a view for each content type and then create menu items for each of them.
Comment: oh derp - I forgot you could create views as actual pages, not just blocks.  Thanks so much.

Content type menu links?


Physiological basis for note durations?

Question: For some reason (probably read something like this a long time ago), I have it in my head that there was some sort of physiological basis for some note durations.
This may have been something like, a whole note (or a breve) is what a singer could be expected to sing with one breath, or a quarter note is related normal breathing/pulse rate etc, or something similar.
The Wikipedia article on tempo indicates

In Renaissance music most music was understood to flow at a tempo defined by the tactus, roughly the rate of the human heartbeat. Which note value corresponded to the tactus was indicated by the mensural time signature.

but I'm suspicious of this (unreferenced) description; my read of it indicates that all Renaissance music would be at (about) 60BPM.
What connections between note durations and physiological features exist in the available historical documentation?
Comment: This question is more about the language/notation/concepts used to refer to music, rather than actual performance.
Comment: In today's parlance; consider the range of durations that a quarter note can represent over the range of pieces in 4/4 time: anywhere from close to 2 seconds (or more) to much much less than 1 second.  The way in which we "make a song go fast" is viewed as shortening all of the notes.  An alternate "conception" would be that instead of shortening all of the notes, instead we making new notes by further dividing of given notes of fixed duration.
Comment: This is all pretty conceptual and some artists and composers may take both of these views over time, but it can be kept objective if the focus is on writings that address this kind of concept.
Comment: I'm also interested if the idea of fixed note durations has cropped up in non-Western musical traditions.
Answer: The basis for note duration is strictly in the context of the piece regardless of any other influences. The time a note is played is relative to the notes preceding it and following it, and if the note is a part of chord etc. The context will determine the physiological influences. There are no rules regarding how long or short a note is to be played other than physical restrictions.
As far as historic documentation, the best source has been Carl Seashore's "Psychology of Music."
This may appear to be a bit dogmatic and I should make some wiggle room here. I think your question is interesting and so are the questions you added in the comments. I am coming at this one as a composer. The main thing I want to convey here is that everything you hear in a piece is relative not absolute. This case of note durations is not so far away from the concept of proportions of shapes in paintings or sculptures or how a director of photography arranges objects in a frame. If we were to attach some psychological basis to note durations we would also have to tweak to include how changes of tempo, change of pitch, texture, and dynamics play a role in this as well and to me that is just something I don't want to think about when composing. What I want to do is get my idea into a sonic form. Perhaps when in the revision stages of writing I might think, geez that note is way too long or not long enough to convey my idea properly, vs my saying to myself, hey that note is way too long or not long enough as it does not meet some psychological criteria.
I think others should offer their opinion on this as well for mine is only one view.
Here's something that might offer some more clues?
http://www.sufimessage.com/music/psychological-influence-of-music.html
Comment: I think the OP means during the Renaissance, not during modern times.
Comment: @filzilla I suspect my question didn't convey my intent very well, but I'll look into the "Psychology of Music".
Answer: It seems that this is a topic that has been debated for some time, since at least the 18th century.  Mattheson (quoted in Anthony Newman) suggests that tactus is indeed related to heartbeat.  He further says that systolic and diastolic 'beats' can be thought of as up and down beats, as in a 2/2 time signature or similar.
This might have some truth in it, but there are other possible explanations:
The natural inclination to have strong and weak beats originated in poetry and the tendency for language to have stresses on particular syllables.
Perhaps the most interesting idea, again from Newman, referencing an organist called Alden Gilchrist:

It is of interest to note that in elaborate Renaissance vocal music the tactus must be either 60, for duple meter, or 80, for triple meter.  The reason we can know this with such certainty is that there is a certain laryngeal technique for producing a rapid series of notes which will only work at one speed, with only the slightest variation for individual differences.  This is sometimes called the "trillo technique", or the "chuckle technique".  The intrinsic value of the notes produces in this way is always the same.  When they fall into groups of eight, the tactus is 60, and when they fall into groups of six, the tactus is 80.

So the rate at which singers can do a "trillo" or "Monteverdi Trill" governed tempi for different meters: a physiological constraint on tempo.
Answer: I'm not a huge classical music fan, but I think your suspicion is probably unfounded: Average resting heart rate is in the mid 70s for most people, which is not outside the range of classical music (Adagio - Adagietto).
Heart rate can go up just as a psychological response (excitement, nervousness), emotions which many pieces of music are designed to inspire. Plenty of rousing military-themed pieces have sections where the temp speeds up as the excitement builds, which may be (intentionally or unintentionally) related to heart beat.
Heart rate can also go up quickly with any moderate activity, for example dancing. A reasonably fit person might have a heartbeat between 90 and 110 bpm when dancing a waltz, which is close to the tempo of the music (waltzes are often around 100bpm).
Another physiological reason for a specific beat rate might be that music is related to the speed at which people dance - some speeds are more comfortable than others, depending on your mass/inertia, agility and strength. If the music is too slow, you might have balance problems (need to put your feet down too soon). Too fast, and you just can't keep up (although some people seem to manage). A fast Lindy hop (ok, this isn't classical, but the principles will still apply) might be 150bpm. That's really fast, for even a really fit, agile human. If you go to a Drum and Bass gig (~160bpm), you'll notice that everyone is actually dancing pretty slowly - at half time, 80bpm - because it's basically impossible to dance at 160 for more than a few seconds in any enjoyable way (unless you're jacked up on something, perhaps).
It's also worth noting that your breathing rate is affected by your pace - when walking you usually breath once per step, when jogging or running, this might go up to 2 or 4 times per step, depending on how fit you are. The same happens while dancing, and that will affect what tempos are comfortable for dancing.
Not that not all of this is necessarily conscious design on the part of the composer - there's an evolutionary process at work in music. If a song is enjoyable (for what ever reason, many of which will be physiological), it will be more popular, and more composers will be inclined to emulate it. That's a major part of the reason that most pop music doesn't go much outside the range of 80-110bpm.
Comment: Before voting on this answer (which is largely unreferenced opinion), check out some of the answers on http://music.stackexchange.com/questions/7064/physiological-responses-to-different-rhythms?lq=1, which argue that mostly it's not physiological.

Physiological basis for note durations?


Approximating radicals using Binomial theorem

Question: Use a suitable binomial expansion to find square root of $1.01$ and correct it to five decimal places. I use the formula
$$(1+ax)= 1+ax + \frac{a(a-1)}{2!} + \cdots$$
but do not know where to stop.
Comment: I suppose that the lhs is $(1+x)^a$ and not $(1+ax)$
Comment: use the remainder of taylor's theorem and find n if you know the tolerance beforehand.
Answer: At each step, the coefficient multiplies by a certain amount. Past a certain point you can tell that the coefficient will always be less than some $c$ in magnitude, so the remainder would have magnitude less than $c ( x^k + x^{k+1} + \cdots ) = c \dfrac{x^k}{1-x}$. Using that you can determine when you are close enough.


Error:Execution failed for task ':app:dexDebug'. com.android.ide.common.internal.LoggedErrorException: Failed to run command:

Question: Error:Execution failed for task ':app:dexDebug'.
 com.android.ide.common.internal.LoggedErrorException: Failed to run command:
    C:\Users\xxx\AppData\Local\Android\sdk\build-tools\21.1.2\dx.bat --dex --no-optimize --multi-dex --main-dex-list C:\___\android\GooglePlus_1\app\build\intermediates\multi-dex\debug\maindexlist.txt --output C:\___\android\GooglePlus_1\app\build\intermediates\dex\debug --input-list=C:\___\android\GooglePlus_1\app\build\intermediates\tmp\dex\debug\inputList.txt
Error Code:
    3

UNEXPECTED TOP-LEVEL ERROR:
    java.lang.OutOfMemoryError: Java heap space
        at com.android.dx.dex.code.RopTranslator.outputBlock(RopTranslator.java:253)
        at com.android.dx.dex.code.RopTranslator.outputInstructions(RopTranslator.java:233)
        at com.android.dx.dex.code.RopTranslator.translateAndGetResult(RopTranslator.java:212)
        at com.android.dx.dex.code.RopTranslator.translate(RopTranslator.java:105)
        at com.android.dx.dex.cf.CfTranslator.processMethods(CfTranslator.java:317)
        at com.android.dx.dex.cf.CfTranslator.translate0(CfTranslator.java:137)
        at com.android.dx.dex.cf.CfTranslator.translate(CfTranslator.java:93)
        at com.android.dx.command.dexer.Main.processClass(Main.java:729)
        at com.android.dx.command.dexer.Main.processFileBytes(Main.java:673)
        at com.android.dx.command.dexer.Main.access$300(Main.java:83)
        at com.android.dx.command.dexer.Main$1.processFileBytes(Main.java:602)
        at com.android.dx.cf.direct.ClassPathOpener.processArchive(ClassPathOpener.java:284)
        at com.android.dx.cf.direct.ClassPathOpener.processOne(ClassPathOpener.java:166)
        at com.android.dx.cf.direct.ClassPathOpener.process(ClassPathOpener.java:144)
        at com.android.dx.command.dexer.Main.processOne(Main.java:632)
        at com.android.dx.command.dexer.Main.processAllFiles(Main.java:505)
        at com.android.dx.command.dexer.Main.runMultiDex(Main.java:334)
        at com.android.dx.command.dexer.Main.run(Main.java:244)
        at com.android.dx.command.dexer.Main.main(Main.java:215)
        at com.android.dx.command.Main.main(Main.java:106)

Gradle file:
    apply plugin: 'com.android.application'

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"

    defaultConfig {
        applicationId "com.googleplus_1"
        minSdkVersion 10
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
        multiDexEnabled = true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:appcompat-v7:22.0.0'
    compile 'com.google.android.gms:play-services:7.0.0'
    compile 'com.google.gdata:core:1.47.1'
}
/*
configurations {
    all*.exclude group: 'com.android.support', module: 'support-v4'
}

configurations {
    all*.exclude group: 'com.android.support', module: 'support-v4'
    all*.exclude group: 'com.google.android.gms', module: 'play-services'
}*/

Comment: You don't have enough Java heap space. Have you changed the VM settings?
Comment: No I did not change.
For some reason now I am getting a diff error msg.
Error:Execution failed for task ':app:dexDebug'.
> com.android.ide.common.internal.LoggedErrorException: Failed to run command:
 C:\Users\bhurata\AppData\Local\Android\sdk\build-tools\21.1.2\dx.bat --dex --no-optimize --multi-dex --main-dex-list C:\___\android\GooglePlus_1\app\build\intermediates\multi-dex\debug\maindexlist.txt --output C:\___\android\GooglePlus_1\app\build\intermediates\dex\debug --input-list=C:\___\android\GooglePlus_1\app\build\intermediates\tmp\dex\debug\inputList.txt
Error Code:
 3
Comment: I have no idea, sorry...
Comment: I figure out that adding this:
        compile 'com.google.gdata:core:1.47.1'
is causing the issue. Any ideas ?
Answer: Why are you adding com.google.gdata:core:1.47.1?
If you read on it's official site: http://code.google.com/p/gdata-java-client/, it says:

Android support: If you are developing for Android and the Google API you want to use is included in the Google Play Services library,
  you should use that library for the best performance and experience.
  If the Google API you want to use with Android is not part of the
  Google Play Services library, you can use the Google APIs Client
  Library for Java, which supports Android 1.5 (or higher) and provides
  other features such as OAuth 2.0 and Maven.

It suggests you use:
  repositories {
      mavenCentral()
  }

  dependencies {
      compile 'com.google.api-client:google-api-client:1.18.0-rc'
  }

Very important for Google Play Services, do not use the "whole" dependency directly:
dependencies {
    compile 'com.google.android.gms:play-services:7.0.0'
}

Do pick individual modules that you need:
dependencies {
    # Google+
    com.google.android.gms:play-services-plus:7.0.0
    # Google Account Login
    com.google.android.gms:play-services-identity:7.0.0
    # Google Actions, Base Client Library
    com.google.android.gms:play-services-base:7.0.0
    # Google App Indexing
    com.google.android.gms:play-services-appindexing:7.0.0
    # Google Analytics
    com.google.android.gms:play-services-analytics:7.0.0
    # Google Cast
    com.google.android.gms:play-services-cast:7.0.0
    # Google Cloud Messaging
    com.google.android.gms:play-services-gcm:7.0.0
    # Google Drive
    com.google.android.gms:play-services-drive:7.0.0
    # Google Fit
    com.google.android.gms:play-services-fitness:7.0.0
    # Google Location, Activity Recognition, and Places
    com.google.android.gms:play-services-location:7.0.0
    # Google Maps
    com.google.android.gms:play-services-maps:7.0.0
    # Google Mobile Ads
    com.google.android.gms:play-services-ads:7.0.0
    # Google Nearby
    com.google.android.gms:play-services-nearby:7.0.0
    # Google Panorama Viewer
    com.google.android.gms:play-services-panorama:7.0.0
    # Google Play Game services
    com.google.android.gms:play-services-games:7.0.0
    # SafetyNet
    com.google.android.gms:play-services-safetynet:7.0.0
    # Google Wallet
    com.google.android.gms:play-services-wallet:7.0.0
    # Android Wear
    com.google.android.gms:play-services-wearable:7.0.0
}

Source: http://developer.android.com/google/play-services/setup.html
Comment: Jared, many thanks for answer. I will answer your question:
"Why are you adding com.google.gdata:core:1.47.1?" : I am using this to access Albums from PIcasa (Google+).

Also, the error went away when I included the individual modules.
Comment: @GreenApple Good! I believe that the library was so large, it was taking up a lot your computer's memory.


Determine the mod 5^3 roots of F(X) = 5X^3 + X^2 - 1 using Hensel's lemma

Question: Determine the mod 5^3 roots of F(X) = 5X^3 + X^2 - 1 using Hensel's lemma.
So far I have:
F'(X) = 15X^2 + 2X.
The mod 5 roots of F(X) are 1 and 4, bc 5|F(1)=5 & 5|F(4)=335
so the next step is to see if I can perform a lift to find the roots mod 5^2.
5 does not divide F'(1)=17
and
5 does not divide F'(4)=248
so I believe this means I cannot perform a lift on either of these roots,
does this mean there are no mod 5^3 roots of F(X) = 5X^3 + X^2 - 1 ?
Thank you
Comment: Welcome to Math.SE! Please take a look at http://math.stackexchange.com/help/notation to see how to use MathJax to properly typeset equations here. Note that a quick check shows that the only two roots in $\mathbb Z_{5^3}$ are $x=59$ and $x=61$. The MATLAB-Script to get these is `find(mod(5*(0:124).^3 + (0:124).^2 - 1, 125) == 0) - 1`
Answer: ok so I discovered that when 5 does not divide F'(1) it is known that:
there exists some integer t such that F(1+5t) is a multiple of 5^2.
in this case t=2, F(11)=6775 which is a multiple of 25,
the there is an int t such that F(11+t*5^2) is a multiple of 125
again t=2, F(61)=1138625 is a multiple of 125, so 61 is a root.
Using the same process for F(4) gives the other root which is 59.


Global handling exception in WPF app with Caliburn.Micro

Question: Hi I try implement solution from this site im my WPF app for global exception handling.
http://www.codeproject.com/Articles/90866/Unhandled-Exception-Handler-For-WPF-Applications.aspx
I use Caliburn Micro as MVVM framework. Service I have in external assembly and it is injected in view model class with MEF.
Here is my implementation for global exception handling in WPF app.
App.xaml
         DispatcherUnhandledException="Application_DispatcherUnhandledException"
         Startup="Application_Startup"

App class:
public partial class App : Application
{
    private IMessageBox _msgBox = new MessageBoxes.MessageBoxes();

    public bool DoHandle { get; set; }

    private void Application_Startup(object sender, StartupEventArgs e)
    {
        AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
    }

    private void Application_DispatcherUnhandledException(object sender,
                           System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
    {
        if (DoHandle)
        {
            _msgBox.ShowException(e.Exception);
             e.Handled = true;
        }
        else
        {
            _msgBox.ShowException(e.Exception);
            e.Handled = false;
        }
    }

    void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
        var ex = e.ExceptionObject as Exception;
        _msgBox.ShowException(ex);
    }

}

Service method from external assembly:
    public void ServiceLogOn()
    {
        try
        {

        }
        catch (Exception ex)
        {

            throw ex;
        }
    }

This service method is call in view model class for example on button click event:
    [Export(typeof(ILogOnViewModel))]
    public class LogOnViewModel : Screen, ILogOnViewModel
    {
        public void LogOn()
        {
            _service.ServiceLogOn();
        }
    }

I run WPF app in Visual Studio and produce exception with message "Bad credentials" in ServiceLogOn method.
I expect that I see the message box with the exception.
But Visual Studio stop debuging app and show exception in service method in service project.
So I try run WPF from exe file and produce same exception in ServiceLogOn method.
I get this error:
Exception has been throw by target of an invocation.

Any exception from view model class is not handled in methods:

Application_DispatcherUnhandledException
or CurrentDomain_UnhandledException.

in App class.
What I do bad?
EDITED with Simon Fox's answer.
I try implement in MEF bootstraper advice of Simon Fox's, but I still something do wrong.
I move handle logic for exception to OnUnhandledException method in bootstraper class.
Here is my code from bootstraper class:
 public class MefBootStrapper : Bootstrapper<IShellViewModel>
    {
//...
    private IMessageBox _msgBox = new MessageBoxes.MessageBoxes();

    public bool DoHandle { get; set; }

    protected override void OnUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
    {
        if (DoHandle)
        {
            _msgBox.ShowException(e.Exception);
            e.Handled = true;
        }
        else
        {
            _msgBox.ShowException(e.Exception);
            e.Handled = false;
        }

    }
//...
    }

I bind some method from view model on button and throw new exception. Something like this:
public void LogOn()
{
    throw new ArgumentException("Bad argument");
}

But result is sam, I test app out of Visual Studio and get this exception.
Exception has been throw by target of an invocation.
Comment: the sample you provided works fine for me. If you run the sample from visual studio without debugging (Ctrl+F5) you should get the desired result. The other exception is only displayed when the debugger is attached and if you continue execution you will eventually get to the `OnUnhandledException override`
Comment: Does the Exception have an InnerException, if so what is it? Can you post the StackTrace contained in the exception?
Comment: Hi Simon, Inner exception is null, if I check in Visual Studio, the code in method OnUnhandledException is note executed.
Comment: Simon I make simple sample, if  you want you can try ut. Here is it:http://cid-042424ddb4d5fcbf.office.live.com/self.aspx/MSDN/MVVM%5E_and%5E_global%5E_exceptions%5E_handling.7z
Comment: Thank, Simon, I have problem with Visual Studio :)
Answer: Caliburn.Micro has built in support for hooking unhandled exceptions. The Bootstrapper class (which every Caliburn project requires) sets this up for you and provides the virtual OnUnhandledException method.
In your custom BootStrapper you must override OnUnhandledException to perform any custom actions for unhandled exceptions in your app. Note that you will most likely have to marshal actions such as displaying a message box to the UI thread (Caliburn enables this easily via Execute.OnUIThread).
You may also have an issue in the way your service moves exceptions to the client, but without any details of how the service is implemented/hosted/etc I cannot help. Are you using WCF to do SOAP? Are you using FaultContracts?
Comment: Hi Simon, I am  not using SOAP or REST Web Services, it is only HTTP POST/GET communication, no SOAP /JSON. I edited my question, see it.
Comment: This answer is right. However it didn't work for me since the exception wasn't thrown from the UI thread. I was using `Task`s so I derived from this answer suggesting the use of [Task.ContinueWith](http://stackoverflow.com/a/7297904/448232)